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