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 -- The above warning supression flag is a temporary kludge.
15 -- While working on this module you are encouraged to remove it and fix
16 -- any warnings in the module. See
17 -- http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
21 rnLExpr, rnExpr, rnStmts
24 #include "HsVersions.h"
26 import RnSource ( rnSrcDecls, rnSplice, checkTH )
27 import RnBinds ( rnLocalBindsAndThen, rnValBindsLHS, rnValBindsRHS,
28 rnMatchGroup, makeMiniFixityEnv)
32 import HscTypes ( availNames )
33 import RnNames ( getLocalDeclBinders, extendRdrEnvRn )
34 import RnTypes ( rnHsTypeFVs,
35 mkOpFormRn, mkOpAppRn, mkNegAppRn, checkSectionPrec)
36 import RnPat (rnOverLit, rnPatsAndThen_LocalRightwards, rnPat_LocalRec, localNameMaker,
38 rnHsRecFields_Con, rnHsRecFields_Update, checkTupSize)
39 import DynFlags ( DynFlag(..) )
40 import BasicTypes ( FixityDirection(..) )
41 import SrcLoc ( SrcSpan )
42 import PrelNames ( thFAKE, hasKey, assertIdKey, assertErrorName,
43 loopAName, choiceAName, appAName, arrAName, composeAName, firstAName,
44 negateName, thenMName, bindMName, failMName )
46 import Name ( Name, nameOccName, nameIsLocalOrFrom )
49 import RdrName ( RdrName, extendLocalRdrEnv, lookupLocalRdrEnv, hideSomeUnquals )
50 import LoadIface ( loadInterfaceForName )
51 import UniqFM ( isNullUFM )
52 import UniqSet ( emptyUniqSet )
54 import Util ( isSingleton )
55 import ListSetOps ( removeDups )
56 import Maybes ( expectJust )
58 import SrcLoc ( Located(..), unLoc, getLoc )
61 import List ( unzip4 )
65 %************************************************************************
67 \subsubsection{Expressions}
69 %************************************************************************
72 rnExprs :: [LHsExpr RdrName] -> RnM ([LHsExpr Name], FreeVars)
73 rnExprs ls = rnExprs' ls emptyUniqSet
75 rnExprs' [] acc = returnM ([], acc)
76 rnExprs' (expr:exprs) acc
77 = rnLExpr expr `thenM` \ (expr', fvExpr) ->
79 -- Now we do a "seq" on the free vars because typically it's small
80 -- or empty, especially in very long lists of constants
82 acc' = acc `plusFV` fvExpr
84 (grubby_seqNameSet acc' rnExprs') exprs acc' `thenM` \ (exprs', fvExprs) ->
85 returnM (expr':exprs', fvExprs)
87 -- Grubby little function to do "seq" on namesets; replace by proper seq when GHC can do seq
88 grubby_seqNameSet ns result | isNullUFM ns = result
92 Variables. We look up the variable and return the resulting name.
95 rnLExpr :: LHsExpr RdrName -> RnM (LHsExpr Name, FreeVars)
96 rnLExpr = wrapLocFstM rnExpr
98 rnExpr :: HsExpr RdrName -> RnM (HsExpr Name, FreeVars)
101 = do name <- lookupOccRn v
102 ignore_asserts <- doptM Opt_IgnoreAsserts
103 finish_var ignore_asserts name
105 finish_var ignore_asserts name
106 | ignore_asserts || not (name `hasKey` assertIdKey)
107 = return (HsVar name, unitFV name)
109 = do { (e, fvs) <- mkAssertErrorExpr
110 ; return (e, fvs `addOneFV` name) }
113 = newIPNameRn v `thenM` \ name ->
114 returnM (HsIPVar name, emptyFVs)
116 rnExpr (HsLit lit@(HsString s))
118 opt_OverloadedStrings <- doptM Opt_OverloadedStrings
119 ; if opt_OverloadedStrings then
120 rnExpr (HsOverLit (mkHsIsString s placeHolderType))
121 else -- Same as below
123 returnM (HsLit lit, emptyFVs)
128 returnM (HsLit lit, emptyFVs)
130 rnExpr (HsOverLit lit)
131 = rnOverLit lit `thenM` \ (lit', fvs) ->
132 returnM (HsOverLit lit', fvs)
134 rnExpr (HsApp fun arg)
135 = rnLExpr fun `thenM` \ (fun',fvFun) ->
136 rnLExpr arg `thenM` \ (arg',fvArg) ->
137 returnM (HsApp fun' arg', fvFun `plusFV` fvArg)
139 rnExpr (OpApp e1 op _ e2)
140 = rnLExpr e1 `thenM` \ (e1', fv_e1) ->
141 rnLExpr e2 `thenM` \ (e2', fv_e2) ->
142 rnLExpr op `thenM` \ (op'@(L _ (HsVar op_name)), fv_op) ->
145 -- When renaming code synthesised from "deriving" declarations
146 -- we used to avoid fixity stuff, but we can't easily tell any
147 -- more, so I've removed the test. Adding HsPars in TcGenDeriv
148 -- should prevent bad things happening.
149 lookupFixityRn op_name `thenM` \ fixity ->
150 mkOpAppRn e1' op' fixity e2' `thenM` \ final_e ->
153 fv_e1 `plusFV` fv_op `plusFV` fv_e2)
156 = rnLExpr e `thenM` \ (e', fv_e) ->
157 lookupSyntaxName negateName `thenM` \ (neg_name, fv_neg) ->
158 mkNegAppRn e' neg_name `thenM` \ final_e ->
159 returnM (final_e, fv_e `plusFV` fv_neg)
162 = rnLExpr e `thenM` \ (e', fvs_e) ->
163 returnM (HsPar e', fvs_e)
165 -- Template Haskell extensions
166 -- Don't ifdef-GHCI them because we want to fail gracefully
167 -- (not with an rnExpr crash) in a stage-1 compiler.
168 rnExpr e@(HsBracket br_body)
169 = checkTH e "bracket" `thenM_`
170 rnBracket br_body `thenM` \ (body', fvs_e) ->
171 returnM (HsBracket body', fvs_e)
173 rnExpr e@(HsSpliceE splice)
174 = rnSplice splice `thenM` \ (splice', fvs) ->
175 returnM (HsSpliceE splice', fvs)
177 rnExpr section@(SectionL expr op)
178 = rnLExpr expr `thenM` \ (expr', fvs_expr) ->
179 rnLExpr op `thenM` \ (op', fvs_op) ->
180 checkSectionPrec InfixL section op' expr' `thenM_`
181 returnM (SectionL expr' op', fvs_op `plusFV` fvs_expr)
183 rnExpr section@(SectionR op expr)
184 = rnLExpr op `thenM` \ (op', fvs_op) ->
185 rnLExpr expr `thenM` \ (expr', fvs_expr) ->
186 checkSectionPrec InfixR section op' expr' `thenM_`
187 returnM (SectionR op' expr', fvs_op `plusFV` fvs_expr)
189 rnExpr (HsCoreAnn ann expr)
190 = rnLExpr expr `thenM` \ (expr', fvs_expr) ->
191 returnM (HsCoreAnn ann expr', fvs_expr)
193 rnExpr (HsSCC lbl expr)
194 = rnLExpr expr `thenM` \ (expr', fvs_expr) ->
195 returnM (HsSCC lbl expr', fvs_expr)
196 rnExpr (HsTickPragma info expr)
197 = rnLExpr expr `thenM` \ (expr', fvs_expr) ->
198 returnM (HsTickPragma info expr', fvs_expr)
200 rnExpr (HsLam matches)
201 = rnMatchGroup LambdaExpr matches `thenM` \ (matches', fvMatch) ->
202 returnM (HsLam matches', fvMatch)
204 rnExpr (HsCase expr matches)
205 = rnLExpr expr `thenM` \ (new_expr, e_fvs) ->
206 rnMatchGroup CaseAlt matches `thenM` \ (new_matches, ms_fvs) ->
207 returnM (HsCase new_expr new_matches, e_fvs `plusFV` ms_fvs)
209 rnExpr (HsLet binds expr)
210 = rnLocalBindsAndThen binds $ \ binds' ->
211 rnLExpr expr `thenM` \ (expr',fvExpr) ->
212 returnM (HsLet binds' expr', fvExpr)
214 rnExpr e@(HsDo do_or_lc stmts body _)
215 = do { ((stmts', body'), fvs) <- rnStmts do_or_lc stmts $
217 ; return (HsDo do_or_lc stmts' body' placeHolderType, fvs) }
219 rnExpr (ExplicitList _ exps)
220 = rnExprs exps `thenM` \ (exps', fvs) ->
221 returnM (ExplicitList placeHolderType exps', fvs)
223 rnExpr (ExplicitPArr _ exps)
224 = rnExprs exps `thenM` \ (exps', fvs) ->
225 returnM (ExplicitPArr placeHolderType exps', fvs)
227 rnExpr e@(ExplicitTuple exps boxity)
228 = checkTupSize (length exps) `thenM_`
229 rnExprs exps `thenM` \ (exps', fvs) ->
230 returnM (ExplicitTuple exps' boxity, fvs)
232 rnExpr (RecordCon con_id _ rbinds)
233 = do { conname <- lookupLocatedOccRn con_id
234 ; (rbinds', fvRbinds) <- rnHsRecFields_Con conname rnLExpr rbinds
235 ; return (RecordCon conname noPostTcExpr rbinds',
236 fvRbinds `addOneFV` unLoc conname) }
238 rnExpr (RecordUpd expr rbinds _ _ _)
239 = do { (expr', fvExpr) <- rnLExpr expr
240 ; (rbinds', fvRbinds) <- rnHsRecFields_Update rnLExpr rbinds
241 ; return (RecordUpd expr' rbinds' [] [] [],
242 fvExpr `plusFV` fvRbinds) }
244 rnExpr (ExprWithTySig expr pty)
245 = do { (pty', fvTy) <- rnHsTypeFVs doc pty
246 ; (expr', fvExpr) <- bindSigTyVarsFV (hsExplicitTvs pty') $
248 ; return (ExprWithTySig expr' pty', fvExpr `plusFV` fvTy) }
250 doc = text "In an expression type signature"
252 rnExpr (HsIf p b1 b2)
253 = rnLExpr p `thenM` \ (p', fvP) ->
254 rnLExpr b1 `thenM` \ (b1', fvB1) ->
255 rnLExpr b2 `thenM` \ (b2', fvB2) ->
256 returnM (HsIf p' b1' b2', plusFVs [fvP, fvB1, fvB2])
259 = rnHsTypeFVs doc a `thenM` \ (t, fvT) ->
260 returnM (HsType t, fvT)
262 doc = text "In a type argument"
264 rnExpr (ArithSeq _ seq)
265 = rnArithSeq seq `thenM` \ (new_seq, fvs) ->
266 returnM (ArithSeq noPostTcExpr new_seq, fvs)
268 rnExpr (PArrSeq _ seq)
269 = rnArithSeq seq `thenM` \ (new_seq, fvs) ->
270 returnM (PArrSeq noPostTcExpr new_seq, fvs)
273 These three are pattern syntax appearing in expressions.
274 Since all the symbols are reservedops we can simply reject them.
275 We return a (bogus) EWildPat in each case.
278 rnExpr e@EWildPat = patSynErr e
279 rnExpr e@(EAsPat {}) = patSynErr e
280 rnExpr e@(ELazyPat {}) = patSynErr e
283 %************************************************************************
287 %************************************************************************
290 rnExpr (HsProc pat body)
292 rnPatsAndThen_LocalRightwards ProcExpr [pat] $ \ ([pat'],_) ->
293 rnCmdTop body `thenM` \ (body',fvBody) ->
294 returnM (HsProc pat' body', fvBody)
296 rnExpr (HsArrApp arrow arg _ ho rtl)
297 = select_arrow_scope (rnLExpr arrow) `thenM` \ (arrow',fvArrow) ->
298 rnLExpr arg `thenM` \ (arg',fvArg) ->
299 returnM (HsArrApp arrow' arg' placeHolderType ho rtl,
300 fvArrow `plusFV` fvArg)
302 select_arrow_scope tc = case ho of
303 HsHigherOrderApp -> tc
304 HsFirstOrderApp -> escapeArrowScope tc
307 rnExpr (HsArrForm op (Just _) [arg1, arg2])
308 = escapeArrowScope (rnLExpr op)
309 `thenM` \ (op'@(L _ (HsVar op_name)),fv_op) ->
310 rnCmdTop arg1 `thenM` \ (arg1',fv_arg1) ->
311 rnCmdTop arg2 `thenM` \ (arg2',fv_arg2) ->
315 lookupFixityRn op_name `thenM` \ fixity ->
316 mkOpFormRn arg1' op' fixity arg2' `thenM` \ final_e ->
319 fv_arg1 `plusFV` fv_op `plusFV` fv_arg2)
321 rnExpr (HsArrForm op fixity cmds)
322 = escapeArrowScope (rnLExpr op) `thenM` \ (op',fvOp) ->
323 rnCmdArgs cmds `thenM` \ (cmds',fvCmds) ->
324 returnM (HsArrForm op' fixity cmds', fvOp `plusFV` fvCmds)
326 rnExpr other = pprPanic "rnExpr: unexpected expression" (ppr other)
331 %************************************************************************
335 %************************************************************************
338 rnCmdArgs [] = returnM ([], emptyFVs)
340 = rnCmdTop arg `thenM` \ (arg',fvArg) ->
341 rnCmdArgs args `thenM` \ (args',fvArgs) ->
342 returnM (arg':args', fvArg `plusFV` fvArgs)
345 rnCmdTop = wrapLocFstM rnCmdTop'
347 rnCmdTop' (HsCmdTop cmd _ _ _)
348 = rnLExpr (convertOpFormsLCmd cmd) `thenM` \ (cmd', fvCmd) ->
350 cmd_names = [arrAName, composeAName, firstAName] ++
351 nameSetToList (methodNamesCmd (unLoc cmd'))
353 -- Generate the rebindable syntax for the monad
354 lookupSyntaxTable cmd_names `thenM` \ (cmd_names', cmd_fvs) ->
356 returnM (HsCmdTop cmd' [] placeHolderType cmd_names',
357 fvCmd `plusFV` cmd_fvs)
359 ---------------------------------------------------
360 -- convert OpApp's in a command context to HsArrForm's
362 convertOpFormsLCmd :: LHsCmd id -> LHsCmd id
363 convertOpFormsLCmd = fmap convertOpFormsCmd
365 convertOpFormsCmd :: HsCmd id -> HsCmd id
367 convertOpFormsCmd (HsApp c e) = HsApp (convertOpFormsLCmd c) e
368 convertOpFormsCmd (HsLam match) = HsLam (convertOpFormsMatch match)
369 convertOpFormsCmd (OpApp c1 op fixity c2)
371 arg1 = L (getLoc c1) $ HsCmdTop (convertOpFormsLCmd c1) [] placeHolderType []
372 arg2 = L (getLoc c2) $ HsCmdTop (convertOpFormsLCmd c2) [] placeHolderType []
374 HsArrForm op (Just fixity) [arg1, arg2]
376 convertOpFormsCmd (HsPar c) = HsPar (convertOpFormsLCmd c)
379 convertOpFormsCmd (HsCase exp matches)
380 = HsCase exp (convertOpFormsMatch matches)
382 convertOpFormsCmd (HsIf exp c1 c2)
383 = HsIf exp (convertOpFormsLCmd c1) (convertOpFormsLCmd c2)
385 convertOpFormsCmd (HsLet binds cmd)
386 = HsLet binds (convertOpFormsLCmd cmd)
388 convertOpFormsCmd (HsDo ctxt stmts body ty)
389 = HsDo ctxt (map (fmap convertOpFormsStmt) stmts)
390 (convertOpFormsLCmd body) ty
392 -- Anything else is unchanged. This includes HsArrForm (already done),
393 -- things with no sub-commands, and illegal commands (which will be
394 -- caught by the type checker)
395 convertOpFormsCmd c = c
397 convertOpFormsStmt (BindStmt pat cmd _ _)
398 = BindStmt pat (convertOpFormsLCmd cmd) noSyntaxExpr noSyntaxExpr
399 convertOpFormsStmt (ExprStmt cmd _ _)
400 = ExprStmt (convertOpFormsLCmd cmd) noSyntaxExpr placeHolderType
401 convertOpFormsStmt (RecStmt stmts lvs rvs es binds)
402 = RecStmt (map (fmap convertOpFormsStmt) stmts) lvs rvs es binds
403 convertOpFormsStmt stmt = stmt
405 convertOpFormsMatch (MatchGroup ms ty)
406 = MatchGroup (map (fmap convert) ms) ty
407 where convert (Match pat mty grhss)
408 = Match pat mty (convertOpFormsGRHSs grhss)
410 convertOpFormsGRHSs (GRHSs grhss binds)
411 = GRHSs (map convertOpFormsGRHS grhss) binds
413 convertOpFormsGRHS = fmap convert
415 convert (GRHS stmts cmd) = GRHS stmts (convertOpFormsLCmd cmd)
417 ---------------------------------------------------
418 type CmdNeeds = FreeVars -- Only inhabitants are
419 -- appAName, choiceAName, loopAName
421 -- find what methods the Cmd needs (loop, choice, apply)
422 methodNamesLCmd :: LHsCmd Name -> CmdNeeds
423 methodNamesLCmd = methodNamesCmd . unLoc
425 methodNamesCmd :: HsCmd Name -> CmdNeeds
427 methodNamesCmd cmd@(HsArrApp _arrow _arg _ HsFirstOrderApp _rtl)
429 methodNamesCmd cmd@(HsArrApp _arrow _arg _ HsHigherOrderApp _rtl)
431 methodNamesCmd cmd@(HsArrForm {}) = emptyFVs
433 methodNamesCmd (HsPar c) = methodNamesLCmd c
435 methodNamesCmd (HsIf p c1 c2)
436 = methodNamesLCmd c1 `plusFV` methodNamesLCmd c2 `addOneFV` choiceAName
438 methodNamesCmd (HsLet b c) = methodNamesLCmd c
440 methodNamesCmd (HsDo sc stmts body ty)
441 = methodNamesStmts stmts `plusFV` methodNamesLCmd body
443 methodNamesCmd (HsApp c e) = methodNamesLCmd c
445 methodNamesCmd (HsLam match) = methodNamesMatch match
447 methodNamesCmd (HsCase scrut matches)
448 = methodNamesMatch matches `addOneFV` choiceAName
450 methodNamesCmd other = emptyFVs
451 -- Other forms can't occur in commands, but it's not convenient
452 -- to error here so we just do what's convenient.
453 -- The type checker will complain later
455 ---------------------------------------------------
456 methodNamesMatch (MatchGroup ms _)
457 = plusFVs (map do_one ms)
459 do_one (L _ (Match pats sig_ty grhss)) = methodNamesGRHSs grhss
461 -------------------------------------------------
463 methodNamesGRHSs (GRHSs grhss binds) = plusFVs (map methodNamesGRHS grhss)
465 -------------------------------------------------
466 methodNamesGRHS (L _ (GRHS stmts rhs)) = methodNamesLCmd rhs
468 ---------------------------------------------------
469 methodNamesStmts stmts = plusFVs (map methodNamesLStmt stmts)
471 ---------------------------------------------------
472 methodNamesLStmt = methodNamesStmt . unLoc
474 methodNamesStmt (ExprStmt cmd _ _) = methodNamesLCmd cmd
475 methodNamesStmt (BindStmt pat cmd _ _) = methodNamesLCmd cmd
476 methodNamesStmt (RecStmt stmts _ _ _ _)
477 = methodNamesStmts stmts `addOneFV` loopAName
478 methodNamesStmt (LetStmt b) = emptyFVs
479 methodNamesStmt (ParStmt ss) = emptyFVs
480 -- ParStmt can't occur in commands, but it's not convenient to error
481 -- here so we just do what's convenient
485 %************************************************************************
489 %************************************************************************
492 rnArithSeq (From expr)
493 = rnLExpr expr `thenM` \ (expr', fvExpr) ->
494 returnM (From expr', fvExpr)
496 rnArithSeq (FromThen expr1 expr2)
497 = rnLExpr expr1 `thenM` \ (expr1', fvExpr1) ->
498 rnLExpr expr2 `thenM` \ (expr2', fvExpr2) ->
499 returnM (FromThen expr1' expr2', fvExpr1 `plusFV` fvExpr2)
501 rnArithSeq (FromTo expr1 expr2)
502 = rnLExpr expr1 `thenM` \ (expr1', fvExpr1) ->
503 rnLExpr expr2 `thenM` \ (expr2', fvExpr2) ->
504 returnM (FromTo expr1' expr2', fvExpr1 `plusFV` fvExpr2)
506 rnArithSeq (FromThenTo expr1 expr2 expr3)
507 = rnLExpr expr1 `thenM` \ (expr1', fvExpr1) ->
508 rnLExpr expr2 `thenM` \ (expr2', fvExpr2) ->
509 rnLExpr expr3 `thenM` \ (expr3', fvExpr3) ->
510 returnM (FromThenTo expr1' expr2' expr3',
511 plusFVs [fvExpr1, fvExpr2, fvExpr3])
514 %************************************************************************
516 Template Haskell brackets
518 %************************************************************************
521 rnBracket (VarBr n) = do { name <- lookupOccRn n
522 ; this_mod <- getModule
523 ; checkM (nameIsLocalOrFrom this_mod name) $ -- Reason: deprecation checking asumes the
524 do { loadInterfaceForName msg name -- home interface is loaded, and this is the
525 ; return () } -- only way that is going to happen
526 ; returnM (VarBr name, unitFV name) }
528 msg = ptext SLIT("Need interface for Template Haskell quoted Name")
530 rnBracket (ExpBr e) = do { (e', fvs) <- rnLExpr e
531 ; return (ExpBr e', fvs) }
533 rnBracket (PatBr p) = do { addErr (ptext SLIT("Tempate Haskell pattern brackets are not supported yet"));
536 rnBracket (TypBr t) = do { (t', fvs) <- rnHsTypeFVs doc t
537 ; return (TypBr t', fvs) }
539 doc = ptext SLIT("In a Template-Haskell quoted type")
540 rnBracket (DecBr group)
541 = do { gbl_env <- getGblEnv
543 ; let new_gbl_env = gbl_env { -- Set the module to thFAKE. The top-level names from the bracketed
544 -- declarations will go into the name cache, and we don't want them to
545 -- confuse the Names for the current module.
546 -- By using a pretend module, thFAKE, we keep them safely out of the way.
549 -- The emptyDUs is so that we just collect uses for this group alone
550 -- in the call to rnSrcDecls below
552 ; setGblEnv new_gbl_env $ do {
554 -- In this situation we want to *shadow* top-level bindings.
556 -- bar = [d| foo = 1 |]
557 -- If we don't shadow, we'll get an ambiguity complaint when we do
558 -- a lookupTopBndrRn (which uses lookupGreLocalRn) on the binder of the 'foo'
560 -- Furthermore, arguably if the splice does define foo, that should hide
561 -- any foo's further out
563 -- The shadowing is acheived by calling rnSrcDecls with True as the shadowing flag
564 ; (tcg_env, group') <- rnSrcDecls True group
566 -- Discard the tcg_env; it contains only extra info about fixity
567 ; return (DecBr group', allUses (tcg_dus tcg_env)) } }
570 %************************************************************************
572 \subsubsection{@Stmt@s: in @do@ expressions}
574 %************************************************************************
577 rnStmts :: HsStmtContext Name -> [LStmt RdrName]
578 -> RnM (thing, FreeVars)
579 -> RnM (([LStmt Name], thing), FreeVars)
581 rnStmts (MDoExpr _) = rnMDoStmts
582 rnStmts ctxt = rnNormalStmts ctxt
584 rnNormalStmts :: HsStmtContext Name -> [LStmt RdrName]
585 -> RnM (thing, FreeVars)
586 -> RnM (([LStmt Name], thing), FreeVars)
587 -- Used for cases *other* than recursive mdo
588 -- Implements nested scopes
590 rnNormalStmts ctxt [] thing_inside
591 = do { (thing, fvs) <- thing_inside
592 ; return (([],thing), fvs) }
594 rnNormalStmts ctxt (L loc stmt : stmts) thing_inside
595 = do { ((stmt', (stmts', thing)), fvs)
596 <- rnStmt ctxt stmt $
597 rnNormalStmts ctxt stmts thing_inside
598 ; return (((L loc stmt' : stmts'), thing), fvs) }
601 rnStmt :: HsStmtContext Name -> Stmt RdrName
602 -> RnM (thing, FreeVars)
603 -> RnM ((Stmt Name, thing), FreeVars)
605 rnStmt ctxt (ExprStmt expr _ _) thing_inside
606 = do { (expr', fv_expr) <- rnLExpr expr
607 ; (then_op, fvs1) <- lookupSyntaxName thenMName
608 ; (thing, fvs2) <- thing_inside
609 ; return ((ExprStmt expr' then_op placeHolderType, thing),
610 fv_expr `plusFV` fvs1 `plusFV` fvs2) }
612 rnStmt ctxt (BindStmt pat expr _ _) thing_inside
613 = do { (expr', fv_expr) <- rnLExpr expr
614 -- The binders do not scope over the expression
615 ; (bind_op, fvs1) <- lookupSyntaxName bindMName
616 ; (fail_op, fvs2) <- lookupSyntaxName failMName
617 ; rnPatsAndThen_LocalRightwards (StmtCtxt ctxt) [pat] $ \ ([pat'],_) -> do
618 { (thing, fvs3) <- thing_inside
619 ; return ((BindStmt pat' expr' bind_op fail_op, thing),
620 fv_expr `plusFV` fvs1 `plusFV` fvs2 `plusFV` fvs3) }}
621 -- fv_expr shouldn't really be filtered by the rnPatsAndThen
622 -- but it does not matter because the names are unique
624 rnStmt ctxt (LetStmt binds) thing_inside
625 = do { checkErr (ok ctxt binds)
626 (badIpBinds (ptext SLIT("a parallel list comprehension:")) binds)
627 ; rnLocalBindsAndThen binds $ \ binds' -> do
628 { (thing, fvs) <- thing_inside
629 ; return ((LetStmt binds', thing), fvs) }}
631 -- We do not allow implicit-parameter bindings in a parallel
632 -- list comprehension. I'm not sure what it might mean.
633 ok (ParStmtCtxt _) (HsIPBinds _) = False
636 rnStmt ctxt (RecStmt rec_stmts _ _ _ _) thing_inside
638 rn_rec_stmts_and_then rec_stmts $ \ segs ->
639 thing_inside `thenM` \ (thing, fvs) ->
641 segs_w_fwd_refs = addFwdRefs segs
642 (ds, us, fs, rec_stmts') = unzip4 segs_w_fwd_refs
643 later_vars = nameSetToList (plusFVs ds `intersectNameSet` fvs)
644 fwd_vars = nameSetToList (plusFVs fs)
646 rec_stmt = RecStmt rec_stmts' later_vars fwd_vars [] emptyLHsBinds
648 returnM ((rec_stmt, thing), uses `plusFV` fvs)
650 doc = text "In a recursive do statement"
652 rnStmt ctxt (ParStmt segs) thing_inside
653 = do { parallel_list_comp <- doptM Opt_ParallelListComp
654 ; checkM parallel_list_comp parStmtErr
655 ; orig_lcl_env <- getLocalRdrEnv
656 ; ((segs',thing), fvs) <- go orig_lcl_env [] segs
657 ; return ((ParStmt segs', thing), fvs) }
659 -- type ParSeg id = [([LStmt id], [id])]
660 -- go :: NameSet -> [ParSeg RdrName]
661 -- -> RnM (([ParSeg Name], thing), FreeVars)
663 go orig_lcl_env bndrs []
664 = do { let { (bndrs', dups) = removeDups cmpByOcc bndrs
665 ; inner_env = extendLocalRdrEnv orig_lcl_env bndrs' }
667 ; (thing, fvs) <- setLocalRdrEnv inner_env thing_inside
668 ; return (([], thing), fvs) }
670 go orig_lcl_env bndrs_so_far ((stmts, _) : segs)
671 = do { ((stmts', (bndrs, segs', thing)), fvs)
672 <- rnNormalStmts par_ctxt stmts $ do
673 { -- Find the Names that are bound by stmts
674 lcl_env <- getLocalRdrEnv
675 ; let { rdr_bndrs = collectLStmtsBinders stmts
676 ; bndrs = map ( expectJust "rnStmt"
677 . lookupLocalRdrEnv lcl_env
679 ; new_bndrs = nub bndrs ++ bndrs_so_far
680 -- The nub is because there might be shadowing
682 -- So we'll look up (Unqual x) twice, getting
683 -- the second binding both times, which is the
686 -- Typecheck the thing inside, passing on all
687 -- the Names bound, but separately; revert the envt
688 ; ((segs', thing), fvs) <- setLocalRdrEnv orig_lcl_env $
689 go orig_lcl_env new_bndrs segs
691 -- Figure out which of the bound names are used
692 ; let used_bndrs = filter (`elemNameSet` fvs) bndrs
693 ; return ((used_bndrs, segs', thing), fvs) }
695 ; let seg' = (stmts', bndrs)
696 ; return (((seg':segs'), thing),
697 delListFromNameSet fvs bndrs) }
699 par_ctxt = ParStmtCtxt ctxt
701 cmpByOcc n1 n2 = nameOccName n1 `compare` nameOccName n2
702 dupErr vs = addErr (ptext SLIT("Duplicate binding in parallel list comprehension for:")
703 <+> quotes (ppr (head vs)))
707 %************************************************************************
709 \subsubsection{mdo expressions}
711 %************************************************************************
714 type FwdRefs = NameSet
715 type Segment stmts = (Defs,
716 Uses, -- May include defs
717 FwdRefs, -- A subset of uses that are
718 -- (a) used before they are bound in this segment, or
719 -- (b) used here, and bound in subsequent segments
720 stmts) -- Either Stmt or [Stmt]
723 ----------------------------------------------------
725 rnMDoStmts :: [LStmt RdrName]
726 -> RnM (thing, FreeVars)
727 -> RnM (([LStmt Name], thing), FreeVars)
728 rnMDoStmts stmts thing_inside
729 = -- Step1: Bring all the binders of the mdo into scope
730 -- (Remember that this also removes the binders from the
731 -- finally-returned free-vars.)
732 -- And rename each individual stmt, making a
733 -- singleton segment. At this stage the FwdRefs field
734 -- isn't finished: it's empty for all except a BindStmt
735 -- for which it's the fwd refs within the bind itself
736 -- (This set may not be empty, because we're in a recursive
738 rn_rec_stmts_and_then stmts $ \ segs -> do {
740 ; (thing, fvs_later) <- thing_inside
743 -- Step 2: Fill in the fwd refs.
744 -- The segments are all singletons, but their fwd-ref
745 -- field mentions all the things used by the segment
746 -- that are bound after their use
747 segs_w_fwd_refs = addFwdRefs segs
749 -- Step 3: Group together the segments to make bigger segments
750 -- Invariant: in the result, no segment uses a variable
751 -- bound in a later segment
752 grouped_segs = glomSegments segs_w_fwd_refs
754 -- Step 4: Turn the segments into Stmts
755 -- Use RecStmt when and only when there are fwd refs
756 -- Also gather up the uses from the end towards the
757 -- start, so we can tell the RecStmt which things are
758 -- used 'after' the RecStmt
759 (stmts', fvs) = segsToStmts grouped_segs fvs_later
761 ; return ((stmts', thing), fvs) }
763 doc = text "In a recursive mdo-expression"
765 ---------------------------------------------
767 -- wrapper that does both the left- and right-hand sides
768 rn_rec_stmts_and_then :: [LStmt RdrName]
769 -- assumes that the FreeVars returned includes
770 -- the FreeVars of the Segments
771 -> ([Segment (LStmt Name)] -> RnM (a, FreeVars))
773 rn_rec_stmts_and_then s cont = do
774 -- (A) make the mini fixity env for all of the stmts
775 fix_env <- makeMiniFixityEnv (collectRecStmtsFixities s)
778 new_lhs_and_fv <- rn_rec_stmts_lhs fix_env s
780 -- bring them and their fixities into scope
781 let bound_names = map unLoc $ collectLStmtsBinders (map fst new_lhs_and_fv)
782 bindLocalNamesFV_WithFixities bound_names fix_env $ do
784 -- (C) do the right-hand-sides and thing-inside
785 segs <- rn_rec_stmts bound_names new_lhs_and_fv
786 (result, result_fvs) <- cont segs
788 -- (D) warn about unusued binders
789 let unused_bndrs = [ b | b <- bound_names, not (b `elemNameSet` result_fvs)]
790 warnUnusedLocalBinds unused_bndrs
793 return (result, result_fvs)
796 -- get all the fixity decls in any Let stmt
797 collectRecStmtsFixities l =
798 foldr (\ s -> \acc -> case s of
799 (L loc (LetStmt (HsValBinds (ValBindsIn _ sigs)))) ->
800 foldr (\ sig -> \ acc -> case sig of
801 (L loc (FixSig s)) -> (L loc s) : acc
807 rn_rec_stmt_lhs :: UniqFM (Located Fixity) -- mini fixity env for the names we're about to bind
808 -- these fixities need to be brought into scope with the names
810 -- rename LHS, and return its FVs
811 -- Warning: we will only need the FreeVars below in the case of a BindStmt,
812 -- so we don't bother to compute it accurately in the other cases
813 -> RnM [(LStmtLR Name RdrName, FreeVars)]
815 rn_rec_stmt_lhs fix_env (L loc (ExprStmt expr a b)) = return [(L loc (ExprStmt expr a b),
816 -- this is actually correct
819 rn_rec_stmt_lhs fix_env (L loc (BindStmt pat expr a b))
821 -- should the ctxt be MDo instead?
822 (pat', fv_pat) <- rnPat_LocalRec fix_env pat
823 return [(L loc (BindStmt pat' expr a b),
826 rn_rec_stmt_lhs fix_env (L loc (LetStmt binds@(HsIPBinds _)))
827 = do { addErr (badIpBinds (ptext SLIT("an mdo expression")) binds)
830 rn_rec_stmt_lhs fix_env (L loc (LetStmt (HsValBinds binds)))
831 = do binds' <- rnValBindsLHS fix_env binds
832 return [(L loc (LetStmt (HsValBinds binds')),
833 -- Warning: this is bogus; see function invariant
837 rn_rec_stmt_lhs fix_env (L loc (RecStmt stmts _ _ _ _)) -- Flatten Rec inside Rec
838 = rn_rec_stmts_lhs fix_env stmts
840 rn_rec_stmt_lhs _ stmt@(L _ (ParStmt _)) -- Syntactically illegal in mdo
841 = pprPanic "rn_rec_stmt" (ppr stmt)
843 rn_rec_stmts_lhs :: UniqFM (Located Fixity) -- mini fixity env for the names we're about to bind
844 -- these fixities need to be brought into scope with the names
846 -> RnM [(LStmtLR Name RdrName, FreeVars)]
847 rn_rec_stmts_lhs fix_env stmts =
848 let boundNames = collectLStmtsBinders stmts
849 doc = text "In a recursive mdo-expression"
851 -- First do error checking: we need to check for dups here because we
852 -- don't bind all of the variables from the Stmt at once
853 -- with bindLocatedLocals.
854 checkDupNames doc boundNames
855 mappM (rn_rec_stmt_lhs fix_env) stmts `thenM` \ ls -> returnM (concat ls)
860 rn_rec_stmt :: [Name] -> LStmtLR Name RdrName -> FreeVars -> RnM [Segment (LStmt Name)]
861 -- Rename a Stmt that is inside a RecStmt (or mdo)
862 -- Assumes all binders are already in scope
863 -- Turns each stmt into a singleton Stmt
864 rn_rec_stmt all_bndrs (L loc (ExprStmt expr _ _)) _
865 = rnLExpr expr `thenM` \ (expr', fvs) ->
866 lookupSyntaxName thenMName `thenM` \ (then_op, fvs1) ->
867 returnM [(emptyNameSet, fvs `plusFV` fvs1, emptyNameSet,
868 L loc (ExprStmt expr' then_op placeHolderType))]
870 rn_rec_stmt all_bndrs (L loc (BindStmt pat' expr _ _)) fv_pat
871 = rnLExpr expr `thenM` \ (expr', fv_expr) ->
872 lookupSyntaxName bindMName `thenM` \ (bind_op, fvs1) ->
873 lookupSyntaxName failMName `thenM` \ (fail_op, fvs2) ->
875 bndrs = mkNameSet (collectPatBinders pat')
876 fvs = fv_expr `plusFV` fv_pat `plusFV` fvs1 `plusFV` fvs2
878 returnM [(bndrs, fvs, bndrs `intersectNameSet` fvs,
879 L loc (BindStmt pat' expr' bind_op fail_op))]
881 rn_rec_stmt all_bndrs (L loc (LetStmt binds@(HsIPBinds _))) _
882 = do { addErr (badIpBinds (ptext SLIT("an mdo expression")) binds)
885 rn_rec_stmt all_bndrs (L loc (LetStmt (HsValBinds binds'))) _ = do
886 (binds', du_binds) <-
887 -- fixities and unused are handled above in rn_rec_stmts_and_then
888 rnValBindsRHS all_bndrs binds'
889 returnM [(duDefs du_binds, duUses du_binds,
890 emptyNameSet, L loc (LetStmt (HsValBinds binds')))]
892 -- no RecStmt case becuase they get flattened above when doing the LHSes
893 rn_rec_stmt all_bndrs stmt@(L loc (RecStmt stmts _ _ _ _)) _
894 = pprPanic "rn_rec_stmt: RecStmt" (ppr stmt)
896 rn_rec_stmt all_bndrs stmt@(L _ (ParStmt _)) _ -- Syntactically illegal in mdo
897 = pprPanic "rn_rec_stmt: ParStmt" (ppr stmt)
899 rn_rec_stmts :: [Name] -> [(LStmtLR Name RdrName, FreeVars)] -> RnM [Segment (LStmt Name)]
900 rn_rec_stmts bndrs stmts = mappM (uncurry (rn_rec_stmt bndrs)) stmts `thenM` \ segs_s ->
901 returnM (concat segs_s)
903 ---------------------------------------------
904 addFwdRefs :: [Segment a] -> [Segment a]
905 -- So far the segments only have forward refs *within* the Stmt
906 -- (which happens for bind: x <- ...x...)
907 -- This function adds the cross-seg fwd ref info
910 = fst (foldr mk_seg ([], emptyNameSet) pairs)
912 mk_seg (defs, uses, fwds, stmts) (segs, later_defs)
913 = (new_seg : segs, all_defs)
915 new_seg = (defs, uses, new_fwds, stmts)
916 all_defs = later_defs `unionNameSets` defs
917 new_fwds = fwds `unionNameSets` (uses `intersectNameSet` later_defs)
918 -- Add the downstream fwd refs here
920 ----------------------------------------------------
921 -- Glomming the singleton segments of an mdo into
922 -- minimal recursive groups.
924 -- At first I thought this was just strongly connected components, but
925 -- there's an important constraint: the order of the stmts must not change.
928 -- mdo { x <- ...y...
935 -- Here, the first stmt mention 'y', which is bound in the third.
936 -- But that means that the innocent second stmt (p <- z) gets caught
937 -- up in the recursion. And that in turn means that the binding for
938 -- 'z' has to be included... and so on.
940 -- Start at the tail { r <- x }
941 -- Now add the next one { z <- y ; r <- x }
942 -- Now add one more { q <- x ; z <- y ; r <- x }
943 -- Now one more... but this time we have to group a bunch into rec
944 -- { rec { y <- ...x... ; q <- x ; z <- y } ; r <- x }
945 -- Now one more, which we can add on without a rec
947 -- rec { y <- ...x... ; q <- x ; z <- y } ;
949 -- Finally we add the last one; since it mentions y we have to
950 -- glom it togeher with the first two groups
951 -- { rec { x <- ...y...; p <- z ; y <- ...x... ;
952 -- q <- x ; z <- y } ;
955 glomSegments :: [Segment (LStmt Name)] -> [Segment [LStmt Name]]
958 glomSegments ((defs,uses,fwds,stmt) : segs)
959 -- Actually stmts will always be a singleton
960 = (seg_defs, seg_uses, seg_fwds, seg_stmts) : others
962 segs' = glomSegments segs
963 (extras, others) = grab uses segs'
964 (ds, us, fs, ss) = unzip4 extras
966 seg_defs = plusFVs ds `plusFV` defs
967 seg_uses = plusFVs us `plusFV` uses
968 seg_fwds = plusFVs fs `plusFV` fwds
969 seg_stmts = stmt : concat ss
971 grab :: NameSet -- The client
973 -> ([Segment a], -- Needed by the 'client'
974 [Segment a]) -- Not needed by the client
975 -- The result is simply a split of the input
977 = (reverse yeses, reverse noes)
979 (noes, yeses) = span not_needed (reverse dus)
980 not_needed (defs,_,_,_) = not (intersectsNameSet defs uses)
983 ----------------------------------------------------
984 segsToStmts :: [Segment [LStmt Name]]
985 -> FreeVars -- Free vars used 'later'
986 -> ([LStmt Name], FreeVars)
988 segsToStmts [] fvs_later = ([], fvs_later)
989 segsToStmts ((defs, uses, fwds, ss) : segs) fvs_later
990 = ASSERT( not (null ss) )
991 (new_stmt : later_stmts, later_uses `plusFV` uses)
993 (later_stmts, later_uses) = segsToStmts segs fvs_later
994 new_stmt | non_rec = head ss
995 | otherwise = L (getLoc (head ss)) $
996 RecStmt ss (nameSetToList used_later) (nameSetToList fwds)
999 non_rec = isSingleton ss && isEmptyNameSet fwds
1000 used_later = defs `intersectNameSet` later_uses
1001 -- The ones needed after the RecStmt
1004 %************************************************************************
1006 \subsubsection{Assertion utils}
1008 %************************************************************************
1011 srcSpanPrimLit :: SrcSpan -> HsExpr Name
1012 srcSpanPrimLit span = HsLit (HsStringPrim (mkFastString (showSDoc (ppr span))))
1014 mkAssertErrorExpr :: RnM (HsExpr Name, FreeVars)
1015 -- Return an expression for (assertError "Foo.hs:27")
1017 = getSrcSpanM `thenM` \ sloc ->
1019 expr = HsApp (L sloc (HsVar assertErrorName))
1020 (L sloc (srcSpanPrimLit sloc))
1022 returnM (expr, emptyFVs)
1025 %************************************************************************
1027 \subsubsection{Errors}
1029 %************************************************************************
1032 patSynErr e = do { addErr (sep [ptext SLIT("Pattern syntax in expression context:"),
1034 ; return (EWildPat, emptyFVs) }
1036 parStmtErr = addErr (ptext SLIT("Illegal parallel list comprehension: use -XParallelListComp"))
1038 badIpBinds what binds
1039 = hang (ptext SLIT("Implicit-parameter bindings illegal in") <+> what)