Make RnExpr warning-free
[ghc-hetmet.git] / compiler / rename / RnExpr.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section[RnExpr]{Renaming of expressions}
5
6 Basically dependency analysis.
7
8 Handles @Match@, @GRHSs@, @HsExpr@, and @Qualifier@ datatypes.  In
9 general, all of these functions return a renamed thing, and a set of
10 free variables.
11
12 \begin{code}
13 module RnExpr (
14         rnLExpr, rnExpr, rnStmts
15    ) where
16
17 #include "HsVersions.h"
18
19 #ifdef GHCI
20 import {-# SOURCE #-} TcSplice( runQuasiQuoteExpr )
21 #endif  /* GHCI */
22
23 import RnSource  ( rnSrcDecls, rnSplice, checkTH ) 
24 import RnBinds   ( rnLocalBindsAndThen, rnValBindsLHS, rnValBindsRHS,
25                    rnMatchGroup, makeMiniFixityEnv) 
26 import HsSyn
27 import TcRnMonad
28 import RnEnv
29 import RnTypes          ( rnHsTypeFVs, 
30                           mkOpFormRn, mkOpAppRn, mkNegAppRn, checkSectionPrec)
31 import RnPat            (rnQuasiQuote, rnOverLit, rnPatsAndThen_LocalRightwards, rnBindPat,
32                          localRecNameMaker, rnLit,
33                          rnHsRecFields_Con, rnHsRecFields_Update, checkTupSize)
34 import DynFlags         ( DynFlag(..) )
35 import BasicTypes       ( FixityDirection(..) )
36 import PrelNames        ( thFAKE, hasKey, assertIdKey, assertErrorName,
37                           loopAName, choiceAName, appAName, arrAName, composeAName, firstAName,
38                           negateName, thenMName, bindMName, failMName, groupWithName )
39
40 import Name
41 import NameSet
42 import RdrName
43 import LoadIface        ( loadInterfaceForName )
44 import UniqSet
45 import List             ( nub )
46 import Util             ( isSingleton )
47 import ListSetOps       ( removeDups )
48 import Maybes           ( expectJust )
49 import Outputable
50 import SrcLoc
51 import FastString
52
53 import List             ( unzip4 )
54 import Control.Monad
55 \end{code}
56
57
58 \begin{code}
59 -- XXX
60 thenM :: Monad a => a b -> (b -> a c) -> a c
61 thenM = (>>=)
62
63 thenM_ :: Monad a => a b -> a c -> a c
64 thenM_ = (>>)
65
66 returnM :: Monad m => a -> m a
67 returnM = return
68
69 mappM :: (Monad m) => (a -> m b) -> [a] -> m [b]
70 mappM = mapM
71
72 checkM :: Monad m => Bool -> m () -> m ()
73 checkM = unless
74 \end{code}
75
76 %************************************************************************
77 %*                                                                      *
78 \subsubsection{Expressions}
79 %*                                                                      *
80 %************************************************************************
81
82 \begin{code}
83 rnExprs :: [LHsExpr RdrName] -> RnM ([LHsExpr Name], FreeVars)
84 rnExprs ls = rnExprs' ls emptyUniqSet
85  where
86   rnExprs' [] acc = returnM ([], acc)
87   rnExprs' (expr:exprs) acc
88    = rnLExpr expr               `thenM` \ (expr', fvExpr) ->
89
90         -- Now we do a "seq" on the free vars because typically it's small
91         -- or empty, especially in very long lists of constants
92     let
93         acc' = acc `plusFV` fvExpr
94     in
95     (grubby_seqNameSet acc' rnExprs') exprs acc'        `thenM` \ (exprs', fvExprs) ->
96     returnM (expr':exprs', fvExprs)
97
98 -- Grubby little function to do "seq" on namesets; replace by proper seq when GHC can do seq
99 grubby_seqNameSet :: UniqSet Name -> a -> a
100 grubby_seqNameSet ns result | isEmptyUniqSet ns = result
101                             | otherwise    = result
102 \end{code}
103
104 Variables. We look up the variable and return the resulting name. 
105
106 \begin{code}
107 rnLExpr :: LHsExpr RdrName -> RnM (LHsExpr Name, FreeVars)
108 rnLExpr = wrapLocFstM rnExpr
109
110 rnExpr :: HsExpr RdrName -> RnM (HsExpr Name, FreeVars)
111
112 rnExpr (HsVar v)
113   = do name           <- lookupOccRn v
114        ignore_asserts <- doptM Opt_IgnoreAsserts
115        finish_var ignore_asserts name
116   where
117     finish_var ignore_asserts name
118         | ignore_asserts || not (name `hasKey` assertIdKey)
119         = return (HsVar name, unitFV name)
120         | otherwise
121         = do { (e, fvs) <- mkAssertErrorExpr
122              ; return (e, fvs `addOneFV` name) }
123
124 rnExpr (HsIPVar v)
125   = newIPNameRn v               `thenM` \ name ->
126     returnM (HsIPVar name, emptyFVs)
127
128 rnExpr (HsLit lit@(HsString s))
129   = do {
130          opt_OverloadedStrings <- doptM Opt_OverloadedStrings
131        ; if opt_OverloadedStrings then
132             rnExpr (HsOverLit (mkHsIsString s placeHolderType))
133          else -- Same as below
134             rnLit lit           `thenM_`
135             returnM (HsLit lit, emptyFVs)
136        }
137
138 rnExpr (HsLit lit) 
139   = rnLit lit           `thenM_`
140     returnM (HsLit lit, emptyFVs)
141
142 rnExpr (HsOverLit lit) 
143   = rnOverLit lit               `thenM` \ (lit', fvs) ->
144     returnM (HsOverLit lit', fvs)
145
146 rnExpr (HsApp fun arg)
147   = rnLExpr fun         `thenM` \ (fun',fvFun) ->
148     rnLExpr arg         `thenM` \ (arg',fvArg) ->
149     returnM (HsApp fun' arg', fvFun `plusFV` fvArg)
150
151 rnExpr (OpApp e1 op _ e2) 
152   = rnLExpr e1                          `thenM` \ (e1', fv_e1) ->
153     rnLExpr e2                          `thenM` \ (e2', fv_e2) ->
154     rnLExpr op                          `thenM` \ (op'@(L _ (HsVar op_name)), fv_op) ->
155
156         -- Deal with fixity
157         -- When renaming code synthesised from "deriving" declarations
158         -- we used to avoid fixity stuff, but we can't easily tell any
159         -- more, so I've removed the test.  Adding HsPars in TcGenDeriv
160         -- should prevent bad things happening.
161     lookupFixityRn op_name              `thenM` \ fixity ->
162     mkOpAppRn e1' op' fixity e2'        `thenM` \ final_e -> 
163
164     returnM (final_e,
165               fv_e1 `plusFV` fv_op `plusFV` fv_e2)
166
167 rnExpr (NegApp e _)
168   = rnLExpr e                   `thenM` \ (e', fv_e) ->
169     lookupSyntaxName negateName `thenM` \ (neg_name, fv_neg) ->
170     mkNegAppRn e' neg_name      `thenM` \ final_e ->
171     returnM (final_e, fv_e `plusFV` fv_neg)
172
173 rnExpr (HsPar e)
174   = rnLExpr e           `thenM` \ (e', fvs_e) ->
175     returnM (HsPar e', fvs_e)
176
177 -- Template Haskell extensions
178 -- Don't ifdef-GHCI them because we want to fail gracefully
179 -- (not with an rnExpr crash) in a stage-1 compiler.
180 rnExpr e@(HsBracket br_body)
181   = checkTH e "bracket"         `thenM_`
182     rnBracket br_body           `thenM` \ (body', fvs_e) ->
183     returnM (HsBracket body', fvs_e)
184
185 rnExpr (HsSpliceE splice)
186   = rnSplice splice             `thenM` \ (splice', fvs) ->
187     returnM (HsSpliceE splice', fvs)
188
189 #ifndef GHCI
190 rnExpr e@(HsQuasiQuoteE _) = pprPanic "Cant do quasiquotation without GHCi" (ppr e)
191 #else
192 rnExpr (HsQuasiQuoteE qq)
193   = rnQuasiQuote qq             `thenM` \ (qq', fvs_qq) ->
194     runQuasiQuoteExpr qq'       `thenM` \ (L _ expr') ->
195     rnExpr expr'                `thenM` \ (expr'', fvs_expr) ->
196     returnM (expr'', fvs_qq `plusFV` fvs_expr)
197 #endif  /* GHCI */
198
199 rnExpr section@(SectionL expr op)
200   = rnLExpr expr                `thenM` \ (expr', fvs_expr) ->
201     rnLExpr op                  `thenM` \ (op', fvs_op) ->
202     checkSectionPrec InfixL section op' expr' `thenM_`
203     returnM (SectionL expr' op', fvs_op `plusFV` fvs_expr)
204
205 rnExpr section@(SectionR op expr)
206   = rnLExpr op                                  `thenM` \ (op',   fvs_op) ->
207     rnLExpr expr                                        `thenM` \ (expr', fvs_expr) ->
208     checkSectionPrec InfixR section op' expr'   `thenM_`
209     returnM (SectionR op' expr', fvs_op `plusFV` fvs_expr)
210
211 rnExpr (HsCoreAnn ann expr)
212   = rnLExpr expr `thenM` \ (expr', fvs_expr) ->
213     returnM (HsCoreAnn ann expr', fvs_expr)
214
215 rnExpr (HsSCC lbl expr)
216   = rnLExpr expr                `thenM` \ (expr', fvs_expr) ->
217     returnM (HsSCC lbl expr', fvs_expr)
218 rnExpr (HsTickPragma info expr)
219   = rnLExpr expr                `thenM` \ (expr', fvs_expr) ->
220     returnM (HsTickPragma info expr', fvs_expr)
221
222 rnExpr (HsLam matches)
223   = rnMatchGroup LambdaExpr matches     `thenM` \ (matches', fvMatch) ->
224     returnM (HsLam matches', fvMatch)
225
226 rnExpr (HsCase expr matches)
227   = rnLExpr expr                        `thenM` \ (new_expr, e_fvs) ->
228     rnMatchGroup CaseAlt matches        `thenM` \ (new_matches, ms_fvs) ->
229     returnM (HsCase new_expr new_matches, e_fvs `plusFV` ms_fvs)
230
231 rnExpr (HsLet binds expr)
232   = rnLocalBindsAndThen binds           $ \ binds' ->
233     rnLExpr expr                         `thenM` \ (expr',fvExpr) ->
234     returnM (HsLet binds' expr', fvExpr)
235
236 rnExpr (HsDo do_or_lc stmts body _)
237   = do  { ((stmts', body'), fvs) <- rnStmts do_or_lc stmts $
238                                     rnLExpr body
239         ; return (HsDo do_or_lc stmts' body' placeHolderType, fvs) }
240
241 rnExpr (ExplicitList _ exps)
242   = rnExprs exps                        `thenM` \ (exps', fvs) ->
243     returnM  (ExplicitList placeHolderType exps', fvs)
244
245 rnExpr (ExplicitPArr _ exps)
246   = rnExprs exps                        `thenM` \ (exps', fvs) ->
247     returnM  (ExplicitPArr placeHolderType exps', fvs)
248
249 rnExpr (ExplicitTuple exps boxity)
250   = checkTupSize (length exps)                  `thenM_`
251     rnExprs exps                                `thenM` \ (exps', fvs) ->
252     returnM (ExplicitTuple exps' boxity, fvs)
253
254 rnExpr (RecordCon con_id _ rbinds)
255   = do  { conname <- lookupLocatedOccRn con_id
256         ; (rbinds', fvRbinds) <- rnHsRecFields_Con conname rnLExpr rbinds
257         ; return (RecordCon conname noPostTcExpr rbinds', 
258                   fvRbinds `addOneFV` unLoc conname) }
259
260 rnExpr (RecordUpd expr rbinds _ _ _)
261   = do  { (expr', fvExpr) <- rnLExpr expr
262         ; (rbinds', fvRbinds) <- rnHsRecFields_Update rnLExpr rbinds
263         ; return (RecordUpd expr' rbinds' [] [] [], 
264                   fvExpr `plusFV` fvRbinds) }
265
266 rnExpr (ExprWithTySig expr pty)
267   = do  { (pty', fvTy) <- rnHsTypeFVs doc pty
268         ; (expr', fvExpr) <- bindSigTyVarsFV (hsExplicitTvs pty') $
269                              rnLExpr expr
270         ; return (ExprWithTySig expr' pty', fvExpr `plusFV` fvTy) }
271   where 
272     doc = text "In an expression type signature"
273
274 rnExpr (HsIf p b1 b2)
275   = rnLExpr p           `thenM` \ (p', fvP) ->
276     rnLExpr b1          `thenM` \ (b1', fvB1) ->
277     rnLExpr b2          `thenM` \ (b2', fvB2) ->
278     returnM (HsIf p' b1' b2', plusFVs [fvP, fvB1, fvB2])
279
280 rnExpr (HsType a)
281   = rnHsTypeFVs doc a   `thenM` \ (t, fvT) -> 
282     returnM (HsType t, fvT)
283   where 
284     doc = text "In a type argument"
285
286 rnExpr (ArithSeq _ seq)
287   = rnArithSeq seq       `thenM` \ (new_seq, fvs) ->
288     returnM (ArithSeq noPostTcExpr new_seq, fvs)
289
290 rnExpr (PArrSeq _ seq)
291   = rnArithSeq seq       `thenM` \ (new_seq, fvs) ->
292     returnM (PArrSeq noPostTcExpr new_seq, fvs)
293 \end{code}
294
295 These three are pattern syntax appearing in expressions.
296 Since all the symbols are reservedops we can simply reject them.
297 We return a (bogus) EWildPat in each case.
298
299 \begin{code}
300 rnExpr e@EWildPat      = patSynErr e
301 rnExpr e@(EAsPat {})   = patSynErr e
302 rnExpr e@(EViewPat {}) = patSynErr e
303 rnExpr e@(ELazyPat {}) = patSynErr e
304 \end{code}
305
306 %************************************************************************
307 %*                                                                      *
308         Arrow notation
309 %*                                                                      *
310 %************************************************************************
311
312 \begin{code}
313 rnExpr (HsProc pat body)
314   = newArrowScope $
315     rnPatsAndThen_LocalRightwards ProcExpr [pat] $ \ [pat'] ->
316     rnCmdTop body                `thenM` \ (body',fvBody) ->
317     returnM (HsProc pat' body', fvBody)
318
319 rnExpr (HsArrApp arrow arg _ ho rtl)
320   = select_arrow_scope (rnLExpr arrow)  `thenM` \ (arrow',fvArrow) ->
321     rnLExpr arg                         `thenM` \ (arg',fvArg) ->
322     returnM (HsArrApp arrow' arg' placeHolderType ho rtl,
323              fvArrow `plusFV` fvArg)
324   where
325     select_arrow_scope tc = case ho of
326         HsHigherOrderApp -> tc
327         HsFirstOrderApp  -> escapeArrowScope tc
328
329 -- infix form
330 rnExpr (HsArrForm op (Just _) [arg1, arg2])
331   = escapeArrowScope (rnLExpr op)
332                         `thenM` \ (op'@(L _ (HsVar op_name)),fv_op) ->
333     rnCmdTop arg1       `thenM` \ (arg1',fv_arg1) ->
334     rnCmdTop arg2       `thenM` \ (arg2',fv_arg2) ->
335
336         -- Deal with fixity
337
338     lookupFixityRn op_name              `thenM` \ fixity ->
339     mkOpFormRn arg1' op' fixity arg2'   `thenM` \ final_e -> 
340
341     returnM (final_e,
342               fv_arg1 `plusFV` fv_op `plusFV` fv_arg2)
343
344 rnExpr (HsArrForm op fixity cmds)
345   = escapeArrowScope (rnLExpr op)       `thenM` \ (op',fvOp) ->
346     rnCmdArgs cmds                      `thenM` \ (cmds',fvCmds) ->
347     returnM (HsArrForm op' fixity cmds', fvOp `plusFV` fvCmds)
348
349 rnExpr other = pprPanic "rnExpr: unexpected expression" (ppr other)
350         -- HsWrap
351 \end{code}
352
353
354 %************************************************************************
355 %*                                                                      *
356         Arrow commands
357 %*                                                                      *
358 %************************************************************************
359
360 \begin{code}
361 rnCmdArgs :: [LHsCmdTop RdrName] -> RnM ([LHsCmdTop Name], FreeVars)
362 rnCmdArgs [] = returnM ([], emptyFVs)
363 rnCmdArgs (arg:args)
364   = rnCmdTop arg        `thenM` \ (arg',fvArg) ->
365     rnCmdArgs args      `thenM` \ (args',fvArgs) ->
366     returnM (arg':args', fvArg `plusFV` fvArgs)
367
368 rnCmdTop :: LHsCmdTop RdrName -> RnM (LHsCmdTop Name, FreeVars)
369 rnCmdTop = wrapLocFstM rnCmdTop'
370  where
371   rnCmdTop' (HsCmdTop cmd _ _ _) 
372    = rnLExpr (convertOpFormsLCmd cmd) `thenM` \ (cmd', fvCmd) ->
373      let 
374         cmd_names = [arrAName, composeAName, firstAName] ++
375                     nameSetToList (methodNamesCmd (unLoc cmd'))
376      in
377         -- Generate the rebindable syntax for the monad
378      lookupSyntaxTable cmd_names        `thenM` \ (cmd_names', cmd_fvs) ->
379
380      returnM (HsCmdTop cmd' [] placeHolderType cmd_names', 
381              fvCmd `plusFV` cmd_fvs)
382
383 ---------------------------------------------------
384 -- convert OpApp's in a command context to HsArrForm's
385
386 convertOpFormsLCmd :: LHsCmd id -> LHsCmd id
387 convertOpFormsLCmd = fmap convertOpFormsCmd
388
389 convertOpFormsCmd :: HsCmd id -> HsCmd id
390
391 convertOpFormsCmd (HsApp c e) = HsApp (convertOpFormsLCmd c) e
392 convertOpFormsCmd (HsLam match) = HsLam (convertOpFormsMatch match)
393 convertOpFormsCmd (OpApp c1 op fixity c2)
394   = let
395         arg1 = L (getLoc c1) $ HsCmdTop (convertOpFormsLCmd c1) [] placeHolderType []
396         arg2 = L (getLoc c2) $ HsCmdTop (convertOpFormsLCmd c2) [] placeHolderType []
397     in
398     HsArrForm op (Just fixity) [arg1, arg2]
399
400 convertOpFormsCmd (HsPar c) = HsPar (convertOpFormsLCmd c)
401
402 convertOpFormsCmd (HsCase exp matches)
403   = HsCase exp (convertOpFormsMatch matches)
404
405 convertOpFormsCmd (HsIf exp c1 c2)
406   = HsIf exp (convertOpFormsLCmd c1) (convertOpFormsLCmd c2)
407
408 convertOpFormsCmd (HsLet binds cmd)
409   = HsLet binds (convertOpFormsLCmd cmd)
410
411 convertOpFormsCmd (HsDo ctxt stmts body ty)
412   = HsDo ctxt (map (fmap convertOpFormsStmt) stmts)
413               (convertOpFormsLCmd body) ty
414
415 -- Anything else is unchanged.  This includes HsArrForm (already done),
416 -- things with no sub-commands, and illegal commands (which will be
417 -- caught by the type checker)
418 convertOpFormsCmd c = c
419
420 convertOpFormsStmt :: StmtLR id id -> StmtLR id id
421 convertOpFormsStmt (BindStmt pat cmd _ _)
422   = BindStmt pat (convertOpFormsLCmd cmd) noSyntaxExpr noSyntaxExpr
423 convertOpFormsStmt (ExprStmt cmd _ _)
424   = ExprStmt (convertOpFormsLCmd cmd) noSyntaxExpr placeHolderType
425 convertOpFormsStmt (RecStmt stmts lvs rvs es binds)
426   = RecStmt (map (fmap convertOpFormsStmt) stmts) lvs rvs es binds
427 convertOpFormsStmt stmt = stmt
428
429 convertOpFormsMatch :: MatchGroup id -> MatchGroup id
430 convertOpFormsMatch (MatchGroup ms ty)
431   = MatchGroup (map (fmap convert) ms) ty
432  where convert (Match pat mty grhss)
433           = Match pat mty (convertOpFormsGRHSs grhss)
434
435 convertOpFormsGRHSs :: GRHSs id -> GRHSs id
436 convertOpFormsGRHSs (GRHSs grhss binds)
437   = GRHSs (map convertOpFormsGRHS grhss) binds
438
439 convertOpFormsGRHS :: Located (GRHS id) -> Located (GRHS id)
440 convertOpFormsGRHS = fmap convert
441  where 
442    convert (GRHS stmts cmd) = GRHS stmts (convertOpFormsLCmd cmd)
443
444 ---------------------------------------------------
445 type CmdNeeds = FreeVars        -- Only inhabitants are 
446                                 --      appAName, choiceAName, loopAName
447
448 -- find what methods the Cmd needs (loop, choice, apply)
449 methodNamesLCmd :: LHsCmd Name -> CmdNeeds
450 methodNamesLCmd = methodNamesCmd . unLoc
451
452 methodNamesCmd :: HsCmd Name -> CmdNeeds
453
454 methodNamesCmd (HsArrApp _arrow _arg _ HsFirstOrderApp _rtl)
455   = emptyFVs
456 methodNamesCmd (HsArrApp _arrow _arg _ HsHigherOrderApp _rtl)
457   = unitFV appAName
458 methodNamesCmd (HsArrForm {}) = emptyFVs
459
460 methodNamesCmd (HsPar c) = methodNamesLCmd c
461
462 methodNamesCmd (HsIf _ c1 c2)
463   = methodNamesLCmd c1 `plusFV` methodNamesLCmd c2 `addOneFV` choiceAName
464
465 methodNamesCmd (HsLet _ c) = methodNamesLCmd c
466
467 methodNamesCmd (HsDo _ stmts body _) 
468   = methodNamesStmts stmts `plusFV` methodNamesLCmd body
469
470 methodNamesCmd (HsApp c _) = methodNamesLCmd c
471
472 methodNamesCmd (HsLam match) = methodNamesMatch match
473
474 methodNamesCmd (HsCase _ matches)
475   = methodNamesMatch matches `addOneFV` choiceAName
476
477 methodNamesCmd _ = emptyFVs
478    -- Other forms can't occur in commands, but it's not convenient 
479    -- to error here so we just do what's convenient.
480    -- The type checker will complain later
481
482 ---------------------------------------------------
483 methodNamesMatch :: MatchGroup Name -> FreeVars
484 methodNamesMatch (MatchGroup ms _)
485   = plusFVs (map do_one ms)
486  where 
487     do_one (L _ (Match _ _ grhss)) = methodNamesGRHSs grhss
488
489 -------------------------------------------------
490 -- gaw 2004
491 methodNamesGRHSs :: GRHSs Name -> FreeVars
492 methodNamesGRHSs (GRHSs grhss _) = plusFVs (map methodNamesGRHS grhss)
493
494 -------------------------------------------------
495
496 methodNamesGRHS :: Located (GRHS Name) -> CmdNeeds
497 methodNamesGRHS (L _ (GRHS _ rhs)) = methodNamesLCmd rhs
498
499 ---------------------------------------------------
500 methodNamesStmts :: [Located (StmtLR Name Name)] -> FreeVars
501 methodNamesStmts stmts = plusFVs (map methodNamesLStmt stmts)
502
503 ---------------------------------------------------
504 methodNamesLStmt :: Located (StmtLR Name Name) -> FreeVars
505 methodNamesLStmt = methodNamesStmt . unLoc
506
507 methodNamesStmt :: StmtLR Name Name -> FreeVars
508 methodNamesStmt (ExprStmt cmd _ _)     = methodNamesLCmd cmd
509 methodNamesStmt (BindStmt _ cmd _ _) = methodNamesLCmd cmd
510 methodNamesStmt (RecStmt stmts _ _ _ _)
511   = methodNamesStmts stmts `addOneFV` loopAName
512 methodNamesStmt (LetStmt _)  = emptyFVs
513 methodNamesStmt (ParStmt _) = emptyFVs
514 methodNamesStmt (TransformStmt _ _ _) = emptyFVs
515 methodNamesStmt (GroupStmt _ _) = emptyFVs
516    -- ParStmt, TransformStmt and GroupStmt can't occur in commands, but it's not convenient to error 
517    -- here so we just do what's convenient
518 \end{code}
519
520
521 %************************************************************************
522 %*                                                                      *
523         Arithmetic sequences
524 %*                                                                      *
525 %************************************************************************
526
527 \begin{code}
528 rnArithSeq :: ArithSeqInfo RdrName -> RnM (ArithSeqInfo Name, FreeVars)
529 rnArithSeq (From expr)
530  = rnLExpr expr         `thenM` \ (expr', fvExpr) ->
531    returnM (From expr', fvExpr)
532
533 rnArithSeq (FromThen expr1 expr2)
534  = rnLExpr expr1        `thenM` \ (expr1', fvExpr1) ->
535    rnLExpr expr2        `thenM` \ (expr2', fvExpr2) ->
536    returnM (FromThen expr1' expr2', fvExpr1 `plusFV` fvExpr2)
537
538 rnArithSeq (FromTo expr1 expr2)
539  = rnLExpr expr1        `thenM` \ (expr1', fvExpr1) ->
540    rnLExpr expr2        `thenM` \ (expr2', fvExpr2) ->
541    returnM (FromTo expr1' expr2', fvExpr1 `plusFV` fvExpr2)
542
543 rnArithSeq (FromThenTo expr1 expr2 expr3)
544  = rnLExpr expr1        `thenM` \ (expr1', fvExpr1) ->
545    rnLExpr expr2        `thenM` \ (expr2', fvExpr2) ->
546    rnLExpr expr3        `thenM` \ (expr3', fvExpr3) ->
547    returnM (FromThenTo expr1' expr2' expr3',
548             plusFVs [fvExpr1, fvExpr2, fvExpr3])
549 \end{code}
550
551 %************************************************************************
552 %*                                                                      *
553         Template Haskell brackets
554 %*                                                                      *
555 %************************************************************************
556
557 \begin{code}
558 rnBracket :: HsBracket RdrName -> RnM (HsBracket Name, FreeVars)
559 rnBracket (VarBr n) = do { name <- lookupOccRn n
560                          ; this_mod <- getModule
561                          ; checkM (nameIsLocalOrFrom this_mod name) $   -- Reason: deprecation checking asumes the
562                            do { loadInterfaceForName msg name           -- home interface is loaded, and this is the
563                               ; return () }                             -- only way that is going to happen
564                          ; returnM (VarBr name, unitFV name) }
565                     where
566                       msg = ptext (sLit "Need interface for Template Haskell quoted Name")
567
568 rnBracket (ExpBr e) = do { (e', fvs) <- rnLExpr e
569                          ; return (ExpBr e', fvs) }
570
571 rnBracket (PatBr _) = do { addErr (ptext (sLit "Tempate Haskell pattern brackets are not supported yet"));
572                            failM }
573
574 rnBracket (TypBr t) = do { (t', fvs) <- rnHsTypeFVs doc t
575                          ; return (TypBr t', fvs) }
576                     where
577                       doc = ptext (sLit "In a Template-Haskell quoted type")
578 rnBracket (DecBr group) 
579   = do { gbl_env  <- getGblEnv
580
581         ; let new_gbl_env = gbl_env { -- Set the module to thFAKE.  The top-level names from the bracketed 
582                                       -- declarations will go into the name cache, and we don't want them to 
583                                       -- confuse the Names for the current module.  
584                                       -- By using a pretend module, thFAKE, we keep them safely out of the way.
585                                      tcg_mod = thFAKE,
586                         
587                                      -- The emptyDUs is so that we just collect uses for this group alone
588                                      -- in the call to rnSrcDecls below
589                                      tcg_dus = emptyDUs }
590        ; setGblEnv new_gbl_env $ do {
591
592         -- In this situation we want to *shadow* top-level bindings.
593         --      foo = 1
594         --      bar = [d| foo = 1 |]
595         -- If we don't shadow, we'll get an ambiguity complaint when we do 
596         -- a lookupTopBndrRn (which uses lookupGreLocalRn) on the binder of the 'foo'
597         --
598         -- Furthermore, arguably if the splice does define foo, that should hide
599         -- any foo's further out
600         --
601         -- The shadowing is acheived by calling rnSrcDecls with True as the shadowing flag
602        ; (tcg_env, group') <- rnSrcDecls True group       
603
604        -- Discard the tcg_env; it contains only extra info about fixity
605         ; return (DecBr group', allUses (tcg_dus tcg_env)) } }
606 \end{code}
607
608 %************************************************************************
609 %*                                                                      *
610 \subsubsection{@Stmt@s: in @do@ expressions}
611 %*                                                                      *
612 %************************************************************************
613
614 \begin{code}
615 rnStmts :: HsStmtContext Name -> [LStmt RdrName] 
616         -> RnM (thing, FreeVars)
617         -> RnM (([LStmt Name], thing), FreeVars)
618
619 rnStmts (MDoExpr _) = rnMDoStmts
620 rnStmts ctxt        = rnNormalStmts ctxt
621
622 rnNormalStmts :: HsStmtContext Name -> [LStmt RdrName]
623               -> RnM (thing, FreeVars)
624               -> RnM (([LStmt Name], thing), FreeVars)  
625 -- Used for cases *other* than recursive mdo
626 -- Implements nested scopes
627
628 rnNormalStmts _ [] thing_inside 
629   = do { (thing, fvs) <- thing_inside
630         ; return (([],thing), fvs) } 
631
632 rnNormalStmts ctxt (L loc stmt : stmts) thing_inside
633   = do { ((stmt', (stmts', thing)), fvs) <- rnStmt ctxt stmt $
634             rnNormalStmts ctxt stmts thing_inside
635         ; return (((L loc stmt' : stmts'), thing), fvs) }
636
637
638 rnStmt :: HsStmtContext Name -> Stmt RdrName
639        -> RnM (thing, FreeVars)
640        -> RnM ((Stmt Name, thing), FreeVars)
641
642 rnStmt _ (ExprStmt expr _ _) thing_inside
643   = do  { (expr', fv_expr) <- rnLExpr expr
644         ; (then_op, fvs1)  <- lookupSyntaxName thenMName
645         ; (thing, fvs2)    <- thing_inside
646         ; return ((ExprStmt expr' then_op placeHolderType, thing),
647                   fv_expr `plusFV` fvs1 `plusFV` fvs2) }
648
649 rnStmt ctxt (BindStmt pat expr _ _) thing_inside
650   = do  { (expr', fv_expr) <- rnLExpr expr
651                 -- The binders do not scope over the expression
652         ; (bind_op, fvs1) <- lookupSyntaxName bindMName
653         ; (fail_op, fvs2) <- lookupSyntaxName failMName
654         ; rnPatsAndThen_LocalRightwards (StmtCtxt ctxt) [pat] $ \ [pat'] -> do
655         { (thing, fvs3) <- thing_inside
656         ; return ((BindStmt pat' expr' bind_op fail_op, thing),
657                   fv_expr `plusFV` fvs1 `plusFV` fvs2 `plusFV` fvs3) }}
658        -- fv_expr shouldn't really be filtered by the rnPatsAndThen
659         -- but it does not matter because the names are unique
660
661 rnStmt ctxt (LetStmt binds) thing_inside 
662   = do  { checkLetStmt ctxt binds
663         ; rnLocalBindsAndThen binds $ \binds' -> do
664         { (thing, fvs) <- thing_inside
665         ; return ((LetStmt binds', thing), fvs) }  }
666
667 rnStmt ctxt (RecStmt rec_stmts _ _ _ _) thing_inside
668   = do  { checkRecStmt ctxt
669         ; rn_rec_stmts_and_then rec_stmts       $ \ segs -> do
670         { (thing, fvs) <- thing_inside
671         ; let
672             segs_w_fwd_refs          = addFwdRefs segs
673             (ds, us, fs, rec_stmts') = unzip4 segs_w_fwd_refs
674             later_vars = nameSetToList (plusFVs ds `intersectNameSet` fvs)
675             fwd_vars   = nameSetToList (plusFVs fs)
676             uses       = plusFVs us
677             rec_stmt   = RecStmt rec_stmts' later_vars fwd_vars [] emptyLHsBinds
678         ; return ((rec_stmt, thing), uses `plusFV` fvs) } }
679
680 rnStmt ctxt (ParStmt segs) thing_inside
681   = do  { checkParStmt ctxt
682         ; ((segs', thing), fvs) <- rnParallelStmts (ParStmtCtxt ctxt) segs thing_inside
683         ; return ((ParStmt segs', thing), fvs) }
684
685 rnStmt ctxt (TransformStmt (stmts, _) usingExpr maybeByExpr) thing_inside = do
686     checkTransformStmt ctxt
687     
688     (usingExpr', fv_usingExpr) <- rnLExpr usingExpr
689     ((stmts', binders, (maybeByExpr', thing)), fvs) <- 
690         rnNormalStmtsAndFindUsedBinders (TransformStmtCtxt ctxt) stmts $ \_unshadowed_bndrs -> do
691             (maybeByExpr', fv_maybeByExpr)  <- rnMaybeLExpr maybeByExpr
692             (thing, fv_thing)               <- thing_inside
693             
694             return ((maybeByExpr', thing), fv_maybeByExpr `plusFV` fv_thing)
695     
696     return ((TransformStmt (stmts', binders) usingExpr' maybeByExpr', thing), fv_usingExpr `plusFV` fvs)
697   where
698     rnMaybeLExpr Nothing = return (Nothing, emptyFVs)
699     rnMaybeLExpr (Just expr) = do
700         (expr', fv_expr) <- rnLExpr expr
701         return (Just expr', fv_expr)
702         
703 rnStmt ctxt (GroupStmt (stmts, _) groupByClause) thing_inside = do
704     checkTransformStmt ctxt
705     
706     -- We must rename the using expression in the context before the transform is begun
707     groupByClauseAction <- 
708         case groupByClause of
709             GroupByNothing usingExpr -> do
710                 (usingExpr', fv_usingExpr) <- rnLExpr usingExpr
711                 (return . return) (GroupByNothing usingExpr', fv_usingExpr)
712             GroupBySomething eitherUsingExpr byExpr -> do
713                 (eitherUsingExpr', fv_eitherUsingExpr) <- 
714                     case eitherUsingExpr of
715                         Right _ -> return (Right $ HsVar groupWithName, unitNameSet groupWithName)
716                         Left usingExpr -> do
717                             (usingExpr', fv_usingExpr) <- rnLExpr usingExpr
718                             return (Left usingExpr', fv_usingExpr)
719                             
720                 return $ do
721                     (byExpr', fv_byExpr) <- rnLExpr byExpr
722                     return (GroupBySomething eitherUsingExpr' byExpr', fv_eitherUsingExpr `plusFV` fv_byExpr)
723     
724     -- We only use rnNormalStmtsAndFindUsedBinders to get unshadowed_bndrs, so
725     -- perhaps we could refactor this to use rnNormalStmts directly?
726     ((stmts', _, (groupByClause', usedBinderMap, thing)), fvs) <- 
727         rnNormalStmtsAndFindUsedBinders (TransformStmtCtxt ctxt) stmts $ \unshadowed_bndrs -> do
728             (groupByClause', fv_groupByClause) <- groupByClauseAction
729             
730             unshadowed_bndrs' <- mapM newLocalName unshadowed_bndrs
731             let binderMap = zip unshadowed_bndrs unshadowed_bndrs'
732             
733             -- Bind the "thing" inside a context where we have REBOUND everything
734             -- bound by the statements before the group. This is necessary since after
735             -- the grouping the same identifiers actually have different meanings
736             -- i.e. they refer to lists not singletons!
737             (thing, fv_thing) <- bindLocalNames unshadowed_bndrs' thing_inside
738             
739             -- We remove entries from the binder map that are not used in the thing_inside.
740             -- We can then use that usage information to ensure that the free variables do 
741             -- not contain the things we just bound, but do contain the things we need to
742             -- make those bindings (i.e. the corresponding non-listy variables)
743             
744             -- Note that we also retain those entries which have an old binder in our
745             -- own free variables (the using or by expression). This is because this map
746             -- is reused in the desugarer to create the type to bind from the statements
747             -- that occur before this one. If the binders we need are not in the map, they
748             -- will never get bound into our desugared expression and hence the simplifier
749             -- crashes as we refer to variables that don't exist!
750             let usedBinderMap = filter 
751                     (\(old_binder, new_binder) -> 
752                         (new_binder `elemNameSet` fv_thing) || 
753                         (old_binder `elemNameSet` fv_groupByClause)) binderMap
754                 (usedOldBinders, usedNewBinders) = unzip usedBinderMap
755                 real_fv_thing = (delListFromNameSet fv_thing usedNewBinders) `plusFV` (mkNameSet usedOldBinders)
756             
757             return ((groupByClause', usedBinderMap, thing), fv_groupByClause `plusFV` real_fv_thing)
758     
759     traceRn (text "rnStmt: implicitly rebound these used binders:" <+> ppr usedBinderMap)
760     return ((GroupStmt (stmts', usedBinderMap) groupByClause', thing), fvs)
761   
762 rnNormalStmtsAndFindUsedBinders :: HsStmtContext Name 
763           -> [LStmt RdrName]
764           -> ([Name] -> RnM (thing, FreeVars))
765           -> RnM (([LStmt Name], [Name], thing), FreeVars)      
766 rnNormalStmtsAndFindUsedBinders ctxt stmts thing_inside = do
767     ((stmts', (used_bndrs, inner_thing)), fvs) <- rnNormalStmts ctxt stmts $ do
768         -- Find the Names that are bound by stmts that
769         -- by assumption we have just renamed
770         local_env <- getLocalRdrEnv
771         let 
772             stmts_binders = collectLStmtsBinders stmts
773             bndrs = map (expectJust "rnStmt"
774                         . lookupLocalRdrEnv local_env
775                         . unLoc) stmts_binders
776                         
777             -- If shadow, we'll look up (Unqual x) twice, getting
778             -- the second binding both times, which is the
779             -- one we want
780             unshadowed_bndrs = nub bndrs
781                         
782         -- Typecheck the thing inside, passing on all 
783         -- the Names bound before it for its information
784         (thing, fvs) <- thing_inside unshadowed_bndrs
785
786         -- Figure out which of the bound names are used
787         -- after the statements we renamed
788         let used_bndrs = filter (`elemNameSet` fvs) bndrs
789         return ((used_bndrs, thing), fvs)
790
791     -- Flatten the tuple returned by the above call a bit!
792     return ((stmts', used_bndrs, inner_thing), fvs)
793
794 rnParallelStmts :: HsStmtContext Name -> [([LStmt RdrName], [RdrName])]
795                 -> RnM (thing, FreeVars)
796                 -> RnM (([([LStmt Name], [Name])], thing), FreeVars)
797 rnParallelStmts ctxt segs thing_inside = do
798         orig_lcl_env <- getLocalRdrEnv
799         go orig_lcl_env [] segs
800     where
801         go orig_lcl_env bndrs [] = do 
802             let (bndrs', dups) = removeDups cmpByOcc bndrs
803                 inner_env = extendLocalRdrEnv orig_lcl_env bndrs'
804             
805             mappM dupErr dups
806             (thing, fvs) <- setLocalRdrEnv inner_env thing_inside
807             return (([], thing), fvs)
808
809         go orig_lcl_env bndrs_so_far ((stmts, _) : segs) = do 
810             ((stmts', bndrs, (segs', thing)), fvs) <- rnNormalStmtsAndFindUsedBinders ctxt stmts $ \new_bndrs -> do
811                 -- Typecheck the thing inside, passing on all
812                 -- the Names bound, but separately; revert the envt
813                 setLocalRdrEnv orig_lcl_env $ do
814                     go orig_lcl_env (new_bndrs ++ bndrs_so_far) segs
815
816             let seg' = (stmts', bndrs)
817             return (((seg':segs'), thing), delListFromNameSet fvs bndrs)
818
819         cmpByOcc n1 n2 = nameOccName n1 `compare` nameOccName n2
820         dupErr vs = addErr (ptext (sLit "Duplicate binding in parallel list comprehension for:")
821                     <+> quotes (ppr (head vs)))
822 \end{code}
823
824
825 %************************************************************************
826 %*                                                                      *
827 \subsubsection{mdo expressions}
828 %*                                                                      *
829 %************************************************************************
830
831 \begin{code}
832 type FwdRefs = NameSet
833 type Segment stmts = (Defs,
834                       Uses,     -- May include defs
835                       FwdRefs,  -- A subset of uses that are 
836                                 --   (a) used before they are bound in this segment, or 
837                                 --   (b) used here, and bound in subsequent segments
838                       stmts)    -- Either Stmt or [Stmt]
839
840
841 ----------------------------------------------------
842
843 rnMDoStmts :: [LStmt RdrName]
844            -> RnM (thing, FreeVars)
845            -> RnM (([LStmt Name], thing), FreeVars)     
846 rnMDoStmts stmts thing_inside
847   =    -- Step1: Bring all the binders of the mdo into scope
848         -- (Remember that this also removes the binders from the
849         -- finally-returned free-vars.)
850         -- And rename each individual stmt, making a
851         -- singleton segment.  At this stage the FwdRefs field
852         -- isn't finished: it's empty for all except a BindStmt
853         -- for which it's the fwd refs within the bind itself
854         -- (This set may not be empty, because we're in a recursive 
855         -- context.)
856      rn_rec_stmts_and_then stmts $ \ segs -> do {
857
858         ; (thing, fvs_later) <- thing_inside
859
860         ; let
861         -- Step 2: Fill in the fwd refs.
862         --         The segments are all singletons, but their fwd-ref
863         --         field mentions all the things used by the segment
864         --         that are bound after their use
865             segs_w_fwd_refs = addFwdRefs segs
866
867         -- Step 3: Group together the segments to make bigger segments
868         --         Invariant: in the result, no segment uses a variable
869         --                    bound in a later segment
870             grouped_segs = glomSegments segs_w_fwd_refs
871
872         -- Step 4: Turn the segments into Stmts
873         --         Use RecStmt when and only when there are fwd refs
874         --         Also gather up the uses from the end towards the
875         --         start, so we can tell the RecStmt which things are
876         --         used 'after' the RecStmt
877             (stmts', fvs) = segsToStmts grouped_segs fvs_later
878
879         ; return ((stmts', thing), fvs) }
880
881 ---------------------------------------------
882
883 -- wrapper that does both the left- and right-hand sides
884 rn_rec_stmts_and_then :: [LStmt RdrName]
885                          -- assumes that the FreeVars returned includes
886                          -- the FreeVars of the Segments
887                       -> ([Segment (LStmt Name)] -> RnM (a, FreeVars))
888                       -> RnM (a, FreeVars)
889 rn_rec_stmts_and_then s cont
890   = do  { -- (A) Make the mini fixity env for all of the stmts
891           fix_env <- makeMiniFixityEnv (collectRecStmtsFixities s)
892
893           -- (B) Do the LHSes
894         ; new_lhs_and_fv <- rn_rec_stmts_lhs fix_env s
895
896           --    ...bring them and their fixities into scope
897         ; let bound_names = map unLoc $ collectLStmtsBinders (map fst new_lhs_and_fv)
898         ; bindLocalNamesFV_WithFixities bound_names fix_env $ do
899
900           -- (C) do the right-hand-sides and thing-inside
901         { segs <- rn_rec_stmts bound_names new_lhs_and_fv
902         ; (res, fvs) <- cont segs 
903         ; warnUnusedLocalBinds bound_names fvs
904         ; return (res, fvs) }}
905
906 -- get all the fixity decls in any Let stmt
907 collectRecStmtsFixities :: [LStmtLR RdrName RdrName] -> [LFixitySig RdrName]
908 collectRecStmtsFixities l = 
909     foldr (\ s -> \acc -> case s of 
910                             (L _ (LetStmt (HsValBinds (ValBindsIn _ sigs)))) -> 
911                                 foldr (\ sig -> \ acc -> case sig of 
912                                                            (L loc (FixSig s)) -> (L loc s) : acc
913                                                            _ -> acc) acc sigs
914                             _ -> acc) [] l
915                              
916 -- left-hand sides
917
918 rn_rec_stmt_lhs :: MiniFixityEnv
919                 -> LStmt RdrName
920                    -- rename LHS, and return its FVs
921                    -- Warning: we will only need the FreeVars below in the case of a BindStmt,
922                    -- so we don't bother to compute it accurately in the other cases
923                 -> RnM [(LStmtLR Name RdrName, FreeVars)]
924
925 rn_rec_stmt_lhs _ (L loc (ExprStmt expr a b)) = return [(L loc (ExprStmt expr a b), 
926                                                        -- this is actually correct
927                                                        emptyFVs)]
928
929 rn_rec_stmt_lhs fix_env (L loc (BindStmt pat expr a b)) 
930   = do 
931       -- should the ctxt be MDo instead?
932       (pat', fv_pat) <- rnBindPat (localRecNameMaker fix_env) pat 
933       return [(L loc (BindStmt pat' expr a b),
934                fv_pat)]
935
936 rn_rec_stmt_lhs _ (L _ (LetStmt binds@(HsIPBinds _)))
937   = do  { addErr (badIpBinds (ptext (sLit "an mdo expression")) binds)
938         ; failM }
939
940 rn_rec_stmt_lhs fix_env (L loc (LetStmt (HsValBinds binds))) 
941     = do binds' <- rnValBindsLHS fix_env binds
942          return [(L loc (LetStmt (HsValBinds binds')),
943                  -- Warning: this is bogus; see function invariant
944                  emptyFVs
945                  )]
946
947 rn_rec_stmt_lhs fix_env (L _ (RecStmt stmts _ _ _ _))   -- Flatten Rec inside Rec
948     = rn_rec_stmts_lhs fix_env stmts
949
950 rn_rec_stmt_lhs _ stmt@(L _ (ParStmt _))        -- Syntactically illegal in mdo
951   = pprPanic "rn_rec_stmt" (ppr stmt)
952   
953 rn_rec_stmt_lhs _ stmt@(L _ (TransformStmt _ _ _))      -- Syntactically illegal in mdo
954   = pprPanic "rn_rec_stmt" (ppr stmt)
955   
956 rn_rec_stmt_lhs _ stmt@(L _ (GroupStmt _ _))    -- Syntactically illegal in mdo
957   = pprPanic "rn_rec_stmt" (ppr stmt)
958
959 rn_rec_stmt_lhs _ (L _ (LetStmt EmptyLocalBinds))
960   = panic "rn_rec_stmt LetStmt EmptyLocalBinds"
961
962 rn_rec_stmts_lhs :: MiniFixityEnv
963                  -> [LStmt RdrName] 
964                  -> RnM [(LStmtLR Name RdrName, FreeVars)]
965 rn_rec_stmts_lhs fix_env stmts = 
966     let boundNames = collectLStmtsBinders stmts
967         doc = text "In a recursive mdo-expression"
968     in do
969      -- First do error checking: we need to check for dups here because we
970      -- don't bind all of the variables from the Stmt at once
971      -- with bindLocatedLocals.
972      checkDupRdrNames doc boundNames
973      mappM (rn_rec_stmt_lhs fix_env) stmts `thenM` \ ls -> returnM (concat ls)
974
975
976 -- right-hand-sides
977
978 rn_rec_stmt :: [Name] -> LStmtLR Name RdrName -> FreeVars -> RnM [Segment (LStmt Name)]
979         -- Rename a Stmt that is inside a RecStmt (or mdo)
980         -- Assumes all binders are already in scope
981         -- Turns each stmt into a singleton Stmt
982 rn_rec_stmt _ (L loc (ExprStmt expr _ _)) _
983   = rnLExpr expr `thenM` \ (expr', fvs) ->
984     lookupSyntaxName thenMName  `thenM` \ (then_op, fvs1) ->
985     returnM [(emptyNameSet, fvs `plusFV` fvs1, emptyNameSet,
986               L loc (ExprStmt expr' then_op placeHolderType))]
987
988 rn_rec_stmt _ (L loc (BindStmt pat' expr _ _)) fv_pat
989   = rnLExpr expr                `thenM` \ (expr', fv_expr) ->
990     lookupSyntaxName bindMName  `thenM` \ (bind_op, fvs1) ->
991     lookupSyntaxName failMName  `thenM` \ (fail_op, fvs2) ->
992     let
993         bndrs = mkNameSet (collectPatBinders pat')
994         fvs   = fv_expr `plusFV` fv_pat `plusFV` fvs1 `plusFV` fvs2
995     in
996     returnM [(bndrs, fvs, bndrs `intersectNameSet` fvs,
997               L loc (BindStmt pat' expr' bind_op fail_op))]
998
999 rn_rec_stmt _ (L _ (LetStmt binds@(HsIPBinds _))) _
1000   = do  { addErr (badIpBinds (ptext (sLit "an mdo expression")) binds)
1001         ; failM }
1002
1003 rn_rec_stmt all_bndrs (L loc (LetStmt (HsValBinds binds'))) _ = do 
1004   (binds', du_binds) <- 
1005       -- fixities and unused are handled above in rn_rec_stmts_and_then
1006       rnValBindsRHS all_bndrs binds'
1007   returnM [(duDefs du_binds, duUses du_binds, 
1008             emptyNameSet, L loc (LetStmt (HsValBinds binds')))]
1009
1010 -- no RecStmt case becuase they get flattened above when doing the LHSes
1011 rn_rec_stmt _ stmt@(L _ (RecStmt _ _ _ _ _)) _  
1012   = pprPanic "rn_rec_stmt: RecStmt" (ppr stmt)
1013
1014 rn_rec_stmt _ stmt@(L _ (ParStmt _)) _  -- Syntactically illegal in mdo
1015   = pprPanic "rn_rec_stmt: ParStmt" (ppr stmt)
1016
1017 rn_rec_stmt _ stmt@(L _ (TransformStmt _ _ _)) _        -- Syntactically illegal in mdo
1018   = pprPanic "rn_rec_stmt: TransformStmt" (ppr stmt)
1019
1020 rn_rec_stmt _ stmt@(L _ (GroupStmt _ _)) _      -- Syntactically illegal in mdo
1021   = pprPanic "rn_rec_stmt: GroupStmt" (ppr stmt)
1022
1023 rn_rec_stmt _ (L _ (LetStmt EmptyLocalBinds)) _
1024   = panic "rn_rec_stmt: LetStmt EmptyLocalBinds"
1025
1026 rn_rec_stmts :: [Name] -> [(LStmtLR Name RdrName, FreeVars)] -> RnM [Segment (LStmt Name)]
1027 rn_rec_stmts bndrs stmts = mappM (uncurry (rn_rec_stmt bndrs)) stmts    `thenM` \ segs_s ->
1028                            returnM (concat segs_s)
1029
1030 ---------------------------------------------
1031 addFwdRefs :: [Segment a] -> [Segment a]
1032 -- So far the segments only have forward refs *within* the Stmt
1033 --      (which happens for bind:  x <- ...x...)
1034 -- This function adds the cross-seg fwd ref info
1035
1036 addFwdRefs pairs 
1037   = fst (foldr mk_seg ([], emptyNameSet) pairs)
1038   where
1039     mk_seg (defs, uses, fwds, stmts) (segs, later_defs)
1040         = (new_seg : segs, all_defs)
1041         where
1042           new_seg = (defs, uses, new_fwds, stmts)
1043           all_defs = later_defs `unionNameSets` defs
1044           new_fwds = fwds `unionNameSets` (uses `intersectNameSet` later_defs)
1045                 -- Add the downstream fwd refs here
1046
1047 ----------------------------------------------------
1048 --      Glomming the singleton segments of an mdo into 
1049 --      minimal recursive groups.
1050 --
1051 -- At first I thought this was just strongly connected components, but
1052 -- there's an important constraint: the order of the stmts must not change.
1053 --
1054 -- Consider
1055 --      mdo { x <- ...y...
1056 --            p <- z
1057 --            y <- ...x...
1058 --            q <- x
1059 --            z <- y
1060 --            r <- x }
1061 --
1062 -- Here, the first stmt mention 'y', which is bound in the third.  
1063 -- But that means that the innocent second stmt (p <- z) gets caught
1064 -- up in the recursion.  And that in turn means that the binding for
1065 -- 'z' has to be included... and so on.
1066 --
1067 -- Start at the tail { r <- x }
1068 -- Now add the next one { z <- y ; r <- x }
1069 -- Now add one more     { q <- x ; z <- y ; r <- x }
1070 -- Now one more... but this time we have to group a bunch into rec
1071 --      { rec { y <- ...x... ; q <- x ; z <- y } ; r <- x }
1072 -- Now one more, which we can add on without a rec
1073 --      { p <- z ; 
1074 --        rec { y <- ...x... ; q <- x ; z <- y } ; 
1075 --        r <- x }
1076 -- Finally we add the last one; since it mentions y we have to
1077 -- glom it togeher with the first two groups
1078 --      { rec { x <- ...y...; p <- z ; y <- ...x... ; 
1079 --              q <- x ; z <- y } ; 
1080 --        r <- x }
1081
1082 glomSegments :: [Segment (LStmt Name)] -> [Segment [LStmt Name]]
1083
1084 glomSegments [] = []
1085 glomSegments ((defs,uses,fwds,stmt) : segs)
1086         -- Actually stmts will always be a singleton
1087   = (seg_defs, seg_uses, seg_fwds, seg_stmts)  : others
1088   where
1089     segs'            = glomSegments segs
1090     (extras, others) = grab uses segs'
1091     (ds, us, fs, ss) = unzip4 extras
1092     
1093     seg_defs  = plusFVs ds `plusFV` defs
1094     seg_uses  = plusFVs us `plusFV` uses
1095     seg_fwds  = plusFVs fs `plusFV` fwds
1096     seg_stmts = stmt : concat ss
1097
1098     grab :: NameSet             -- The client
1099          -> [Segment a]
1100          -> ([Segment a],       -- Needed by the 'client'
1101              [Segment a])       -- Not needed by the client
1102         -- The result is simply a split of the input
1103     grab uses dus 
1104         = (reverse yeses, reverse noes)
1105         where
1106           (noes, yeses)           = span not_needed (reverse dus)
1107           not_needed (defs,_,_,_) = not (intersectsNameSet defs uses)
1108
1109
1110 ----------------------------------------------------
1111 segsToStmts :: [Segment [LStmt Name]] 
1112             -> FreeVars                 -- Free vars used 'later'
1113             -> ([LStmt Name], FreeVars)
1114
1115 segsToStmts [] fvs_later = ([], fvs_later)
1116 segsToStmts ((defs, uses, fwds, ss) : segs) fvs_later
1117   = ASSERT( not (null ss) )
1118     (new_stmt : later_stmts, later_uses `plusFV` uses)
1119   where
1120     (later_stmts, later_uses) = segsToStmts segs fvs_later
1121     new_stmt | non_rec   = head ss
1122              | otherwise = L (getLoc (head ss)) $ 
1123                            RecStmt ss (nameSetToList used_later) (nameSetToList fwds) 
1124                                       [] emptyLHsBinds
1125              where
1126                non_rec    = isSingleton ss && isEmptyNameSet fwds
1127                used_later = defs `intersectNameSet` later_uses
1128                                 -- The ones needed after the RecStmt
1129 \end{code}
1130
1131 %************************************************************************
1132 %*                                                                      *
1133 \subsubsection{Assertion utils}
1134 %*                                                                      *
1135 %************************************************************************
1136
1137 \begin{code}
1138 srcSpanPrimLit :: SrcSpan -> HsExpr Name
1139 srcSpanPrimLit span = HsLit (HsStringPrim (mkFastString (showSDoc (ppr span))))
1140
1141 mkAssertErrorExpr :: RnM (HsExpr Name, FreeVars)
1142 -- Return an expression for (assertError "Foo.hs:27")
1143 mkAssertErrorExpr
1144   = getSrcSpanM                         `thenM` \ sloc ->
1145     let
1146         expr = HsApp (L sloc (HsVar assertErrorName)) 
1147                      (L sloc (srcSpanPrimLit sloc))
1148     in
1149     returnM (expr, emptyFVs)
1150 \end{code}
1151
1152 %************************************************************************
1153 %*                                                                      *
1154 \subsubsection{Errors}
1155 %*                                                                      *
1156 %************************************************************************
1157
1158 \begin{code}
1159
1160 ---------------------- 
1161 -- Checking when a particular Stmt is ok
1162 checkLetStmt :: HsStmtContext Name -> HsLocalBinds RdrName -> RnM ()
1163 checkLetStmt (ParStmtCtxt _) (HsIPBinds binds) = addErr (badIpBinds (ptext (sLit "a parallel list comprehension:")) binds)
1164 checkLetStmt _ctxt           _binds            = return ()
1165         -- We do not allow implicit-parameter bindings in a parallel
1166         -- list comprehension.  I'm not sure what it might mean.
1167
1168 ---------
1169 checkRecStmt :: HsStmtContext Name -> RnM ()
1170 checkRecStmt (MDoExpr {}) = return ()   -- Recursive stmt ok in 'mdo'
1171 checkRecStmt (DoExpr {})  = return ()   -- ..and in 'do' but only because of arrows:
1172                                         --   proc x -> do { ...rec... }
1173                                         -- We don't have enough context to distinguish this situation here
1174                                         --      so we leave it to the type checker
1175 checkRecStmt ctxt         = addErr msg
1176   where
1177     msg = ptext (sLit "Illegal 'rec' stmt in") <+> pprStmtContext ctxt
1178
1179 ---------
1180 checkParStmt :: HsStmtContext Name -> RnM ()
1181 checkParStmt _
1182   = do  { parallel_list_comp <- doptM Opt_ParallelListComp
1183         ; checkErr parallel_list_comp msg }
1184   where
1185     msg = ptext (sLit "Illegal parallel list comprehension: use -XParallelListComp")
1186
1187 ---------
1188 checkTransformStmt :: HsStmtContext Name -> RnM ()
1189 checkTransformStmt ListComp  -- Ensure we are really within a list comprehension because otherwise the
1190                              -- desugarer will break when we come to operate on a parallel array
1191   = do  { transform_list_comp <- doptM Opt_TransformListComp
1192         ; checkErr transform_list_comp msg }
1193   where
1194     msg = ptext (sLit "Illegal transform or grouping list comprehension: use -XTransformListComp")
1195 checkTransformStmt (ParStmtCtxt       ctxt) = checkTransformStmt ctxt   -- Ok to nest inside a parallel comprehension
1196 checkTransformStmt (TransformStmtCtxt ctxt) = checkTransformStmt ctxt   -- Ok to nest inside a parallel comprehension
1197 checkTransformStmt ctxt = addErr msg
1198   where
1199     msg = ptext (sLit "Illegal transform or grouping in") <+> pprStmtContext ctxt
1200     
1201 ---------
1202 patSynErr :: HsExpr RdrName -> RnM (HsExpr Name, FreeVars)
1203 patSynErr e = do { addErr (sep [ptext (sLit "Pattern syntax in expression context:"),
1204                                 nest 4 (ppr e)])
1205                  ; return (EWildPat, emptyFVs) }
1206
1207 badIpBinds :: Outputable a => SDoc -> a -> SDoc
1208 badIpBinds what binds
1209   = hang (ptext (sLit "Implicit-parameter bindings illegal in") <+> what)
1210          2 (ppr binds)
1211 \end{code}