More hacking on monad-comp; now works
[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, findSplice )
24 import RnBinds   ( rnLocalBindsAndThen, rnLocalValBindsLHS, rnLocalValBindsRHS,
25                    rnMatchGroup, makeMiniFixityEnv) 
26 import HsSyn
27 import TcRnMonad
28 import TcEnv            ( thRnBrack )
29 import RnEnv
30 import RnTypes          ( rnHsTypeFVs, rnSplice, checkTH,
31                           mkOpFormRn, mkOpAppRn, mkNegAppRn, checkSectionPrec)
32 import RnPat
33 import DynFlags
34 import BasicTypes       ( FixityDirection(..) )
35 import PrelNames
36
37 import Name
38 import NameSet
39 import RdrName
40 import LoadIface        ( loadInterfaceForName )
41 import UniqSet
42 import Data.List
43 import Util             ( isSingleton, snocView )
44 import ListSetOps       ( removeDups )
45 import Outputable
46 import SrcLoc
47 import FastString
48 import Control.Monad
49 \end{code}
50
51
52 \begin{code}
53 -- XXX
54 thenM :: Monad a => a b -> (b -> a c) -> a c
55 thenM = (>>=)
56
57 thenM_ :: Monad a => a b -> a c -> a c
58 thenM_ = (>>)
59 \end{code}
60
61 %************************************************************************
62 %*                                                                      *
63 \subsubsection{Expressions}
64 %*                                                                      *
65 %************************************************************************
66
67 \begin{code}
68 rnExprs :: [LHsExpr RdrName] -> RnM ([LHsExpr Name], FreeVars)
69 rnExprs ls = rnExprs' ls emptyUniqSet
70  where
71   rnExprs' [] acc = return ([], acc)
72   rnExprs' (expr:exprs) acc
73    = rnLExpr expr               `thenM` \ (expr', fvExpr) ->
74
75         -- Now we do a "seq" on the free vars because typically it's small
76         -- or empty, especially in very long lists of constants
77     let
78         acc' = acc `plusFV` fvExpr
79     in
80     acc' `seq` rnExprs' exprs acc' `thenM` \ (exprs', fvExprs) ->
81     return (expr':exprs', fvExprs)
82 \end{code}
83
84 Variables. We look up the variable and return the resulting name. 
85
86 \begin{code}
87 rnLExpr :: LHsExpr RdrName -> RnM (LHsExpr Name, FreeVars)
88 rnLExpr = wrapLocFstM rnExpr
89
90 rnExpr :: HsExpr RdrName -> RnM (HsExpr Name, FreeVars)
91
92 finishHsVar :: Name -> RnM (HsExpr Name, FreeVars)
93 -- Separated from rnExpr because it's also used
94 -- when renaming infix expressions
95 -- See Note [Adding the implicit parameter to 'assert']
96 finishHsVar name 
97  = do { ignore_asserts <- doptM Opt_IgnoreAsserts
98       ; if ignore_asserts || not (name `hasKey` assertIdKey)
99         then return (HsVar name, unitFV name)
100         else do { e <- mkAssertErrorExpr
101                 ; return (e, unitFV name) } }
102
103 rnExpr (HsVar v)
104   = do name <- lookupOccRn v
105        finishHsVar name
106
107 rnExpr (HsIPVar v)
108   = newIPNameRn v               `thenM` \ name ->
109     return (HsIPVar name, emptyFVs)
110
111 rnExpr (HsLit lit@(HsString s))
112   = do {
113          opt_OverloadedStrings <- xoptM Opt_OverloadedStrings
114        ; if opt_OverloadedStrings then
115             rnExpr (HsOverLit (mkHsIsString s placeHolderType))
116          else -- Same as below
117             rnLit lit           `thenM_`
118             return (HsLit lit, emptyFVs)
119        }
120
121 rnExpr (HsLit lit) 
122   = rnLit lit           `thenM_`
123     return (HsLit lit, emptyFVs)
124
125 rnExpr (HsOverLit lit) 
126   = rnOverLit lit               `thenM` \ (lit', fvs) ->
127     return (HsOverLit lit', fvs)
128
129 rnExpr (HsApp fun arg)
130   = rnLExpr fun         `thenM` \ (fun',fvFun) ->
131     rnLExpr arg         `thenM` \ (arg',fvArg) ->
132     return (HsApp fun' arg', fvFun `plusFV` fvArg)
133
134 rnExpr (OpApp e1 (L op_loc (HsVar op_rdr)) _ e2)
135   = do  { (e1', fv_e1) <- rnLExpr e1
136         ; (e2', fv_e2) <- rnLExpr e2
137         ; op_name <- setSrcSpan op_loc (lookupOccRn op_rdr)
138         ; (op', fv_op) <- finishHsVar op_name
139                 -- NB: op' is usually just a variable, but might be
140                 --     an applicatoin (assert "Foo.hs:47")
141         -- Deal with fixity
142         -- When renaming code synthesised from "deriving" declarations
143         -- we used to avoid fixity stuff, but we can't easily tell any
144         -- more, so I've removed the test.  Adding HsPars in TcGenDeriv
145         -- should prevent bad things happening.
146         ; fixity <- lookupFixityRn op_name
147         ; final_e <- mkOpAppRn e1' (L op_loc op') fixity e2'
148         ; return (final_e, fv_e1 `plusFV` fv_op `plusFV` fv_e2) }
149 rnExpr (OpApp _ other_op _ _)
150   = failWith (vcat [ hang (ptext (sLit "Operator application with a non-variable operator:"))
151                         2 (ppr other_op)
152                    , ptext (sLit "(Probably resulting from a Template Haskell splice)") ])
153
154 rnExpr (NegApp e _)
155   = rnLExpr e                   `thenM` \ (e', fv_e) ->
156     lookupSyntaxName negateName `thenM` \ (neg_name, fv_neg) ->
157     mkNegAppRn e' neg_name      `thenM` \ final_e ->
158     return (final_e, fv_e `plusFV` fv_neg)
159
160 ------------------------------------------
161 -- Template Haskell extensions
162 -- Don't ifdef-GHCI them because we want to fail gracefully
163 -- (not with an rnExpr crash) in a stage-1 compiler.
164 rnExpr e@(HsBracket br_body)
165   = checkTH e "bracket"         `thenM_`
166     rnBracket br_body           `thenM` \ (body', fvs_e) ->
167     return (HsBracket body', fvs_e)
168
169 rnExpr (HsSpliceE splice)
170   = rnSplice splice             `thenM` \ (splice', fvs) ->
171     return (HsSpliceE splice', fvs)
172
173 #ifndef GHCI
174 rnExpr e@(HsQuasiQuoteE _) = pprPanic "Cant do quasiquotation without GHCi" (ppr e)
175 #else
176 rnExpr (HsQuasiQuoteE qq)
177   = runQuasiQuoteExpr qq        `thenM` \ (L _ expr') ->
178     rnExpr expr'
179 #endif  /* GHCI */
180
181 ---------------------------------------------
182 --      Sections
183 -- See Note [Parsing sections] in Parser.y.pp
184 rnExpr (HsPar (L loc (section@(SectionL {}))))
185   = do  { (section', fvs) <- rnSection section
186         ; return (HsPar (L loc section'), fvs) }
187
188 rnExpr (HsPar (L loc (section@(SectionR {}))))
189   = do  { (section', fvs) <- rnSection section
190         ; return (HsPar (L loc section'), fvs) }
191
192 rnExpr (HsPar e)
193   = do  { (e', fvs_e) <- rnLExpr e
194         ; return (HsPar e', fvs_e) }
195
196 rnExpr expr@(SectionL {})
197   = do  { addErr (sectionErr expr); rnSection expr }
198 rnExpr expr@(SectionR {})
199   = do  { addErr (sectionErr expr); rnSection expr }
200
201 ---------------------------------------------
202 rnExpr (HsCoreAnn ann expr)
203   = rnLExpr expr `thenM` \ (expr', fvs_expr) ->
204     return (HsCoreAnn ann expr', fvs_expr)
205
206 rnExpr (HsSCC lbl expr)
207   = rnLExpr expr                `thenM` \ (expr', fvs_expr) ->
208     return (HsSCC lbl expr', fvs_expr)
209 rnExpr (HsTickPragma info expr)
210   = rnLExpr expr                `thenM` \ (expr', fvs_expr) ->
211     return (HsTickPragma info expr', fvs_expr)
212
213 rnExpr (HsLam matches)
214   = rnMatchGroup LambdaExpr matches     `thenM` \ (matches', fvMatch) ->
215     return (HsLam matches', fvMatch)
216
217 rnExpr (HsCase expr matches)
218   = rnLExpr expr                        `thenM` \ (new_expr, e_fvs) ->
219     rnMatchGroup CaseAlt matches        `thenM` \ (new_matches, ms_fvs) ->
220     return (HsCase new_expr new_matches, e_fvs `plusFV` ms_fvs)
221
222 rnExpr (HsLet binds expr)
223   = rnLocalBindsAndThen binds           $ \ binds' ->
224     rnLExpr expr                         `thenM` \ (expr',fvExpr) ->
225     return (HsLet binds' expr', fvExpr)
226
227 rnExpr (HsDo do_or_lc stmts _)
228   = do  { ((stmts', _), fvs) <- rnStmts do_or_lc stmts (\ _ -> return ((), emptyFVs))
229         ; return ( HsDo do_or_lc stmts' placeHolderType, fvs ) }
230
231 rnExpr (ExplicitList _ exps)
232   = rnExprs exps                        `thenM` \ (exps', fvs) ->
233     return  (ExplicitList placeHolderType exps', fvs)
234
235 rnExpr (ExplicitPArr _ exps)
236   = rnExprs exps                        `thenM` \ (exps', fvs) ->
237     return  (ExplicitPArr placeHolderType exps', fvs)
238
239 rnExpr (ExplicitTuple tup_args boxity)
240   = do { checkTupleSection tup_args
241        ; checkTupSize (length tup_args)
242        ; (tup_args', fvs) <- mapAndUnzipM rnTupArg tup_args
243        ; return (ExplicitTuple tup_args' boxity, plusFVs fvs) }
244   where
245     rnTupArg (Present e) = do { (e',fvs) <- rnLExpr e; return (Present e', fvs) }
246     rnTupArg (Missing _) = return (Missing placeHolderType, emptyFVs)
247
248 rnExpr (RecordCon con_id _ rbinds)
249   = do  { conname <- lookupLocatedOccRn con_id
250         ; (rbinds', fvRbinds) <- rnHsRecBinds (HsRecFieldCon (unLoc conname)) rbinds
251         ; return (RecordCon conname noPostTcExpr rbinds', 
252                   fvRbinds `addOneFV` unLoc conname) }
253
254 rnExpr (RecordUpd expr rbinds _ _ _)
255   = do  { (expr', fvExpr) <- rnLExpr expr
256         ; (rbinds', fvRbinds) <- rnHsRecBinds HsRecFieldUpd rbinds
257         ; return (RecordUpd expr' rbinds' [] [] [], 
258                   fvExpr `plusFV` fvRbinds) }
259
260 rnExpr (ExprWithTySig expr pty)
261   = do  { (pty', fvTy) <- rnHsTypeFVs doc pty
262         ; (expr', fvExpr) <- bindSigTyVarsFV (hsExplicitTvs pty') $
263                              rnLExpr expr
264         ; return (ExprWithTySig expr' pty', fvExpr `plusFV` fvTy) }
265   where 
266     doc = text "In an expression type signature"
267
268 rnExpr (HsIf _ p b1 b2)
269   = do { (p', fvP) <- rnLExpr p
270        ; (b1', fvB1) <- rnLExpr b1
271        ; (b2', fvB2) <- rnLExpr b2
272        ; (mb_ite, fvITE) <- lookupIfThenElse
273        ; return (HsIf mb_ite p' b1' b2', plusFVs [fvITE, fvP, fvB1, fvB2]) }
274
275 rnExpr (HsType a)
276   = rnHsTypeFVs doc a   `thenM` \ (t, fvT) -> 
277     return (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     return (ArithSeq noPostTcExpr new_seq, fvs)
284
285 rnExpr (PArrSeq _ seq)
286   = rnArithSeq seq       `thenM` \ (new_seq, fvs) ->
287     return (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     rnPat ProcExpr pat $ \ pat' ->
311     rnCmdTop body                `thenM` \ (body',fvBody) ->
312     return (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     return (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',fv_op) ->
328     let L _ (HsVar op_name) = op' in
329     rnCmdTop arg1       `thenM` \ (arg1',fv_arg1) ->
330     rnCmdTop arg2       `thenM` \ (arg2',fv_arg2) ->
331
332         -- Deal with fixity
333
334     lookupFixityRn op_name              `thenM` \ fixity ->
335     mkOpFormRn arg1' op' fixity arg2'   `thenM` \ final_e -> 
336
337     return (final_e,
338               fv_arg1 `plusFV` fv_op `plusFV` fv_arg2)
339
340 rnExpr (HsArrForm op fixity cmds)
341   = escapeArrowScope (rnLExpr op)       `thenM` \ (op',fvOp) ->
342     rnCmdArgs cmds                      `thenM` \ (cmds',fvCmds) ->
343     return (HsArrForm op' fixity cmds', fvOp `plusFV` fvCmds)
344
345 rnExpr other = pprPanic "rnExpr: unexpected expression" (ppr other)
346         -- HsWrap
347
348 ----------------------
349 -- See Note [Parsing sections] in Parser.y.pp
350 rnSection :: HsExpr RdrName -> RnM (HsExpr Name, FreeVars)
351 rnSection section@(SectionR op expr)
352   = do  { (op', fvs_op)     <- rnLExpr op
353         ; (expr', fvs_expr) <- rnLExpr expr
354         ; checkSectionPrec InfixR section op' expr'
355         ; return (SectionR op' expr', fvs_op `plusFV` fvs_expr) }
356
357 rnSection section@(SectionL expr op)
358   = do  { (expr', fvs_expr) <- rnLExpr expr
359         ; (op', fvs_op)     <- rnLExpr op
360         ; checkSectionPrec InfixL section op' expr'
361         ; return (SectionL expr' op', fvs_op `plusFV` fvs_expr) }
362
363 rnSection other = pprPanic "rnSection" (ppr other)
364 \end{code}
365
366 %************************************************************************
367 %*                                                                      *
368         Records
369 %*                                                                      *
370 %************************************************************************
371
372 \begin{code}
373 rnHsRecBinds :: HsRecFieldContext -> HsRecordBinds RdrName
374              -> RnM (HsRecordBinds Name, FreeVars)
375 rnHsRecBinds ctxt rec_binds@(HsRecFields { rec_dotdot = dd })
376   = do { (flds, fvs) <- rnHsRecFields1 ctxt HsVar rec_binds
377        ; (flds', fvss) <- mapAndUnzipM rn_field flds
378        ; return (HsRecFields { rec_flds = flds', rec_dotdot = dd }, 
379                  fvs `plusFV` plusFVs fvss) }
380   where 
381     rn_field fld = do { (arg', fvs) <- rnLExpr (hsRecFieldArg fld)
382                       ; return (fld { hsRecFieldArg = arg' }, fvs) }
383 \end{code}
384
385
386 %************************************************************************
387 %*                                                                      *
388         Arrow commands
389 %*                                                                      *
390 %************************************************************************
391
392 \begin{code}
393 rnCmdArgs :: [LHsCmdTop RdrName] -> RnM ([LHsCmdTop Name], FreeVars)
394 rnCmdArgs [] = return ([], emptyFVs)
395 rnCmdArgs (arg:args)
396   = rnCmdTop arg        `thenM` \ (arg',fvArg) ->
397     rnCmdArgs args      `thenM` \ (args',fvArgs) ->
398     return (arg':args', fvArg `plusFV` fvArgs)
399
400 rnCmdTop :: LHsCmdTop RdrName -> RnM (LHsCmdTop Name, FreeVars)
401 rnCmdTop = wrapLocFstM rnCmdTop'
402  where
403   rnCmdTop' (HsCmdTop cmd _ _ _) 
404    = rnLExpr (convertOpFormsLCmd cmd) `thenM` \ (cmd', fvCmd) ->
405      let 
406         cmd_names = [arrAName, composeAName, firstAName] ++
407                     nameSetToList (methodNamesCmd (unLoc cmd'))
408      in
409         -- Generate the rebindable syntax for the monad
410      lookupSyntaxTable cmd_names        `thenM` \ (cmd_names', cmd_fvs) ->
411
412      return (HsCmdTop cmd' [] placeHolderType cmd_names', 
413              fvCmd `plusFV` cmd_fvs)
414
415 ---------------------------------------------------
416 -- convert OpApp's in a command context to HsArrForm's
417
418 convertOpFormsLCmd :: LHsCmd id -> LHsCmd id
419 convertOpFormsLCmd = fmap convertOpFormsCmd
420
421 convertOpFormsCmd :: HsCmd id -> HsCmd id
422
423 convertOpFormsCmd (HsApp c e) = HsApp (convertOpFormsLCmd c) e
424 convertOpFormsCmd (HsLam match) = HsLam (convertOpFormsMatch match)
425 convertOpFormsCmd (OpApp c1 op fixity c2)
426   = let
427         arg1 = L (getLoc c1) $ HsCmdTop (convertOpFormsLCmd c1) [] placeHolderType []
428         arg2 = L (getLoc c2) $ HsCmdTop (convertOpFormsLCmd c2) [] placeHolderType []
429     in
430     HsArrForm op (Just fixity) [arg1, arg2]
431
432 convertOpFormsCmd (HsPar c) = HsPar (convertOpFormsLCmd c)
433
434 convertOpFormsCmd (HsCase exp matches)
435   = HsCase exp (convertOpFormsMatch matches)
436
437 convertOpFormsCmd (HsIf f exp c1 c2)
438   = HsIf f exp (convertOpFormsLCmd c1) (convertOpFormsLCmd c2)
439
440 convertOpFormsCmd (HsLet binds cmd)
441   = HsLet binds (convertOpFormsLCmd cmd)
442
443 convertOpFormsCmd (HsDo ctxt stmts ty)
444   = HsDo ctxt (map (fmap convertOpFormsStmt) stmts) ty
445
446 -- Anything else is unchanged.  This includes HsArrForm (already done),
447 -- things with no sub-commands, and illegal commands (which will be
448 -- caught by the type checker)
449 convertOpFormsCmd c = c
450
451 convertOpFormsStmt :: StmtLR id id -> StmtLR id id
452 convertOpFormsStmt (BindStmt pat cmd _ _)
453   = BindStmt pat (convertOpFormsLCmd cmd) noSyntaxExpr noSyntaxExpr
454 convertOpFormsStmt (ExprStmt cmd _ _ _)
455   = ExprStmt (convertOpFormsLCmd cmd) noSyntaxExpr noSyntaxExpr placeHolderType
456 convertOpFormsStmt stmt@(RecStmt { recS_stmts = stmts })
457   = stmt { recS_stmts = map (fmap convertOpFormsStmt) stmts }
458 convertOpFormsStmt stmt = stmt
459
460 convertOpFormsMatch :: MatchGroup id -> MatchGroup id
461 convertOpFormsMatch (MatchGroup ms ty)
462   = MatchGroup (map (fmap convert) ms) ty
463  where convert (Match pat mty grhss)
464           = Match pat mty (convertOpFormsGRHSs grhss)
465
466 convertOpFormsGRHSs :: GRHSs id -> GRHSs id
467 convertOpFormsGRHSs (GRHSs grhss binds)
468   = GRHSs (map convertOpFormsGRHS grhss) binds
469
470 convertOpFormsGRHS :: Located (GRHS id) -> Located (GRHS id)
471 convertOpFormsGRHS = fmap convert
472  where 
473    convert (GRHS stmts cmd) = GRHS stmts (convertOpFormsLCmd cmd)
474
475 ---------------------------------------------------
476 type CmdNeeds = FreeVars        -- Only inhabitants are 
477                                 --      appAName, choiceAName, loopAName
478
479 -- find what methods the Cmd needs (loop, choice, apply)
480 methodNamesLCmd :: LHsCmd Name -> CmdNeeds
481 methodNamesLCmd = methodNamesCmd . unLoc
482
483 methodNamesCmd :: HsCmd Name -> CmdNeeds
484
485 methodNamesCmd (HsArrApp _arrow _arg _ HsFirstOrderApp _rtl)
486   = emptyFVs
487 methodNamesCmd (HsArrApp _arrow _arg _ HsHigherOrderApp _rtl)
488   = unitFV appAName
489 methodNamesCmd (HsArrForm {}) = emptyFVs
490
491 methodNamesCmd (HsPar c) = methodNamesLCmd c
492
493 methodNamesCmd (HsIf _ _ c1 c2)
494   = methodNamesLCmd c1 `plusFV` methodNamesLCmd c2 `addOneFV` choiceAName
495
496 methodNamesCmd (HsLet _ c)      = methodNamesLCmd c
497 methodNamesCmd (HsDo _ stmts _) = methodNamesStmts stmts 
498 methodNamesCmd (HsApp c _)      = methodNamesLCmd c
499 methodNamesCmd (HsLam match)    = methodNamesMatch match
500
501 methodNamesCmd (HsCase _ matches)
502   = methodNamesMatch matches `addOneFV` choiceAName
503
504 methodNamesCmd _ = emptyFVs
505    -- Other forms can't occur in commands, but it's not convenient 
506    -- to error here so we just do what's convenient.
507    -- The type checker will complain later
508
509 ---------------------------------------------------
510 methodNamesMatch :: MatchGroup Name -> FreeVars
511 methodNamesMatch (MatchGroup ms _)
512   = plusFVs (map do_one ms)
513  where 
514     do_one (L _ (Match _ _ grhss)) = methodNamesGRHSs grhss
515
516 -------------------------------------------------
517 -- gaw 2004
518 methodNamesGRHSs :: GRHSs Name -> FreeVars
519 methodNamesGRHSs (GRHSs grhss _) = plusFVs (map methodNamesGRHS grhss)
520
521 -------------------------------------------------
522
523 methodNamesGRHS :: Located (GRHS Name) -> CmdNeeds
524 methodNamesGRHS (L _ (GRHS _ rhs)) = methodNamesLCmd rhs
525
526 ---------------------------------------------------
527 methodNamesStmts :: [Located (StmtLR Name Name)] -> FreeVars
528 methodNamesStmts stmts = plusFVs (map methodNamesLStmt stmts)
529
530 ---------------------------------------------------
531 methodNamesLStmt :: Located (StmtLR Name Name) -> FreeVars
532 methodNamesLStmt = methodNamesStmt . unLoc
533
534 methodNamesStmt :: StmtLR Name Name -> FreeVars
535 methodNamesStmt (LastStmt cmd _)                 = methodNamesLCmd cmd
536 methodNamesStmt (ExprStmt cmd _ _ _)             = methodNamesLCmd cmd
537 methodNamesStmt (BindStmt _ cmd _ _)             = methodNamesLCmd cmd
538 methodNamesStmt (RecStmt { recS_stmts = stmts }) = methodNamesStmts stmts `addOneFV` loopAName
539 methodNamesStmt (LetStmt _)                      = emptyFVs
540 methodNamesStmt (ParStmt _ _ _ _)                = emptyFVs
541 methodNamesStmt (TransformStmt {})               = emptyFVs
542 methodNamesStmt (GroupStmt {})                   = emptyFVs
543    -- ParStmt, TransformStmt and GroupStmt can't occur in commands, but it's not convenient to error 
544    -- here so we just do what's convenient
545 \end{code}
546
547
548 %************************************************************************
549 %*                                                                      *
550         Arithmetic sequences
551 %*                                                                      *
552 %************************************************************************
553
554 \begin{code}
555 rnArithSeq :: ArithSeqInfo RdrName -> RnM (ArithSeqInfo Name, FreeVars)
556 rnArithSeq (From expr)
557  = rnLExpr expr         `thenM` \ (expr', fvExpr) ->
558    return (From expr', fvExpr)
559
560 rnArithSeq (FromThen expr1 expr2)
561  = rnLExpr expr1        `thenM` \ (expr1', fvExpr1) ->
562    rnLExpr expr2        `thenM` \ (expr2', fvExpr2) ->
563    return (FromThen expr1' expr2', fvExpr1 `plusFV` fvExpr2)
564
565 rnArithSeq (FromTo expr1 expr2)
566  = rnLExpr expr1        `thenM` \ (expr1', fvExpr1) ->
567    rnLExpr expr2        `thenM` \ (expr2', fvExpr2) ->
568    return (FromTo expr1' expr2', fvExpr1 `plusFV` fvExpr2)
569
570 rnArithSeq (FromThenTo expr1 expr2 expr3)
571  = rnLExpr expr1        `thenM` \ (expr1', fvExpr1) ->
572    rnLExpr expr2        `thenM` \ (expr2', fvExpr2) ->
573    rnLExpr expr3        `thenM` \ (expr3', fvExpr3) ->
574    return (FromThenTo expr1' expr2' expr3',
575             plusFVs [fvExpr1, fvExpr2, fvExpr3])
576 \end{code}
577
578 %************************************************************************
579 %*                                                                      *
580         Template Haskell brackets
581 %*                                                                      *
582 %************************************************************************
583
584 \begin{code}
585 rnBracket :: HsBracket RdrName -> RnM (HsBracket Name, FreeVars)
586 rnBracket (VarBr n) = do { name <- lookupOccRn n
587                          ; this_mod <- getModule
588                          ; unless (nameIsLocalOrFrom this_mod name) $   -- Reason: deprecation checking asumes the
589                            do { _ <- loadInterfaceForName msg name      -- home interface is loaded, and this is the
590                               ; return () }                             -- only way that is going to happen
591                          ; return (VarBr name, unitFV name) }
592                     where
593                       msg = ptext (sLit "Need interface for Template Haskell quoted Name")
594
595 rnBracket (ExpBr e) = do { (e', fvs) <- rnLExpr e
596                          ; return (ExpBr e', fvs) }
597
598 rnBracket (PatBr p) = rnPat ThPatQuote p $ \ p' -> return (PatBr p', emptyFVs)
599
600 rnBracket (TypBr t) = do { (t', fvs) <- rnHsTypeFVs doc t
601                          ; return (TypBr t', fvs) }
602                     where
603                       doc = ptext (sLit "In a Template-Haskell quoted type")
604
605 rnBracket (DecBrL decls) 
606   = do { (group, mb_splice) <- findSplice decls
607        ; case mb_splice of
608            Nothing -> return ()
609            Just (SpliceDecl (L loc _) _, _)  
610               -> setSrcSpan loc $
611                  addErr (ptext (sLit "Declaration splices are not permitted inside declaration brackets"))
612                 -- Why not?  See Section 7.3 of the TH paper.  
613
614        ; gbl_env  <- getGblEnv
615        ; let new_gbl_env = gbl_env { tcg_dus = emptyDUs }
616                           -- The emptyDUs is so that we just collect uses for this
617                           -- group alone in the call to rnSrcDecls below
618        ; (tcg_env, group') <- setGblEnv new_gbl_env $ 
619                               setStage thRnBrack $
620                               rnSrcDecls group      
621
622               -- Discard the tcg_env; it contains only extra info about fixity
623         ; traceRn (text "rnBracket dec" <+> (ppr (tcg_dus tcg_env) $$ ppr (duUses (tcg_dus tcg_env))))
624         ; return (DecBrG group', duUses (tcg_dus tcg_env)) }
625
626 rnBracket (DecBrG _) = panic "rnBracket: unexpected DecBrG"
627 \end{code}
628
629 %************************************************************************
630 %*                                                                      *
631 \subsubsection{@Stmt@s: in @do@ expressions}
632 %*                                                                      *
633 %************************************************************************
634
635 \begin{code}
636 rnStmts :: HsStmtContext Name -> [LStmt RdrName]
637         -> ([Name] -> RnM (thing, FreeVars))
638         -> RnM (([LStmt Name], thing), FreeVars)        
639 -- Variables bound by the Stmts, and mentioned in thing_inside,
640 -- do not appear in the result FreeVars
641
642 rnStmts ctxt [] thing_inside
643   = do { checkEmptyStmts ctxt
644        ; (thing, fvs) <- thing_inside []
645        ; return (([], thing), fvs) }
646
647 rnStmts MDoExpr stmts thing_inside    -- Deal with mdo
648   = -- Behave like do { rec { ...all but last... }; last }
649     do { ((stmts1, (stmts2, thing)), fvs) 
650            <- rnStmt MDoExpr (noLoc $ mkRecStmt all_but_last) $ \ _ ->
651               do { checkStmt MDoExpr True last_stmt
652                  ; rnStmt MDoExpr last_stmt thing_inside }
653         ; return (((stmts1 ++ stmts2), thing), fvs) }
654   where
655     Just (all_but_last, last_stmt) = snocView stmts
656
657 rnStmts ctxt (lstmt@(L loc stmt) : lstmts) thing_inside
658   | null lstmts
659   = setSrcSpan loc $
660     do { -- Turn a final ExprStmt into a LastStmt
661          -- This is the first place it's convenient to do this
662          -- (In principle the parser could do it, but it's 
663          --  just not very convenient to do so.)
664          let stmt' | okEmpty ctxt 
665                    = lstmt
666                    | otherwise    
667                    = case stmt of 
668                        ExprStmt e _ _ _ -> L loc (mkLastStmt e)
669                        _                -> lstmt
670        ; checkStmt ctxt True {- last stmt -} stmt'
671        ; rnStmt ctxt stmt' thing_inside }
672
673   | otherwise
674   = do { ((stmts1, (stmts2, thing)), fvs) 
675             <- setSrcSpan loc                         $
676                do { checkStmt ctxt False {- Not last -} lstmt
677                   ; rnStmt ctxt lstmt    $ \ bndrs1 ->
678                     rnStmts ctxt lstmts  $ \ bndrs2 ->
679                     thing_inside (bndrs1 ++ bndrs2) }
680         ; return (((stmts1 ++ stmts2), thing), fvs) }
681
682 ----------------------
683 rnStmt :: HsStmtContext Name 
684        -> LStmt RdrName
685        -> ([Name] -> RnM (thing, FreeVars))
686        -> RnM (([LStmt Name], thing), FreeVars)
687 -- Variables bound by the Stmt, and mentioned in thing_inside,
688 -- do not appear in the result FreeVars
689
690 rnStmt _ (L loc (LastStmt expr _)) thing_inside
691   = do  { (expr', fv_expr) <- rnLExpr expr
692         ; (ret_op, fvs1)   <- lookupSyntaxName returnMName
693         ; (thing, fvs3)    <- thing_inside []
694         ; return (([L loc (LastStmt expr' ret_op)], thing),
695                   fv_expr `plusFV` fvs1 `plusFV` fvs3) }
696
697 rnStmt ctxt (L loc (ExprStmt expr _ _ _)) thing_inside
698   = do  { (expr', fv_expr) <- rnLExpr expr
699         ; (then_op, fvs1)  <- lookupSyntaxName thenMName
700         ; (guard_op, fvs2) <- if isMonadCompExpr ctxt
701                                  then lookupSyntaxName guardMName
702                                  else return (noSyntaxExpr, emptyFVs)
703         ; (thing, fvs3)    <- thing_inside []
704         ; return (([L loc (ExprStmt expr' then_op guard_op placeHolderType)], thing),
705                   fv_expr `plusFV` fvs1 `plusFV` fvs2 `plusFV` fvs3) }
706
707 rnStmt ctxt (L loc (BindStmt pat expr _ _)) thing_inside
708   = do  { (expr', fv_expr) <- rnLExpr expr
709                 -- The binders do not scope over the expression
710         ; (bind_op, fvs1) <- lookupSyntaxName bindMName
711         ; (fail_op, fvs2) <- lookupSyntaxName failMName
712         ; rnPat (StmtCtxt ctxt) pat $ \ pat' -> do
713         { (thing, fvs3) <- thing_inside (collectPatBinders pat')
714         ; return (([L loc (BindStmt pat' expr' bind_op fail_op)], thing),
715                   fv_expr `plusFV` fvs1 `plusFV` fvs2 `plusFV` fvs3) }}
716        -- fv_expr shouldn't really be filtered by the rnPatsAndThen
717         -- but it does not matter because the names are unique
718
719 rnStmt _ (L loc (LetStmt binds)) thing_inside 
720   = do  { rnLocalBindsAndThen binds $ \binds' -> do
721         { (thing, fvs) <- thing_inside (collectLocalBinders binds')
722         ; return (([L loc (LetStmt binds')], thing), fvs) }  }
723
724 rnStmt _ (L _ (RecStmt { recS_stmts = rec_stmts })) thing_inside
725   = do  { 
726         -- Step1: Bring all the binders of the mdo into scope
727         -- (Remember that this also removes the binders from the
728         -- finally-returned free-vars.)
729         -- And rename each individual stmt, making a
730         -- singleton segment.  At this stage the FwdRefs field
731         -- isn't finished: it's empty for all except a BindStmt
732         -- for which it's the fwd refs within the bind itself
733         -- (This set may not be empty, because we're in a recursive 
734         -- context.)
735         ; rnRecStmtsAndThen rec_stmts   $ \ segs -> do
736
737         { let bndrs = nameSetToList $ foldr (unionNameSets . (\(ds,_,_,_) -> ds)) 
738                                             emptyNameSet segs
739         ; (thing, fvs_later) <- thing_inside bndrs
740         ; (return_op, fvs1)  <- lookupSyntaxName returnMName
741         ; (mfix_op,   fvs2)  <- lookupSyntaxName mfixName
742         ; (bind_op,   fvs3)  <- lookupSyntaxName bindMName
743         ; let
744                 -- Step 2: Fill in the fwd refs.
745                 --         The segments are all singletons, but their fwd-ref
746                 --         field mentions all the things used by the segment
747                 --         that are bound after their use
748             segs_w_fwd_refs          = addFwdRefs segs
749
750                 -- Step 3: Group together the segments to make bigger segments
751                 --         Invariant: in the result, no segment uses a variable
752                 --                    bound in a later segment
753             grouped_segs = glomSegments segs_w_fwd_refs
754
755                 -- Step 4: Turn the segments into Stmts
756                 --         Use RecStmt when and only when there are fwd refs
757                 --         Also gather up the uses from the end towards the
758                 --         start, so we can tell the RecStmt which things are
759                 --         used 'after' the RecStmt
760             empty_rec_stmt = emptyRecStmt { recS_ret_fn  = return_op
761                                           , recS_mfix_fn = mfix_op
762                                           , recS_bind_fn = bind_op }
763             (rec_stmts', fvs) = segsToStmts empty_rec_stmt grouped_segs fvs_later
764
765         ; return ((rec_stmts', thing), fvs `plusFV` fvs1 `plusFV` fvs2 `plusFV` fvs3) } }
766
767 rnStmt ctxt (L loc (ParStmt segs _ _ _)) thing_inside
768   = do  { ((mzip_op, fvs1), (bind_op, fvs2), (return_op, fvs3)) <- if isMonadCompExpr ctxt
769               then (,,) <$> lookupSyntaxName mzipName
770                         <*> lookupSyntaxName bindMName
771                         <*> lookupSyntaxName returnMName
772               else return ( (noSyntaxExpr, emptyFVs)
773                           , (noSyntaxExpr, emptyFVs)
774                           , (noSyntaxExpr, emptyFVs) )
775         ; ((segs', thing), fvs4) <- rnParallelStmts (ParStmtCtxt ctxt) segs thing_inside
776         ; return ( ([L loc (ParStmt segs' mzip_op bind_op return_op)], thing)
777                  , fvs1 `plusFV` fvs2 `plusFV` fvs3 `plusFV` fvs4) }
778
779 rnStmt ctxt (L loc (TransformStmt stmts _ using by _ _)) thing_inside
780   = do { (using', fvs1) <- rnLExpr using
781
782        ; ((stmts', (by', used_bndrs, thing)), fvs2)
783              <- rnStmts (TransformStmtCtxt ctxt) stmts $ \ bndrs ->
784                 do { (by', fvs_by) <- case by of
785                                         Nothing -> return (Nothing, emptyFVs)
786                                         Just e  -> do { (e', fvs) <- rnLExpr e; return (Just e', fvs) }
787                    ; (thing, fvs_thing) <- thing_inside bndrs
788                    ; let fvs        = fvs_by `plusFV` fvs_thing
789                          used_bndrs = filter (`elemNameSet` fvs) bndrs
790                          -- The paper (Fig 5) has a bug here; we must treat any free varaible of
791                          -- the "thing inside", **or of the by-expression**, as used
792                    ; return ((by', used_bndrs, thing), fvs) }
793
794        -- Lookup `(>>=)` and `fail` for monad comprehensions
795        ; ((return_op, fvs3), (bind_op, fvs4)) <-
796              if isMonadCompExpr ctxt
797                 then (,) <$> lookupSyntaxName returnMName
798                          <*> lookupSyntaxName bindMName
799                 else return ( (noSyntaxExpr, emptyFVs)
800                             , (noSyntaxExpr, emptyFVs) )
801
802        ; return (([L loc (TransformStmt stmts' used_bndrs using' by' return_op bind_op)], thing), 
803                  fvs1 `plusFV` fvs2 `plusFV` fvs3 `plusFV` fvs4) }
804         
805 rnStmt ctxt (L loc (GroupStmt { grpS_stmts = stmts, grpS_by = by, grpS_explicit = explicit
806                               , grpS_using = using })) thing_inside
807   = do { -- Rename the 'using' expression in the context before the transform is begun
808          let implicit_name | isMonadCompExpr ctxt = groupMName
809                            | otherwise            = groupWithName
810        ; (using', fvs1) <- if explicit 
811                            then rnLExpr using
812                            else do { (e,fvs) <- lookupSyntaxName implicit_name
813                                    ; return (noLoc e, fvs) }
814
815          -- Rename the stmts and the 'by' expression
816          -- Keep track of the variables mentioned in the 'by' expression
817        ; ((stmts', (by', used_bndrs, thing)), fvs2) 
818              <- rnStmts (TransformStmtCtxt ctxt) stmts $ \ bndrs ->
819                 do { (by',   fvs_by) <- mapMaybeFvRn rnLExpr by
820                    ; (thing, fvs_thing) <- thing_inside bndrs
821                    ; let fvs = fvs_by `plusFV` fvs_thing
822                          used_bndrs = filter (`elemNameSet` fvs) bndrs
823                    ; return ((by', used_bndrs, thing), fvs) }
824
825        -- Lookup `return`, `(>>=)` and `liftM` for monad comprehensions
826        ; ((return_op, fvs3), (bind_op, fvs4), (fmap_op, fvs5)) <-
827              if isMonadCompExpr ctxt
828                 then (,,) <$> lookupSyntaxName returnMName
829                           <*> lookupSyntaxName bindMName
830                           <*> lookupSyntaxName fmapName
831                 else return ( (noSyntaxExpr, emptyFVs)
832                             , (noSyntaxExpr, emptyFVs)
833                             , (noSyntaxExpr, emptyFVs) )
834
835        ; let all_fvs  = fvs1 `plusFV` fvs2 `plusFV` fvs3 `plusFV` fvs4
836                              `plusFV` fvs5
837              bndr_map = used_bndrs `zip` used_bndrs
838              -- See Note [GroupStmt binder map] in HsExpr
839
840        ; traceRn (text "rnStmt: implicitly rebound these used binders:" <+> ppr bndr_map)
841        ; return (([L loc (GroupStmt { grpS_stmts = stmts', grpS_bndrs = bndr_map
842                                     , grpS_by = by', grpS_using = using', grpS_explicit = explicit
843                                     , grpS_ret = return_op, grpS_bind = bind_op
844                                     , grpS_fmap = fmap_op })], thing), all_fvs) }
845
846 type ParSeg id = ([LStmt id], [id])        -- The Names are bound by the Stmts
847
848 rnParallelStmts :: forall thing. HsStmtContext Name 
849                 -> [ParSeg RdrName]
850                 -> ([Name] -> RnM (thing, FreeVars))
851                 -> RnM (([ParSeg Name], thing), FreeVars)
852 -- Note [Renaming parallel Stmts]
853 rnParallelStmts ctxt segs thing_inside
854   = do { orig_lcl_env <- getLocalRdrEnv
855        ; rn_segs orig_lcl_env [] segs }
856   where
857     rn_segs :: LocalRdrEnv
858             -> [Name] -> [ParSeg RdrName]
859             -> RnM (([ParSeg Name], thing), FreeVars)
860     rn_segs _ bndrs_so_far [] 
861       = do { let (bndrs', dups) = removeDups cmpByOcc bndrs_so_far
862            ; mapM_ dupErr dups
863            ; (thing, fvs) <- bindLocalNames bndrs' (thing_inside bndrs')
864            ; return (([], thing), fvs) }
865
866     rn_segs env bndrs_so_far ((stmts,_) : segs) 
867       = do { ((stmts', (used_bndrs, segs', thing)), fvs)
868                     <- rnStmts ctxt stmts $ \ bndrs ->
869                        setLocalRdrEnv env       $ do
870                        { ((segs', thing), fvs) <- rn_segs env (bndrs ++ bndrs_so_far) segs
871                        ; let used_bndrs = filter (`elemNameSet` fvs) bndrs
872                        ; return ((used_bndrs, segs', thing), fvs) }
873                        
874            ; let seg' = (stmts', used_bndrs)
875            ; return ((seg':segs', thing), fvs) }
876
877     cmpByOcc n1 n2 = nameOccName n1 `compare` nameOccName n2
878     dupErr vs = addErr (ptext (sLit "Duplicate binding in parallel list comprehension for:")
879                     <+> quotes (ppr (head vs)))
880 \end{code}
881
882 Note [Renaming parallel Stmts]
883 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
884 Renaming parallel statements is painful.  Given, say  
885      [ a+c | a <- as, bs <- bss
886            | c <- bs, a <- ds ]
887 Note that
888   (a) In order to report "Defined by not used" about 'bs', we must rename
889       each group of Stmts with a thing_inside whose FreeVars include at least {a,c}
890    
891   (b) We want to report that 'a' is illegally bound in both branches
892
893   (c) The 'bs' in the second group must obviously not be captured by 
894       the binding in the first group
895
896 To satisfy (a) we nest the segements. 
897 To satisfy (b) we check for duplicates just before thing_inside.
898 To satisfy (c) we reset the LocalRdrEnv each time.
899
900 %************************************************************************
901 %*                                                                      *
902 \subsubsection{mdo expressions}
903 %*                                                                      *
904 %************************************************************************
905
906 \begin{code}
907 type FwdRefs = NameSet
908 type Segment stmts = (Defs,
909                       Uses,     -- May include defs
910                       FwdRefs,  -- A subset of uses that are 
911                                 --   (a) used before they are bound in this segment, or 
912                                 --   (b) used here, and bound in subsequent segments
913                       stmts)    -- Either Stmt or [Stmt]
914
915
916 -- wrapper that does both the left- and right-hand sides
917 rnRecStmtsAndThen :: [LStmt RdrName]
918                          -- assumes that the FreeVars returned includes
919                          -- the FreeVars of the Segments
920                       -> ([Segment (LStmt Name)] -> RnM (a, FreeVars))
921                       -> RnM (a, FreeVars)
922 rnRecStmtsAndThen s cont
923   = do  { -- (A) Make the mini fixity env for all of the stmts
924           fix_env <- makeMiniFixityEnv (collectRecStmtsFixities s)
925
926           -- (B) Do the LHSes
927         ; new_lhs_and_fv <- rn_rec_stmts_lhs fix_env s
928
929           --    ...bring them and their fixities into scope
930         ; let bound_names = collectLStmtsBinders (map fst new_lhs_and_fv)
931               -- Fake uses of variables introduced implicitly (warning suppression, see #4404)
932               implicit_uses = lStmtsImplicits (map fst new_lhs_and_fv)
933         ; bindLocalNamesFV bound_names $
934           addLocalFixities fix_env bound_names $ do
935
936           -- (C) do the right-hand-sides and thing-inside
937         { segs <- rn_rec_stmts bound_names new_lhs_and_fv
938         ; (res, fvs) <- cont segs 
939         ; warnUnusedLocalBinds bound_names (fvs `unionNameSets` implicit_uses)
940         ; return (res, fvs) }}
941
942 -- get all the fixity decls in any Let stmt
943 collectRecStmtsFixities :: [LStmtLR RdrName RdrName] -> [LFixitySig RdrName]
944 collectRecStmtsFixities l = 
945     foldr (\ s -> \acc -> case s of 
946                             (L _ (LetStmt (HsValBinds (ValBindsIn _ sigs)))) -> 
947                                 foldr (\ sig -> \ acc -> case sig of 
948                                                            (L loc (FixSig s)) -> (L loc s) : acc
949                                                            _ -> acc) acc sigs
950                             _ -> acc) [] l
951                              
952 -- left-hand sides
953
954 rn_rec_stmt_lhs :: MiniFixityEnv
955                 -> LStmt RdrName
956                    -- rename LHS, and return its FVs
957                    -- Warning: we will only need the FreeVars below in the case of a BindStmt,
958                    -- so we don't bother to compute it accurately in the other cases
959                 -> RnM [(LStmtLR Name RdrName, FreeVars)]
960
961 rn_rec_stmt_lhs _ (L loc (ExprStmt expr a b c)) 
962   = return [(L loc (ExprStmt expr a b c), emptyFVs)]
963
964 rn_rec_stmt_lhs _ (L loc (LastStmt expr a)) 
965   = return [(L loc (LastStmt expr a), emptyFVs)]
966
967 rn_rec_stmt_lhs fix_env (L loc (BindStmt pat expr a b)) 
968   = do 
969       -- should the ctxt be MDo instead?
970       (pat', fv_pat) <- rnBindPat (localRecNameMaker fix_env) pat 
971       return [(L loc (BindStmt pat' expr a b),
972                fv_pat)]
973
974 rn_rec_stmt_lhs _ (L _ (LetStmt binds@(HsIPBinds _)))
975   = failWith (badIpBinds (ptext (sLit "an mdo expression")) binds)
976
977 rn_rec_stmt_lhs fix_env (L loc (LetStmt (HsValBinds binds))) 
978     = do (_bound_names, binds') <- rnLocalValBindsLHS fix_env binds
979          return [(L loc (LetStmt (HsValBinds binds')),
980                  -- Warning: this is bogus; see function invariant
981                  emptyFVs
982                  )]
983
984 -- XXX Do we need to do something with the return and mfix names?
985 rn_rec_stmt_lhs fix_env (L _ (RecStmt { recS_stmts = stmts }))  -- Flatten Rec inside Rec
986     = rn_rec_stmts_lhs fix_env stmts
987
988 rn_rec_stmt_lhs _ stmt@(L _ (ParStmt _ _ _ _))  -- Syntactically illegal in mdo
989   = pprPanic "rn_rec_stmt" (ppr stmt)
990   
991 rn_rec_stmt_lhs _ stmt@(L _ (TransformStmt {})) -- Syntactically illegal in mdo
992   = pprPanic "rn_rec_stmt" (ppr stmt)
993   
994 rn_rec_stmt_lhs _ stmt@(L _ (GroupStmt {}))     -- Syntactically illegal in mdo
995   = pprPanic "rn_rec_stmt" (ppr stmt)
996
997 rn_rec_stmt_lhs _ (L _ (LetStmt EmptyLocalBinds))
998   = panic "rn_rec_stmt LetStmt EmptyLocalBinds"
999
1000 rn_rec_stmts_lhs :: MiniFixityEnv
1001                  -> [LStmt RdrName] 
1002                  -> RnM [(LStmtLR Name RdrName, FreeVars)]
1003 rn_rec_stmts_lhs fix_env stmts
1004   = do { ls <- concatMapM (rn_rec_stmt_lhs fix_env) stmts
1005        ; let boundNames = collectLStmtsBinders (map fst ls)
1006             -- First do error checking: we need to check for dups here because we
1007             -- don't bind all of the variables from the Stmt at once
1008             -- with bindLocatedLocals.
1009        ; checkDupNames boundNames
1010        ; return ls }
1011
1012
1013 -- right-hand-sides
1014
1015 rn_rec_stmt :: [Name] -> LStmtLR Name RdrName -> FreeVars -> RnM [Segment (LStmt Name)]
1016         -- Rename a Stmt that is inside a RecStmt (or mdo)
1017         -- Assumes all binders are already in scope
1018         -- Turns each stmt into a singleton Stmt
1019 rn_rec_stmt _ (L loc (LastStmt expr _)) _
1020   = do  { (expr', fv_expr) <- rnLExpr expr
1021         ; (ret_op, fvs1)   <- lookupSyntaxName returnMName
1022         ; return [(emptyNameSet, fv_expr `plusFV` fvs1, emptyNameSet,
1023                    L loc (LastStmt expr' ret_op))] }
1024
1025 rn_rec_stmt _ (L loc (ExprStmt expr _ _ _)) _
1026   = rnLExpr expr `thenM` \ (expr', fvs) ->
1027     lookupSyntaxName thenMName  `thenM` \ (then_op, fvs1) ->
1028     return [(emptyNameSet, fvs `plusFV` fvs1, emptyNameSet,
1029               L loc (ExprStmt expr' then_op noSyntaxExpr placeHolderType))]
1030
1031 rn_rec_stmt _ (L loc (BindStmt pat' expr _ _)) fv_pat
1032   = rnLExpr expr                `thenM` \ (expr', fv_expr) ->
1033     lookupSyntaxName bindMName  `thenM` \ (bind_op, fvs1) ->
1034     lookupSyntaxName failMName  `thenM` \ (fail_op, fvs2) ->
1035     let
1036         bndrs = mkNameSet (collectPatBinders pat')
1037         fvs   = fv_expr `plusFV` fv_pat `plusFV` fvs1 `plusFV` fvs2
1038     in
1039     return [(bndrs, fvs, bndrs `intersectNameSet` fvs,
1040               L loc (BindStmt pat' expr' bind_op fail_op))]
1041
1042 rn_rec_stmt _ (L _ (LetStmt binds@(HsIPBinds _))) _
1043   = failWith (badIpBinds (ptext (sLit "an mdo expression")) binds)
1044
1045 rn_rec_stmt all_bndrs (L loc (LetStmt (HsValBinds binds'))) _ = do 
1046   (binds', du_binds) <- 
1047       -- fixities and unused are handled above in rnRecStmtsAndThen
1048       rnLocalValBindsRHS (mkNameSet all_bndrs) binds'
1049   return [(duDefs du_binds, allUses du_binds, 
1050            emptyNameSet, L loc (LetStmt (HsValBinds binds')))]
1051
1052 -- no RecStmt case becuase they get flattened above when doing the LHSes
1053 rn_rec_stmt _ stmt@(L _ (RecStmt {})) _
1054   = pprPanic "rn_rec_stmt: RecStmt" (ppr stmt)
1055
1056 rn_rec_stmt _ stmt@(L _ (ParStmt {})) _ -- Syntactically illegal in mdo
1057   = pprPanic "rn_rec_stmt: ParStmt" (ppr stmt)
1058
1059 rn_rec_stmt _ stmt@(L _ (TransformStmt {})) _   -- Syntactically illegal in mdo
1060   = pprPanic "rn_rec_stmt: TransformStmt" (ppr stmt)
1061
1062 rn_rec_stmt _ stmt@(L _ (GroupStmt {})) _       -- Syntactically illegal in mdo
1063   = pprPanic "rn_rec_stmt: GroupStmt" (ppr stmt)
1064
1065 rn_rec_stmt _ (L _ (LetStmt EmptyLocalBinds)) _
1066   = panic "rn_rec_stmt: LetStmt EmptyLocalBinds"
1067
1068 rn_rec_stmts :: [Name] -> [(LStmtLR Name RdrName, FreeVars)] -> RnM [Segment (LStmt Name)]
1069 rn_rec_stmts bndrs stmts = mapM (uncurry (rn_rec_stmt bndrs)) stmts     `thenM` \ segs_s ->
1070                            return (concat segs_s)
1071
1072 ---------------------------------------------
1073 addFwdRefs :: [Segment a] -> [Segment a]
1074 -- So far the segments only have forward refs *within* the Stmt
1075 --      (which happens for bind:  x <- ...x...)
1076 -- This function adds the cross-seg fwd ref info
1077
1078 addFwdRefs pairs 
1079   = fst (foldr mk_seg ([], emptyNameSet) pairs)
1080   where
1081     mk_seg (defs, uses, fwds, stmts) (segs, later_defs)
1082         = (new_seg : segs, all_defs)
1083         where
1084           new_seg = (defs, uses, new_fwds, stmts)
1085           all_defs = later_defs `unionNameSets` defs
1086           new_fwds = fwds `unionNameSets` (uses `intersectNameSet` later_defs)
1087                 -- Add the downstream fwd refs here
1088
1089 ----------------------------------------------------
1090 --      Glomming the singleton segments of an mdo into 
1091 --      minimal recursive groups.
1092 --
1093 -- At first I thought this was just strongly connected components, but
1094 -- there's an important constraint: the order of the stmts must not change.
1095 --
1096 -- Consider
1097 --      mdo { x <- ...y...
1098 --            p <- z
1099 --            y <- ...x...
1100 --            q <- x
1101 --            z <- y
1102 --            r <- x }
1103 --
1104 -- Here, the first stmt mention 'y', which is bound in the third.  
1105 -- But that means that the innocent second stmt (p <- z) gets caught
1106 -- up in the recursion.  And that in turn means that the binding for
1107 -- 'z' has to be included... and so on.
1108 --
1109 -- Start at the tail { r <- x }
1110 -- Now add the next one { z <- y ; r <- x }
1111 -- Now add one more     { q <- x ; z <- y ; r <- x }
1112 -- Now one more... but this time we have to group a bunch into rec
1113 --      { rec { y <- ...x... ; q <- x ; z <- y } ; r <- x }
1114 -- Now one more, which we can add on without a rec
1115 --      { p <- z ; 
1116 --        rec { y <- ...x... ; q <- x ; z <- y } ; 
1117 --        r <- x }
1118 -- Finally we add the last one; since it mentions y we have to
1119 -- glom it togeher with the first two groups
1120 --      { rec { x <- ...y...; p <- z ; y <- ...x... ; 
1121 --              q <- x ; z <- y } ; 
1122 --        r <- x }
1123
1124 glomSegments :: [Segment (LStmt Name)] -> [Segment [LStmt Name]]
1125
1126 glomSegments [] = []
1127 glomSegments ((defs,uses,fwds,stmt) : segs)
1128         -- Actually stmts will always be a singleton
1129   = (seg_defs, seg_uses, seg_fwds, seg_stmts)  : others
1130   where
1131     segs'            = glomSegments segs
1132     (extras, others) = grab uses segs'
1133     (ds, us, fs, ss) = unzip4 extras
1134     
1135     seg_defs  = plusFVs ds `plusFV` defs
1136     seg_uses  = plusFVs us `plusFV` uses
1137     seg_fwds  = plusFVs fs `plusFV` fwds
1138     seg_stmts = stmt : concat ss
1139
1140     grab :: NameSet             -- The client
1141          -> [Segment a]
1142          -> ([Segment a],       -- Needed by the 'client'
1143              [Segment a])       -- Not needed by the client
1144         -- The result is simply a split of the input
1145     grab uses dus 
1146         = (reverse yeses, reverse noes)
1147         where
1148           (noes, yeses)           = span not_needed (reverse dus)
1149           not_needed (defs,_,_,_) = not (intersectsNameSet defs uses)
1150
1151
1152 ----------------------------------------------------
1153 segsToStmts :: Stmt Name                -- A RecStmt with the SyntaxOps filled in
1154             -> [Segment [LStmt Name]] 
1155             -> FreeVars                 -- Free vars used 'later'
1156             -> ([LStmt Name], FreeVars)
1157
1158 segsToStmts _ [] fvs_later = ([], fvs_later)
1159 segsToStmts empty_rec_stmt ((defs, uses, fwds, ss) : segs) fvs_later
1160   = ASSERT( not (null ss) )
1161     (new_stmt : later_stmts, later_uses `plusFV` uses)
1162   where
1163     (later_stmts, later_uses) = segsToStmts empty_rec_stmt segs fvs_later
1164     new_stmt | non_rec   = head ss
1165              | otherwise = L (getLoc (head ss)) rec_stmt 
1166     rec_stmt = empty_rec_stmt { recS_stmts     = ss
1167                               , recS_later_ids = nameSetToList used_later
1168                               , recS_rec_ids   = nameSetToList fwds }
1169     non_rec    = isSingleton ss && isEmptyNameSet fwds
1170     used_later = defs `intersectNameSet` later_uses
1171                                 -- The ones needed after the RecStmt
1172 \end{code}
1173
1174 %************************************************************************
1175 %*                                                                      *
1176 \subsubsection{Assertion utils}
1177 %*                                                                      *
1178 %************************************************************************
1179
1180 \begin{code}
1181 srcSpanPrimLit :: SrcSpan -> HsExpr Name
1182 srcSpanPrimLit span = HsLit (HsStringPrim (mkFastString (showSDocOneLine (ppr span))))
1183
1184 mkAssertErrorExpr :: RnM (HsExpr Name)
1185 -- Return an expression for (assertError "Foo.hs:27")
1186 mkAssertErrorExpr
1187   = getSrcSpanM                         `thenM` \ sloc ->
1188     return (HsApp (L sloc (HsVar assertErrorName)) 
1189                   (L sloc (srcSpanPrimLit sloc)))
1190 \end{code}
1191
1192 Note [Adding the implicit parameter to 'assert']
1193 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1194 The renamer transforms (assert e1 e2) to (assert "Foo.hs:27" e1 e2).
1195 By doing this in the renamer we allow the typechecker to just see the
1196 expanded application and do the right thing. But it's not really 
1197 the Right Thing because there's no way to "undo" if you want to see
1198 the original source code.  We'll have fix this in due course, when
1199 we care more about being able to reconstruct the exact original 
1200 program.
1201
1202 %************************************************************************
1203 %*                                                                      *
1204 \subsubsection{Errors}
1205 %*                                                                      *
1206 %************************************************************************
1207
1208 \begin{code}
1209 checkEmptyStmts :: HsStmtContext Name -> RnM ()
1210 -- We've seen an empty sequence of Stmts... is that ok?
1211 checkEmptyStmts ctxt 
1212   = unless (okEmpty ctxt) (addErr (emptyErr ctxt))
1213
1214 okEmpty :: HsStmtContext Name -> Bool
1215 okEmpty (PatGuard {}) = True
1216 okEmpty _             = False
1217
1218 emptyErr :: HsStmtContext Name -> SDoc
1219 emptyErr (ParStmtCtxt {})       = ptext (sLit "Empty statement group in parallel comprehension")
1220 emptyErr (TransformStmtCtxt {}) = ptext (sLit "Empty statement group preceding 'group' or 'then'")
1221 emptyErr ctxt                   = ptext (sLit "Empty") <+> pprStmtContext ctxt
1222
1223 ---------------------- 
1224 -- Checking when a particular Stmt is ok
1225 checkStmt :: HsStmtContext Name
1226           -> Bool                       -- True <=> this is the last Stmt in the sequence
1227           -> LStmt RdrName 
1228           -> RnM ()
1229 checkStmt ctxt is_last (L _ stmt)
1230   = do { dflags <- getDOpts
1231        ; case okStmt dflags ctxt is_last stmt of 
1232            Nothing    -> return ()
1233            Just extra -> addErr (msg $$ extra) }
1234   where
1235    msg = sep [ ptext (sLit "Unexpected") <+> pprStmtCat stmt <+> ptext (sLit "statement")
1236              , ptext (sLit "in") <+> pprAStmtContext ctxt ]
1237
1238 pprStmtCat :: Stmt a -> SDoc
1239 pprStmtCat (TransformStmt {}) = ptext (sLit "transform")
1240 pprStmtCat (GroupStmt {})     = ptext (sLit "group")
1241 pprStmtCat (LastStmt {})      = ptext (sLit "return expression")
1242 pprStmtCat (ExprStmt {})      = ptext (sLit "exprssion")
1243 pprStmtCat (BindStmt {})      = ptext (sLit "binding")
1244 pprStmtCat (LetStmt {})       = ptext (sLit "let")
1245 pprStmtCat (RecStmt {})       = ptext (sLit "rec")
1246 pprStmtCat (ParStmt {})       = ptext (sLit "parallel")
1247
1248 ------------
1249 isOK, notOK :: Maybe SDoc
1250 isOK  = Nothing
1251 notOK = Just empty
1252
1253 okStmt, okDoStmt, okCompStmt :: DynFlags -> HsStmtContext Name -> Bool 
1254                              -> Stmt RdrName -> Maybe SDoc
1255 -- Return Nothing if OK, (Just extra) if not ok
1256 -- The "extra" is an SDoc that is appended to an generic error message
1257 okStmt _ (PatGuard {}) _ stmt
1258   = case stmt of
1259       ExprStmt {} -> isOK
1260       BindStmt {} -> isOK
1261       LetStmt {}  -> isOK
1262       _           -> notOK
1263
1264 okStmt dflags (ParStmtCtxt ctxt) _ stmt
1265   = case stmt of
1266       LetStmt (HsIPBinds {}) -> notOK
1267       _                      -> okStmt dflags ctxt False stmt
1268                                 -- NB: is_last=False in recursive
1269                                 -- call; the branches of of a Par
1270                                 -- not finish with a LastStmt
1271
1272 okStmt dflags (TransformStmtCtxt ctxt) _ stmt 
1273   = okStmt dflags ctxt False stmt
1274
1275 okStmt dflags ctxt is_last stmt 
1276   | isDoExpr       ctxt = okDoStmt   dflags ctxt is_last stmt
1277   | isListCompExpr ctxt = okCompStmt dflags ctxt is_last stmt
1278   | otherwise           = pprPanic "okStmt" (pprStmtContext ctxt)
1279
1280 ----------------
1281 okDoStmt dflags ctxt is_last stmt
1282   | is_last
1283   = case stmt of 
1284       LastStmt {} -> isOK
1285       _ -> Just (ptext (sLit "The last statement in") <+> pprAStmtContext ctxt
1286                  <+> ptext (sLit "must be an expression"))
1287
1288   | otherwise
1289   = case stmt of
1290        RecStmt {} 
1291          | Opt_DoRec `xopt` dflags -> isOK
1292          | otherwise -> Just (ptext (sLit "Use -XDoRec"))
1293        BindStmt {} -> isOK
1294        LetStmt {}  -> isOK
1295        ExprStmt {} -> isOK
1296        _           -> notOK
1297
1298
1299 ----------------
1300 okCompStmt dflags _ is_last stmt
1301   | is_last
1302   = case stmt of
1303       LastStmt {} -> Nothing
1304       _ -> pprPanic "Unexpected stmt" (ppr stmt)  -- Not a user error
1305
1306   | otherwise
1307   = case stmt of
1308        BindStmt {} -> isOK
1309        LetStmt {}  -> isOK
1310        ExprStmt {} -> isOK
1311        ParStmt {} 
1312          | Opt_ParallelListComp `xopt` dflags -> isOK
1313          | otherwise -> Just (ptext (sLit "Use -XParallelListComp"))
1314        TransformStmt {} 
1315          | Opt_TransformListComp `xopt` dflags -> isOK
1316          | otherwise -> Just (ptext (sLit "Use -XTransformListComp"))
1317        GroupStmt {} 
1318          | Opt_TransformListComp `xopt` dflags -> isOK
1319          | otherwise -> Just (ptext (sLit "Use -XTransformListComp"))
1320        LastStmt {} -> notOK
1321        RecStmt {}  -> notOK
1322
1323 ---------
1324 checkTupleSection :: [HsTupArg RdrName] -> RnM ()
1325 checkTupleSection args
1326   = do  { tuple_section <- xoptM Opt_TupleSections
1327         ; checkErr (all tupArgPresent args || tuple_section) msg }
1328   where
1329     msg = ptext (sLit "Illegal tuple section: use -XTupleSections")
1330
1331 ---------
1332 sectionErr :: HsExpr RdrName -> SDoc
1333 sectionErr expr
1334   = hang (ptext (sLit "A section must be enclosed in parentheses"))
1335        2 (ptext (sLit "thus:") <+> (parens (ppr expr)))
1336
1337 patSynErr :: HsExpr RdrName -> RnM (HsExpr Name, FreeVars)
1338 patSynErr e = do { addErr (sep [ptext (sLit "Pattern syntax in expression context:"),
1339                                 nest 4 (ppr e)])
1340                  ; return (EWildPat, emptyFVs) }
1341
1342 badIpBinds :: Outputable a => SDoc -> a -> SDoc
1343 badIpBinds what binds
1344   = hang (ptext (sLit "Implicit-parameter bindings illegal in") <+> what)
1345          2 (ppr binds)
1346 \end{code}