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