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