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