2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[RnExpr]{Renaming of expressions}
6 Basically dependency analysis.
8 Handles @Match@, @GRHSs@, @HsExpr@, and @Qualifier@ datatypes. In
9 general, all of these functions return a renamed thing, and a set of
14 rnLExpr, rnExpr, rnStmts
17 #include "HsVersions.h"
20 import {-# SOURCE #-} TcSplice( runQuasiQuoteExpr )
23 import RnSource ( rnSrcDecls, findSplice )
24 import RnBinds ( rnLocalBindsAndThen, rnLocalValBindsLHS, rnLocalValBindsRHS,
25 rnMatchGroup, makeMiniFixityEnv)
28 import TcEnv ( thRnBrack )
30 import RnTypes ( rnHsTypeFVs, rnSplice, checkTH,
31 mkOpFormRn, mkOpAppRn, mkNegAppRn, checkSectionPrec)
34 import BasicTypes ( FixityDirection(..) )
40 import LoadIface ( loadInterfaceForName )
43 import Util ( isSingleton, snocView )
44 import ListSetOps ( removeDups )
54 thenM :: Monad a => a b -> (b -> a c) -> a c
57 thenM_ :: Monad a => a b -> a c -> a c
61 %************************************************************************
63 \subsubsection{Expressions}
65 %************************************************************************
68 rnExprs :: [LHsExpr RdrName] -> RnM ([LHsExpr Name], FreeVars)
69 rnExprs ls = rnExprs' ls emptyUniqSet
71 rnExprs' [] acc = return ([], acc)
72 rnExprs' (expr:exprs) acc
73 = rnLExpr expr `thenM` \ (expr', fvExpr) ->
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
78 acc' = acc `plusFV` fvExpr
80 acc' `seq` rnExprs' exprs acc' `thenM` \ (exprs', fvExprs) ->
81 return (expr':exprs', fvExprs)
84 Variables. We look up the variable and return the resulting name.
87 rnLExpr :: LHsExpr RdrName -> RnM (LHsExpr Name, FreeVars)
88 rnLExpr = wrapLocFstM rnExpr
90 rnExpr :: HsExpr RdrName -> RnM (HsExpr Name, FreeVars)
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']
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) } }
104 = do name <- lookupOccRn v
108 = newIPNameRn v `thenM` \ name ->
109 return (HsIPVar name, emptyFVs)
111 rnExpr (HsLit lit@(HsString s))
113 opt_OverloadedStrings <- xoptM Opt_OverloadedStrings
114 ; if opt_OverloadedStrings then
115 rnExpr (HsOverLit (mkHsIsString s placeHolderType))
116 else -- Same as below
118 return (HsLit lit, emptyFVs)
123 return (HsLit lit, emptyFVs)
125 rnExpr (HsOverLit lit)
126 = rnOverLit lit `thenM` \ (lit', fvs) ->
127 return (HsOverLit lit', fvs)
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)
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")
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:"))
152 , ptext (sLit "(Probably resulting from a Template Haskell splice)") ])
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)
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)
169 rnExpr (HsSpliceE splice)
170 = rnSplice splice `thenM` \ (splice', fvs) ->
171 return (HsSpliceE splice', fvs)
174 rnExpr e@(HsQuasiQuoteE _) = pprPanic "Cant do quasiquotation without GHCi" (ppr e)
176 rnExpr (HsQuasiQuoteE qq)
177 = runQuasiQuoteExpr qq `thenM` \ (L _ expr') ->
181 ---------------------------------------------
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) }
188 rnExpr (HsPar (L loc (section@(SectionR {}))))
189 = do { (section', fvs) <- rnSection section
190 ; return (HsPar (L loc section'), fvs) }
193 = do { (e', fvs_e) <- rnLExpr e
194 ; return (HsPar e', fvs_e) }
196 rnExpr expr@(SectionL {})
197 = do { addErr (sectionErr expr); rnSection expr }
198 rnExpr expr@(SectionR {})
199 = do { addErr (sectionErr expr); rnSection expr }
201 ---------------------------------------------
202 rnExpr (HsCoreAnn ann expr)
203 = rnLExpr expr `thenM` \ (expr', fvs_expr) ->
204 return (HsCoreAnn ann expr', fvs_expr)
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)
213 rnExpr (HsLam matches)
214 = rnMatchGroup LambdaExpr matches `thenM` \ (matches', fvMatch) ->
215 return (HsLam matches', fvMatch)
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)
222 rnExpr (HsLet binds expr)
223 = rnLocalBindsAndThen binds $ \ binds' ->
224 rnLExpr expr `thenM` \ (expr',fvExpr) ->
225 return (HsLet binds' expr', fvExpr)
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 ) }
231 rnExpr (ExplicitList _ exps)
232 = rnExprs exps `thenM` \ (exps', fvs) ->
233 return (ExplicitList placeHolderType exps', fvs)
235 rnExpr (ExplicitPArr _ exps)
236 = rnExprs exps `thenM` \ (exps', fvs) ->
237 return (ExplicitPArr placeHolderType exps', fvs)
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) }
245 rnTupArg (Present e) = do { (e',fvs) <- rnLExpr e; return (Present e', fvs) }
246 rnTupArg (Missing _) = return (Missing placeHolderType, emptyFVs)
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) }
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) }
260 rnExpr (ExprWithTySig expr pty)
261 = do { (pty', fvTy) <- rnHsTypeFVs doc pty
262 ; (expr', fvExpr) <- bindSigTyVarsFV (hsExplicitTvs pty') $
264 ; return (ExprWithTySig expr' pty', fvExpr `plusFV` fvTy) }
266 doc = text "In an expression type signature"
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]) }
276 = rnHsTypeFVs doc a `thenM` \ (t, fvT) ->
277 return (HsType t, fvT)
279 doc = text "In a type argument"
281 rnExpr (ArithSeq _ seq)
282 = rnArithSeq seq `thenM` \ (new_seq, fvs) ->
283 return (ArithSeq noPostTcExpr new_seq, fvs)
285 rnExpr (PArrSeq _ seq)
286 = rnArithSeq seq `thenM` \ (new_seq, fvs) ->
287 return (PArrSeq noPostTcExpr new_seq, fvs)
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.
295 rnExpr e@EWildPat = patSynErr e
296 rnExpr e@(EAsPat {}) = patSynErr e
297 rnExpr e@(EViewPat {}) = patSynErr e
298 rnExpr e@(ELazyPat {}) = patSynErr e
301 %************************************************************************
305 %************************************************************************
308 rnExpr (HsProc pat body)
310 rnPat ProcExpr pat $ \ pat' ->
311 rnCmdTop body `thenM` \ (body',fvBody) ->
312 return (HsProc pat' body', fvBody)
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)
320 select_arrow_scope tc = case ho of
321 HsHigherOrderApp -> tc
322 HsFirstOrderApp -> escapeArrowScope tc
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) ->
334 lookupFixityRn op_name `thenM` \ fixity ->
335 mkOpFormRn arg1' op' fixity arg2' `thenM` \ final_e ->
338 fv_arg1 `plusFV` fv_op `plusFV` fv_arg2)
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)
345 rnExpr other = pprPanic "rnExpr: unexpected expression" (ppr other)
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) }
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) }
363 rnSection other = pprPanic "rnSection" (ppr other)
366 %************************************************************************
370 %************************************************************************
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) }
381 rn_field fld = do { (arg', fvs) <- rnLExpr (hsRecFieldArg fld)
382 ; return (fld { hsRecFieldArg = arg' }, fvs) }
386 %************************************************************************
390 %************************************************************************
393 rnCmdArgs :: [LHsCmdTop RdrName] -> RnM ([LHsCmdTop Name], FreeVars)
394 rnCmdArgs [] = return ([], emptyFVs)
396 = rnCmdTop arg `thenM` \ (arg',fvArg) ->
397 rnCmdArgs args `thenM` \ (args',fvArgs) ->
398 return (arg':args', fvArg `plusFV` fvArgs)
400 rnCmdTop :: LHsCmdTop RdrName -> RnM (LHsCmdTop Name, FreeVars)
401 rnCmdTop = wrapLocFstM rnCmdTop'
403 rnCmdTop' (HsCmdTop cmd _ _ _)
404 = rnLExpr (convertOpFormsLCmd cmd) `thenM` \ (cmd', fvCmd) ->
406 cmd_names = [arrAName, composeAName, firstAName] ++
407 nameSetToList (methodNamesCmd (unLoc cmd'))
409 -- Generate the rebindable syntax for the monad
410 lookupSyntaxTable cmd_names `thenM` \ (cmd_names', cmd_fvs) ->
412 return (HsCmdTop cmd' [] placeHolderType cmd_names',
413 fvCmd `plusFV` cmd_fvs)
415 ---------------------------------------------------
416 -- convert OpApp's in a command context to HsArrForm's
418 convertOpFormsLCmd :: LHsCmd id -> LHsCmd id
419 convertOpFormsLCmd = fmap convertOpFormsCmd
421 convertOpFormsCmd :: HsCmd id -> HsCmd id
423 convertOpFormsCmd (HsApp c e) = HsApp (convertOpFormsLCmd c) e
424 convertOpFormsCmd (HsLam match) = HsLam (convertOpFormsMatch match)
425 convertOpFormsCmd (OpApp c1 op fixity c2)
427 arg1 = L (getLoc c1) $ HsCmdTop (convertOpFormsLCmd c1) [] placeHolderType []
428 arg2 = L (getLoc c2) $ HsCmdTop (convertOpFormsLCmd c2) [] placeHolderType []
430 HsArrForm op (Just fixity) [arg1, arg2]
432 convertOpFormsCmd (HsPar c) = HsPar (convertOpFormsLCmd c)
434 convertOpFormsCmd (HsCase exp matches)
435 = HsCase exp (convertOpFormsMatch matches)
437 convertOpFormsCmd (HsIf f exp c1 c2)
438 = HsIf f exp (convertOpFormsLCmd c1) (convertOpFormsLCmd c2)
440 convertOpFormsCmd (HsLet binds cmd)
441 = HsLet binds (convertOpFormsLCmd cmd)
443 convertOpFormsCmd (HsDo DoExpr stmts ty)
444 = HsDo ArrowExpr (map (fmap convertOpFormsStmt) stmts) ty
445 -- Mark the HsDo as begin the body of an arrow command
447 -- Anything else is unchanged. This includes HsArrForm (already done),
448 -- things with no sub-commands, and illegal commands (which will be
449 -- caught by the type checker)
450 convertOpFormsCmd c = c
452 convertOpFormsStmt :: StmtLR id id -> StmtLR id id
453 convertOpFormsStmt (BindStmt pat cmd _ _)
454 = BindStmt pat (convertOpFormsLCmd cmd) noSyntaxExpr noSyntaxExpr
455 convertOpFormsStmt (ExprStmt cmd _ _ _)
456 = ExprStmt (convertOpFormsLCmd cmd) noSyntaxExpr noSyntaxExpr placeHolderType
457 convertOpFormsStmt stmt@(RecStmt { recS_stmts = stmts })
458 = stmt { recS_stmts = map (fmap convertOpFormsStmt) stmts }
459 convertOpFormsStmt stmt = stmt
461 convertOpFormsMatch :: MatchGroup id -> MatchGroup id
462 convertOpFormsMatch (MatchGroup ms ty)
463 = MatchGroup (map (fmap convert) ms) ty
464 where convert (Match pat mty grhss)
465 = Match pat mty (convertOpFormsGRHSs grhss)
467 convertOpFormsGRHSs :: GRHSs id -> GRHSs id
468 convertOpFormsGRHSs (GRHSs grhss binds)
469 = GRHSs (map convertOpFormsGRHS grhss) binds
471 convertOpFormsGRHS :: Located (GRHS id) -> Located (GRHS id)
472 convertOpFormsGRHS = fmap convert
474 convert (GRHS stmts cmd) = GRHS stmts (convertOpFormsLCmd cmd)
476 ---------------------------------------------------
477 type CmdNeeds = FreeVars -- Only inhabitants are
478 -- appAName, choiceAName, loopAName
480 -- find what methods the Cmd needs (loop, choice, apply)
481 methodNamesLCmd :: LHsCmd Name -> CmdNeeds
482 methodNamesLCmd = methodNamesCmd . unLoc
484 methodNamesCmd :: HsCmd Name -> CmdNeeds
486 methodNamesCmd (HsArrApp _arrow _arg _ HsFirstOrderApp _rtl)
488 methodNamesCmd (HsArrApp _arrow _arg _ HsHigherOrderApp _rtl)
490 methodNamesCmd (HsArrForm {}) = emptyFVs
492 methodNamesCmd (HsPar c) = methodNamesLCmd c
494 methodNamesCmd (HsIf _ _ c1 c2)
495 = methodNamesLCmd c1 `plusFV` methodNamesLCmd c2 `addOneFV` choiceAName
497 methodNamesCmd (HsLet _ c) = methodNamesLCmd c
498 methodNamesCmd (HsDo _ stmts _) = methodNamesStmts stmts
499 methodNamesCmd (HsApp c _) = methodNamesLCmd c
500 methodNamesCmd (HsLam match) = methodNamesMatch match
502 methodNamesCmd (HsCase _ matches)
503 = methodNamesMatch matches `addOneFV` choiceAName
505 methodNamesCmd _ = emptyFVs
506 -- Other forms can't occur in commands, but it's not convenient
507 -- to error here so we just do what's convenient.
508 -- The type checker will complain later
510 ---------------------------------------------------
511 methodNamesMatch :: MatchGroup Name -> FreeVars
512 methodNamesMatch (MatchGroup ms _)
513 = plusFVs (map do_one ms)
515 do_one (L _ (Match _ _ grhss)) = methodNamesGRHSs grhss
517 -------------------------------------------------
519 methodNamesGRHSs :: GRHSs Name -> FreeVars
520 methodNamesGRHSs (GRHSs grhss _) = plusFVs (map methodNamesGRHS grhss)
522 -------------------------------------------------
524 methodNamesGRHS :: Located (GRHS Name) -> CmdNeeds
525 methodNamesGRHS (L _ (GRHS _ rhs)) = methodNamesLCmd rhs
527 ---------------------------------------------------
528 methodNamesStmts :: [Located (StmtLR Name Name)] -> FreeVars
529 methodNamesStmts stmts = plusFVs (map methodNamesLStmt stmts)
531 ---------------------------------------------------
532 methodNamesLStmt :: Located (StmtLR Name Name) -> FreeVars
533 methodNamesLStmt = methodNamesStmt . unLoc
535 methodNamesStmt :: StmtLR Name Name -> FreeVars
536 methodNamesStmt (LastStmt cmd _) = methodNamesLCmd cmd
537 methodNamesStmt (ExprStmt cmd _ _ _) = methodNamesLCmd cmd
538 methodNamesStmt (BindStmt _ cmd _ _) = methodNamesLCmd cmd
539 methodNamesStmt (RecStmt { recS_stmts = stmts }) = methodNamesStmts stmts `addOneFV` loopAName
540 methodNamesStmt (LetStmt _) = emptyFVs
541 methodNamesStmt (ParStmt _ _ _ _) = emptyFVs
542 methodNamesStmt (TransStmt {}) = emptyFVs
543 -- ParStmt and TransStmt can't occur in commands, but it's not convenient to error
544 -- here so we just do what's convenient
548 %************************************************************************
552 %************************************************************************
555 rnArithSeq :: ArithSeqInfo RdrName -> RnM (ArithSeqInfo Name, FreeVars)
556 rnArithSeq (From expr)
557 = rnLExpr expr `thenM` \ (expr', fvExpr) ->
558 return (From expr', fvExpr)
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)
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)
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])
578 %************************************************************************
580 Template Haskell brackets
582 %************************************************************************
585 rnBracket :: HsBracket RdrName -> RnM (HsBracket Name, FreeVars)
587 = do { name <- lookupOccRn n
588 ; this_mod <- getModule
589 ; unless (nameIsLocalOrFrom this_mod name) $ -- Reason: deprecation checking assumes
590 do { _ <- loadInterfaceForName msg name -- the home interface is loaded, and
591 ; return () } -- this is the only way that is going
593 ; return (VarBr name, unitFV name) }
595 msg = ptext (sLit "Need interface for Template Haskell quoted Name")
597 rnBracket (ExpBr e) = do { (e', fvs) <- rnLExpr e
598 ; return (ExpBr e', fvs) }
600 rnBracket (PatBr p) = rnPat ThPatQuote p $ \ p' -> return (PatBr p', emptyFVs)
602 rnBracket (TypBr t) = do { (t', fvs) <- rnHsTypeFVs doc t
603 ; return (TypBr t', fvs) }
605 doc = ptext (sLit "In a Template-Haskell quoted type")
607 rnBracket (DecBrL decls)
608 = do { (group, mb_splice) <- findSplice decls
611 Just (SpliceDecl (L loc _) _, _)
613 addErr (ptext (sLit "Declaration splices are not permitted inside declaration brackets"))
614 -- Why not? See Section 7.3 of the TH paper.
616 ; gbl_env <- getGblEnv
617 ; let new_gbl_env = gbl_env { tcg_dus = emptyDUs }
618 -- The emptyDUs is so that we just collect uses for this
619 -- group alone in the call to rnSrcDecls below
620 ; (tcg_env, group') <- setGblEnv new_gbl_env $
624 -- Discard the tcg_env; it contains only extra info about fixity
625 ; traceRn (text "rnBracket dec" <+> (ppr (tcg_dus tcg_env) $$
626 ppr (duUses (tcg_dus tcg_env))))
627 ; return (DecBrG group', duUses (tcg_dus tcg_env)) }
629 rnBracket (DecBrG _) = panic "rnBracket: unexpected DecBrG"
632 %************************************************************************
634 \subsubsection{@Stmt@s: in @do@ expressions}
636 %************************************************************************
639 rnStmts :: HsStmtContext Name -> [LStmt RdrName]
640 -> ([Name] -> RnM (thing, FreeVars))
641 -> RnM (([LStmt Name], thing), FreeVars)
642 -- Variables bound by the Stmts, and mentioned in thing_inside,
643 -- do not appear in the result FreeVars
645 rnStmts ctxt [] thing_inside
646 = do { checkEmptyStmts ctxt
647 ; (thing, fvs) <- thing_inside []
648 ; return (([], thing), fvs) }
650 rnStmts MDoExpr stmts thing_inside -- Deal with mdo
651 = -- Behave like do { rec { ...all but last... }; last }
652 do { ((stmts1, (stmts2, thing)), fvs)
653 <- rnStmt MDoExpr (noLoc $ mkRecStmt all_but_last) $ \ _ ->
654 do { last_stmt' <- checkLastStmt MDoExpr last_stmt
655 ; rnStmt MDoExpr last_stmt' thing_inside }
656 ; return (((stmts1 ++ stmts2), thing), fvs) }
658 Just (all_but_last, last_stmt) = snocView stmts
660 rnStmts ctxt (lstmt@(L loc _) : lstmts) thing_inside
663 do { lstmt' <- checkLastStmt ctxt lstmt
664 ; rnStmt ctxt lstmt' thing_inside }
667 = do { ((stmts1, (stmts2, thing)), fvs)
669 do { checkStmt ctxt lstmt
670 ; rnStmt ctxt lstmt $ \ bndrs1 ->
671 rnStmts ctxt lstmts $ \ bndrs2 ->
672 thing_inside (bndrs1 ++ bndrs2) }
673 ; return (((stmts1 ++ stmts2), thing), fvs) }
675 ----------------------
676 rnStmt :: HsStmtContext Name
678 -> ([Name] -> RnM (thing, FreeVars))
679 -> RnM (([LStmt Name], thing), FreeVars)
680 -- Variables bound by the Stmt, and mentioned in thing_inside,
681 -- do not appear in the result FreeVars
683 rnStmt ctxt (L loc (LastStmt expr _)) thing_inside
684 = do { (expr', fv_expr) <- rnLExpr expr
685 ; (ret_op, fvs1) <- lookupStmtName ctxt returnMName
686 ; (thing, fvs3) <- thing_inside []
687 ; return (([L loc (LastStmt expr' ret_op)], thing),
688 fv_expr `plusFV` fvs1 `plusFV` fvs3) }
690 rnStmt ctxt (L loc (ExprStmt expr _ _ _)) thing_inside
691 = do { (expr', fv_expr) <- rnLExpr expr
692 ; (then_op, fvs1) <- lookupStmtName ctxt thenMName
693 ; (guard_op, fvs2) <- if isListCompExpr ctxt
694 then lookupStmtName ctxt guardMName
695 else return (noSyntaxExpr, emptyFVs)
696 -- Only list/parr/monad comprehensions use 'guard'
697 ; (thing, fvs3) <- thing_inside []
698 ; return (([L loc (ExprStmt expr' then_op guard_op placeHolderType)], thing),
699 fv_expr `plusFV` fvs1 `plusFV` fvs2 `plusFV` fvs3) }
701 rnStmt ctxt (L loc (BindStmt pat expr _ _)) thing_inside
702 = do { (expr', fv_expr) <- rnLExpr expr
703 -- The binders do not scope over the expression
704 ; (bind_op, fvs1) <- lookupStmtName ctxt bindMName
705 ; (fail_op, fvs2) <- lookupStmtName ctxt failMName
706 ; rnPat (StmtCtxt ctxt) pat $ \ pat' -> do
707 { (thing, fvs3) <- thing_inside (collectPatBinders pat')
708 ; return (([L loc (BindStmt pat' expr' bind_op fail_op)], thing),
709 fv_expr `plusFV` fvs1 `plusFV` fvs2 `plusFV` fvs3) }}
710 -- fv_expr shouldn't really be filtered by the rnPatsAndThen
711 -- but it does not matter because the names are unique
713 rnStmt _ (L loc (LetStmt binds)) thing_inside
714 = do { rnLocalBindsAndThen binds $ \binds' -> do
715 { (thing, fvs) <- thing_inside (collectLocalBinders binds')
716 ; return (([L loc (LetStmt binds')], thing), fvs) } }
718 rnStmt ctxt (L _ (RecStmt { recS_stmts = rec_stmts })) thing_inside
720 -- Step1: Bring all the binders of the mdo into scope
721 -- (Remember that this also removes the binders from the
722 -- finally-returned free-vars.)
723 -- And rename each individual stmt, making a
724 -- singleton segment. At this stage the FwdRefs field
725 -- isn't finished: it's empty for all except a BindStmt
726 -- for which it's the fwd refs within the bind itself
727 -- (This set may not be empty, because we're in a recursive
729 ; rnRecStmtsAndThen rec_stmts $ \ segs -> do
731 { let bndrs = nameSetToList $ foldr (unionNameSets . (\(ds,_,_,_) -> ds))
733 ; (thing, fvs_later) <- thing_inside bndrs
734 ; (return_op, fvs1) <- lookupStmtName ctxt returnMName
735 ; (mfix_op, fvs2) <- lookupStmtName ctxt mfixName
736 ; (bind_op, fvs3) <- lookupStmtName ctxt bindMName
738 -- Step 2: Fill in the fwd refs.
739 -- The segments are all singletons, but their fwd-ref
740 -- field mentions all the things used by the segment
741 -- that are bound after their use
742 segs_w_fwd_refs = addFwdRefs segs
744 -- Step 3: Group together the segments to make bigger segments
745 -- Invariant: in the result, no segment uses a variable
746 -- bound in a later segment
747 grouped_segs = glomSegments segs_w_fwd_refs
749 -- Step 4: Turn the segments into Stmts
750 -- Use RecStmt when and only when there are fwd refs
751 -- Also gather up the uses from the end towards the
752 -- start, so we can tell the RecStmt which things are
753 -- used 'after' the RecStmt
754 empty_rec_stmt = emptyRecStmt { recS_ret_fn = return_op
755 , recS_mfix_fn = mfix_op
756 , recS_bind_fn = bind_op }
757 (rec_stmts', fvs) = segsToStmts empty_rec_stmt grouped_segs fvs_later
759 ; return ((rec_stmts', thing), fvs `plusFV` fvs1 `plusFV` fvs2 `plusFV` fvs3) } }
761 rnStmt ctxt (L loc (ParStmt segs _ _ _)) thing_inside
762 = do { (mzip_op, fvs1) <- lookupStmtName ctxt mzipName
763 ; (bind_op, fvs2) <- lookupStmtName ctxt bindMName
764 ; (return_op, fvs3) <- lookupStmtName ctxt returnMName
765 ; ((segs', thing), fvs4) <- rnParallelStmts (ParStmtCtxt ctxt) segs thing_inside
766 ; return ( ([L loc (ParStmt segs' mzip_op bind_op return_op)], thing)
767 , fvs1 `plusFV` fvs2 `plusFV` fvs3 `plusFV` fvs4) }
769 rnStmt ctxt (L loc (TransStmt { trS_stmts = stmts, trS_by = by, trS_form = form
770 , trS_using = using })) thing_inside
771 = do { -- Rename the 'using' expression in the context before the transform is begun
772 (using', fvs1) <- case form of
773 GroupFormB -> do { (e,fvs) <- lookupStmtName ctxt groupMName
774 ; return (noLoc e, fvs) }
777 -- Rename the stmts and the 'by' expression
778 -- Keep track of the variables mentioned in the 'by' expression
779 ; ((stmts', (by', used_bndrs, thing)), fvs2)
780 <- rnStmts (TransStmtCtxt ctxt) stmts $ \ bndrs ->
781 do { (by', fvs_by) <- mapMaybeFvRn rnLExpr by
782 ; (thing, fvs_thing) <- thing_inside bndrs
783 ; let fvs = fvs_by `plusFV` fvs_thing
784 used_bndrs = filter (`elemNameSet` fvs) bndrs
785 -- The paper (Fig 5) has a bug here; we must treat any free varaible
786 -- of the "thing inside", **or of the by-expression**, as used
787 ; return ((by', used_bndrs, thing), fvs) }
789 -- Lookup `return`, `(>>=)` and `liftM` for monad comprehensions
790 ; (return_op, fvs3) <- lookupStmtName ctxt returnMName
791 ; (bind_op, fvs4) <- lookupStmtName ctxt bindMName
792 ; (fmap_op, fvs5) <- case form of
793 ThenForm -> return (noSyntaxExpr, emptyFVs)
794 _ -> lookupStmtName ctxt fmapName
796 ; let all_fvs = fvs1 `plusFV` fvs2 `plusFV` fvs3
797 `plusFV` fvs4 `plusFV` fvs5
798 bndr_map = used_bndrs `zip` used_bndrs
799 -- See Note [TransStmt binder map] in HsExpr
801 ; traceRn (text "rnStmt: implicitly rebound these used binders:" <+> ppr bndr_map)
802 ; return (([L loc (TransStmt { trS_stmts = stmts', trS_bndrs = bndr_map
803 , trS_by = by', trS_using = using', trS_form = form
804 , trS_ret = return_op, trS_bind = bind_op
805 , trS_fmap = fmap_op })], thing), all_fvs) }
807 type ParSeg id = ([LStmt id], [id]) -- The Names are bound by the Stmts
809 rnParallelStmts :: forall thing. HsStmtContext Name
811 -> ([Name] -> RnM (thing, FreeVars))
812 -> RnM (([ParSeg Name], thing), FreeVars)
813 -- Note [Renaming parallel Stmts]
814 rnParallelStmts ctxt segs thing_inside
815 = do { orig_lcl_env <- getLocalRdrEnv
816 ; rn_segs orig_lcl_env [] segs }
818 rn_segs :: LocalRdrEnv
819 -> [Name] -> [ParSeg RdrName]
820 -> RnM (([ParSeg Name], thing), FreeVars)
821 rn_segs _ bndrs_so_far []
822 = do { let (bndrs', dups) = removeDups cmpByOcc bndrs_so_far
824 ; (thing, fvs) <- bindLocalNames bndrs' (thing_inside bndrs')
825 ; return (([], thing), fvs) }
827 rn_segs env bndrs_so_far ((stmts,_) : segs)
828 = do { ((stmts', (used_bndrs, segs', thing)), fvs)
829 <- rnStmts ctxt stmts $ \ bndrs ->
830 setLocalRdrEnv env $ do
831 { ((segs', thing), fvs) <- rn_segs env (bndrs ++ bndrs_so_far) segs
832 ; let used_bndrs = filter (`elemNameSet` fvs) bndrs
833 ; return ((used_bndrs, segs', thing), fvs) }
835 ; let seg' = (stmts', used_bndrs)
836 ; return ((seg':segs', thing), fvs) }
838 cmpByOcc n1 n2 = nameOccName n1 `compare` nameOccName n2
839 dupErr vs = addErr (ptext (sLit "Duplicate binding in parallel list comprehension for:")
840 <+> quotes (ppr (head vs)))
842 lookupStmtName :: HsStmtContext Name -> Name -> RnM (HsExpr Name, FreeVars)
843 -- Like lookupSyntaxName, but ListComp/PArrComp are never rebindable
844 lookupStmtName ListComp n = return (HsVar n, emptyFVs)
845 lookupStmtName PArrComp n = return (HsVar n, emptyFVs)
846 lookupStmtName _ n = lookupSyntaxName n
849 Note [Renaming parallel Stmts]
850 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
851 Renaming parallel statements is painful. Given, say
852 [ a+c | a <- as, bs <- bss
855 (a) In order to report "Defined by not used" about 'bs', we must rename
856 each group of Stmts with a thing_inside whose FreeVars include at least {a,c}
858 (b) We want to report that 'a' is illegally bound in both branches
860 (c) The 'bs' in the second group must obviously not be captured by
861 the binding in the first group
863 To satisfy (a) we nest the segements.
864 To satisfy (b) we check for duplicates just before thing_inside.
865 To satisfy (c) we reset the LocalRdrEnv each time.
867 %************************************************************************
869 \subsubsection{mdo expressions}
871 %************************************************************************
874 type FwdRefs = NameSet
875 type Segment stmts = (Defs,
876 Uses, -- May include defs
877 FwdRefs, -- A subset of uses that are
878 -- (a) used before they are bound in this segment, or
879 -- (b) used here, and bound in subsequent segments
880 stmts) -- Either Stmt or [Stmt]
883 -- wrapper that does both the left- and right-hand sides
884 rnRecStmtsAndThen :: [LStmt RdrName]
885 -- assumes that the FreeVars returned includes
886 -- the FreeVars of the Segments
887 -> ([Segment (LStmt Name)] -> RnM (a, FreeVars))
889 rnRecStmtsAndThen s cont
890 = do { -- (A) Make the mini fixity env for all of the stmts
891 fix_env <- makeMiniFixityEnv (collectRecStmtsFixities s)
894 ; new_lhs_and_fv <- rn_rec_stmts_lhs fix_env s
896 -- ...bring them and their fixities into scope
897 ; let bound_names = collectLStmtsBinders (map fst new_lhs_and_fv)
898 -- Fake uses of variables introduced implicitly (warning suppression, see #4404)
899 implicit_uses = lStmtsImplicits (map fst new_lhs_and_fv)
900 ; bindLocalNamesFV bound_names $
901 addLocalFixities fix_env bound_names $ do
903 -- (C) do the right-hand-sides and thing-inside
904 { segs <- rn_rec_stmts bound_names new_lhs_and_fv
905 ; (res, fvs) <- cont segs
906 ; warnUnusedLocalBinds bound_names (fvs `unionNameSets` implicit_uses)
907 ; return (res, fvs) }}
909 -- get all the fixity decls in any Let stmt
910 collectRecStmtsFixities :: [LStmtLR RdrName RdrName] -> [LFixitySig RdrName]
911 collectRecStmtsFixities l =
912 foldr (\ s -> \acc -> case s of
913 (L _ (LetStmt (HsValBinds (ValBindsIn _ sigs)))) ->
914 foldr (\ sig -> \ acc -> case sig of
915 (L loc (FixSig s)) -> (L loc s) : acc
921 rn_rec_stmt_lhs :: MiniFixityEnv
923 -- rename LHS, and return its FVs
924 -- Warning: we will only need the FreeVars below in the case of a BindStmt,
925 -- so we don't bother to compute it accurately in the other cases
926 -> RnM [(LStmtLR Name RdrName, FreeVars)]
928 rn_rec_stmt_lhs _ (L loc (ExprStmt expr a b c))
929 = return [(L loc (ExprStmt expr a b c), emptyFVs)]
931 rn_rec_stmt_lhs _ (L loc (LastStmt expr a))
932 = return [(L loc (LastStmt expr a), emptyFVs)]
934 rn_rec_stmt_lhs fix_env (L loc (BindStmt pat expr a b))
936 -- should the ctxt be MDo instead?
937 (pat', fv_pat) <- rnBindPat (localRecNameMaker fix_env) pat
938 return [(L loc (BindStmt pat' expr a b),
941 rn_rec_stmt_lhs _ (L _ (LetStmt binds@(HsIPBinds _)))
942 = failWith (badIpBinds (ptext (sLit "an mdo expression")) binds)
944 rn_rec_stmt_lhs fix_env (L loc (LetStmt (HsValBinds binds)))
945 = do (_bound_names, binds') <- rnLocalValBindsLHS fix_env binds
946 return [(L loc (LetStmt (HsValBinds binds')),
947 -- Warning: this is bogus; see function invariant
951 -- XXX Do we need to do something with the return and mfix names?
952 rn_rec_stmt_lhs fix_env (L _ (RecStmt { recS_stmts = stmts })) -- Flatten Rec inside Rec
953 = rn_rec_stmts_lhs fix_env stmts
955 rn_rec_stmt_lhs _ stmt@(L _ (ParStmt _ _ _ _)) -- Syntactically illegal in mdo
956 = pprPanic "rn_rec_stmt" (ppr stmt)
958 rn_rec_stmt_lhs _ stmt@(L _ (TransStmt {})) -- Syntactically illegal in mdo
959 = pprPanic "rn_rec_stmt" (ppr stmt)
961 rn_rec_stmt_lhs _ (L _ (LetStmt EmptyLocalBinds))
962 = panic "rn_rec_stmt LetStmt EmptyLocalBinds"
964 rn_rec_stmts_lhs :: MiniFixityEnv
966 -> RnM [(LStmtLR Name RdrName, FreeVars)]
967 rn_rec_stmts_lhs fix_env stmts
968 = do { ls <- concatMapM (rn_rec_stmt_lhs fix_env) stmts
969 ; let boundNames = collectLStmtsBinders (map fst ls)
970 -- First do error checking: we need to check for dups here because we
971 -- don't bind all of the variables from the Stmt at once
972 -- with bindLocatedLocals.
973 ; checkDupNames boundNames
979 rn_rec_stmt :: [Name] -> LStmtLR Name RdrName -> FreeVars -> RnM [Segment (LStmt Name)]
980 -- Rename a Stmt that is inside a RecStmt (or mdo)
981 -- Assumes all binders are already in scope
982 -- Turns each stmt into a singleton Stmt
983 rn_rec_stmt _ (L loc (LastStmt expr _)) _
984 = do { (expr', fv_expr) <- rnLExpr expr
985 ; (ret_op, fvs1) <- lookupSyntaxName returnMName
986 ; return [(emptyNameSet, fv_expr `plusFV` fvs1, emptyNameSet,
987 L loc (LastStmt expr' ret_op))] }
989 rn_rec_stmt _ (L loc (ExprStmt expr _ _ _)) _
990 = rnLExpr expr `thenM` \ (expr', fvs) ->
991 lookupSyntaxName thenMName `thenM` \ (then_op, fvs1) ->
992 return [(emptyNameSet, fvs `plusFV` fvs1, emptyNameSet,
993 L loc (ExprStmt expr' then_op noSyntaxExpr placeHolderType))]
995 rn_rec_stmt _ (L loc (BindStmt pat' expr _ _)) fv_pat
996 = rnLExpr expr `thenM` \ (expr', fv_expr) ->
997 lookupSyntaxName bindMName `thenM` \ (bind_op, fvs1) ->
998 lookupSyntaxName failMName `thenM` \ (fail_op, fvs2) ->
1000 bndrs = mkNameSet (collectPatBinders pat')
1001 fvs = fv_expr `plusFV` fv_pat `plusFV` fvs1 `plusFV` fvs2
1003 return [(bndrs, fvs, bndrs `intersectNameSet` fvs,
1004 L loc (BindStmt pat' expr' bind_op fail_op))]
1006 rn_rec_stmt _ (L _ (LetStmt binds@(HsIPBinds _))) _
1007 = failWith (badIpBinds (ptext (sLit "an mdo expression")) binds)
1009 rn_rec_stmt all_bndrs (L loc (LetStmt (HsValBinds binds'))) _ = do
1010 (binds', du_binds) <-
1011 -- fixities and unused are handled above in rnRecStmtsAndThen
1012 rnLocalValBindsRHS (mkNameSet all_bndrs) binds'
1013 return [(duDefs du_binds, allUses du_binds,
1014 emptyNameSet, L loc (LetStmt (HsValBinds binds')))]
1016 -- no RecStmt case becuase they get flattened above when doing the LHSes
1017 rn_rec_stmt _ stmt@(L _ (RecStmt {})) _
1018 = pprPanic "rn_rec_stmt: RecStmt" (ppr stmt)
1020 rn_rec_stmt _ stmt@(L _ (ParStmt {})) _ -- Syntactically illegal in mdo
1021 = pprPanic "rn_rec_stmt: ParStmt" (ppr stmt)
1023 rn_rec_stmt _ stmt@(L _ (TransStmt {})) _ -- Syntactically illegal in mdo
1024 = pprPanic "rn_rec_stmt: TransStmt" (ppr stmt)
1026 rn_rec_stmt _ (L _ (LetStmt EmptyLocalBinds)) _
1027 = panic "rn_rec_stmt: LetStmt EmptyLocalBinds"
1029 rn_rec_stmts :: [Name] -> [(LStmtLR Name RdrName, FreeVars)] -> RnM [Segment (LStmt Name)]
1030 rn_rec_stmts bndrs stmts = mapM (uncurry (rn_rec_stmt bndrs)) stmts `thenM` \ segs_s ->
1031 return (concat segs_s)
1033 ---------------------------------------------
1034 addFwdRefs :: [Segment a] -> [Segment a]
1035 -- So far the segments only have forward refs *within* the Stmt
1036 -- (which happens for bind: x <- ...x...)
1037 -- This function adds the cross-seg fwd ref info
1040 = fst (foldr mk_seg ([], emptyNameSet) pairs)
1042 mk_seg (defs, uses, fwds, stmts) (segs, later_defs)
1043 = (new_seg : segs, all_defs)
1045 new_seg = (defs, uses, new_fwds, stmts)
1046 all_defs = later_defs `unionNameSets` defs
1047 new_fwds = fwds `unionNameSets` (uses `intersectNameSet` later_defs)
1048 -- Add the downstream fwd refs here
1050 ----------------------------------------------------
1051 -- Glomming the singleton segments of an mdo into
1052 -- minimal recursive groups.
1054 -- At first I thought this was just strongly connected components, but
1055 -- there's an important constraint: the order of the stmts must not change.
1058 -- mdo { x <- ...y...
1065 -- Here, the first stmt mention 'y', which is bound in the third.
1066 -- But that means that the innocent second stmt (p <- z) gets caught
1067 -- up in the recursion. And that in turn means that the binding for
1068 -- 'z' has to be included... and so on.
1070 -- Start at the tail { r <- x }
1071 -- Now add the next one { z <- y ; r <- x }
1072 -- Now add one more { q <- x ; z <- y ; r <- x }
1073 -- Now one more... but this time we have to group a bunch into rec
1074 -- { rec { y <- ...x... ; q <- x ; z <- y } ; r <- x }
1075 -- Now one more, which we can add on without a rec
1077 -- rec { y <- ...x... ; q <- x ; z <- y } ;
1079 -- Finally we add the last one; since it mentions y we have to
1080 -- glom it togeher with the first two groups
1081 -- { rec { x <- ...y...; p <- z ; y <- ...x... ;
1082 -- q <- x ; z <- y } ;
1085 glomSegments :: [Segment (LStmt Name)] -> [Segment [LStmt Name]]
1087 glomSegments [] = []
1088 glomSegments ((defs,uses,fwds,stmt) : segs)
1089 -- Actually stmts will always be a singleton
1090 = (seg_defs, seg_uses, seg_fwds, seg_stmts) : others
1092 segs' = glomSegments segs
1093 (extras, others) = grab uses segs'
1094 (ds, us, fs, ss) = unzip4 extras
1096 seg_defs = plusFVs ds `plusFV` defs
1097 seg_uses = plusFVs us `plusFV` uses
1098 seg_fwds = plusFVs fs `plusFV` fwds
1099 seg_stmts = stmt : concat ss
1101 grab :: NameSet -- The client
1103 -> ([Segment a], -- Needed by the 'client'
1104 [Segment a]) -- Not needed by the client
1105 -- The result is simply a split of the input
1107 = (reverse yeses, reverse noes)
1109 (noes, yeses) = span not_needed (reverse dus)
1110 not_needed (defs,_,_,_) = not (intersectsNameSet defs uses)
1113 ----------------------------------------------------
1114 segsToStmts :: Stmt Name -- A RecStmt with the SyntaxOps filled in
1115 -> [Segment [LStmt Name]]
1116 -> FreeVars -- Free vars used 'later'
1117 -> ([LStmt Name], FreeVars)
1119 segsToStmts _ [] fvs_later = ([], fvs_later)
1120 segsToStmts empty_rec_stmt ((defs, uses, fwds, ss) : segs) fvs_later
1121 = ASSERT( not (null ss) )
1122 (new_stmt : later_stmts, later_uses `plusFV` uses)
1124 (later_stmts, later_uses) = segsToStmts empty_rec_stmt segs fvs_later
1125 new_stmt | non_rec = head ss
1126 | otherwise = L (getLoc (head ss)) rec_stmt
1127 rec_stmt = empty_rec_stmt { recS_stmts = ss
1128 , recS_later_ids = nameSetToList used_later
1129 , recS_rec_ids = nameSetToList fwds }
1130 non_rec = isSingleton ss && isEmptyNameSet fwds
1131 used_later = defs `intersectNameSet` later_uses
1132 -- The ones needed after the RecStmt
1135 %************************************************************************
1137 \subsubsection{Assertion utils}
1139 %************************************************************************
1142 srcSpanPrimLit :: SrcSpan -> HsExpr Name
1143 srcSpanPrimLit span = HsLit (HsStringPrim (mkFastString (showSDocOneLine (ppr span))))
1145 mkAssertErrorExpr :: RnM (HsExpr Name)
1146 -- Return an expression for (assertError "Foo.hs:27")
1148 = getSrcSpanM `thenM` \ sloc ->
1149 return (HsApp (L sloc (HsVar assertErrorName))
1150 (L sloc (srcSpanPrimLit sloc)))
1153 Note [Adding the implicit parameter to 'assert']
1154 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1155 The renamer transforms (assert e1 e2) to (assert "Foo.hs:27" e1 e2).
1156 By doing this in the renamer we allow the typechecker to just see the
1157 expanded application and do the right thing. But it's not really
1158 the Right Thing because there's no way to "undo" if you want to see
1159 the original source code. We'll have fix this in due course, when
1160 we care more about being able to reconstruct the exact original
1163 %************************************************************************
1165 \subsubsection{Errors}
1167 %************************************************************************
1170 checkEmptyStmts :: HsStmtContext Name -> RnM ()
1171 -- We've seen an empty sequence of Stmts... is that ok?
1172 checkEmptyStmts ctxt
1173 = unless (okEmpty ctxt) (addErr (emptyErr ctxt))
1175 okEmpty :: HsStmtContext a -> Bool
1176 okEmpty (PatGuard {}) = True
1179 emptyErr :: HsStmtContext Name -> SDoc
1180 emptyErr (ParStmtCtxt {}) = ptext (sLit "Empty statement group in parallel comprehension")
1181 emptyErr (TransStmtCtxt {}) = ptext (sLit "Empty statement group preceding 'group' or 'then'")
1182 emptyErr ctxt = ptext (sLit "Empty") <+> pprStmtContext ctxt
1184 ----------------------
1185 checkLastStmt :: HsStmtContext Name
1187 -> RnM (LStmt RdrName)
1188 checkLastStmt ctxt lstmt@(L loc stmt)
1190 ListComp -> check_comp
1191 MonadComp -> check_comp
1192 PArrComp -> check_comp
1193 ArrowExpr -> check_do
1198 check_do -- Expect ExprStmt, and change it to LastStmt
1200 ExprStmt e _ _ _ -> return (L loc (mkLastStmt e))
1201 LastStmt {} -> return lstmt -- "Deriving" clauses may generate a
1202 -- LastStmt directly (unlike the parser)
1203 _ -> do { addErr (hang last_error 2 (ppr stmt)); return lstmt }
1204 last_error = (ptext (sLit "The last statement in") <+> pprAStmtContext ctxt
1205 <+> ptext (sLit "must be an expression"))
1207 check_comp -- Expect LastStmt; this should be enforced by the parser!
1209 LastStmt {} -> return lstmt
1210 _ -> pprPanic "checkLastStmt" (ppr lstmt)
1212 check_other -- Behave just as if this wasn't the last stmt
1213 = do { checkStmt ctxt lstmt; return lstmt }
1215 -- Checking when a particular Stmt is ok
1216 checkStmt :: HsStmtContext Name
1219 checkStmt ctxt (L _ stmt)
1220 = do { dflags <- getDOpts
1221 ; case okStmt dflags ctxt stmt of
1222 Nothing -> return ()
1223 Just extra -> addErr (msg $$ extra) }
1225 msg = sep [ ptext (sLit "Unexpected") <+> pprStmtCat stmt <+> ptext (sLit "statement")
1226 , ptext (sLit "in") <+> pprAStmtContext ctxt ]
1228 pprStmtCat :: Stmt a -> SDoc
1229 pprStmtCat (TransStmt {}) = ptext (sLit "transform")
1230 pprStmtCat (LastStmt {}) = ptext (sLit "return expression")
1231 pprStmtCat (ExprStmt {}) = ptext (sLit "exprssion")
1232 pprStmtCat (BindStmt {}) = ptext (sLit "binding")
1233 pprStmtCat (LetStmt {}) = ptext (sLit "let")
1234 pprStmtCat (RecStmt {}) = ptext (sLit "rec")
1235 pprStmtCat (ParStmt {}) = ptext (sLit "parallel")
1238 isOK, notOK :: Maybe SDoc
1242 okStmt, okDoStmt, okCompStmt, okParStmt, okPArrStmt
1243 :: DynFlags -> HsStmtContext Name
1244 -> Stmt RdrName -> Maybe SDoc
1245 -- Return Nothing if OK, (Just extra) if not ok
1246 -- The "extra" is an SDoc that is appended to an generic error message
1248 okStmt dflags ctxt stmt
1250 PatGuard {} -> okPatGuardStmt stmt
1251 ParStmtCtxt ctxt -> okParStmt dflags ctxt stmt
1252 DoExpr -> okDoStmt dflags ctxt stmt
1253 MDoExpr -> okDoStmt dflags ctxt stmt
1254 ArrowExpr -> okDoStmt dflags ctxt stmt
1255 GhciStmt -> okDoStmt dflags ctxt stmt
1256 ListComp -> okCompStmt dflags ctxt stmt
1257 MonadComp -> okCompStmt dflags ctxt stmt
1258 PArrComp -> okPArrStmt dflags ctxt stmt
1259 TransStmtCtxt ctxt -> okStmt dflags ctxt stmt
1262 okPatGuardStmt :: Stmt RdrName -> Maybe SDoc
1271 okParStmt dflags ctxt stmt
1273 LetStmt (HsIPBinds {}) -> notOK
1274 _ -> okStmt dflags ctxt stmt
1277 okDoStmt dflags ctxt stmt
1280 | Opt_DoRec `xopt` dflags -> isOK
1281 | ArrowExpr <- ctxt -> isOK -- Arrows allows 'rec'
1282 | otherwise -> Just (ptext (sLit "Use -XDoRec"))
1289 okCompStmt dflags _ stmt
1295 | Opt_ParallelListComp `xopt` dflags -> isOK
1296 | otherwise -> Just (ptext (sLit "Use -XParallelListComp"))
1298 | Opt_TransformListComp `xopt` dflags -> isOK
1299 | otherwise -> Just (ptext (sLit "Use -XTransformListComp"))
1301 LastStmt {} -> notOK -- Should not happen (dealt with by checkLastStmt)
1304 okPArrStmt dflags _ stmt
1310 | Opt_ParallelListComp `xopt` dflags -> isOK
1311 | otherwise -> Just (ptext (sLit "Use -XParallelListComp"))
1312 TransStmt {} -> notOK
1314 LastStmt {} -> notOK -- Should not happen (dealt with by checkLastStmt)
1317 checkTupleSection :: [HsTupArg RdrName] -> RnM ()
1318 checkTupleSection args
1319 = do { tuple_section <- xoptM Opt_TupleSections
1320 ; checkErr (all tupArgPresent args || tuple_section) msg }
1322 msg = ptext (sLit "Illegal tuple section: use -XTupleSections")
1325 sectionErr :: HsExpr RdrName -> SDoc
1327 = hang (ptext (sLit "A section must be enclosed in parentheses"))
1328 2 (ptext (sLit "thus:") <+> (parens (ppr expr)))
1330 patSynErr :: HsExpr RdrName -> RnM (HsExpr Name, FreeVars)
1331 patSynErr e = do { addErr (sep [ptext (sLit "Pattern syntax in expression context:"),
1333 ; return (EWildPat, emptyFVs) }
1335 badIpBinds :: Outputable a => SDoc -> a -> SDoc
1336 badIpBinds what binds
1337 = hang (ptext (sLit "Implicit-parameter bindings illegal in") <+> what)