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, rnValBinds,
28 rnMatchGroup, trimWith )
32 import HscTypes ( availNames )
33 import RnNames ( getLocalDeclBinders, extendRdrEnvRn )
34 import RnTypes ( rnHsTypeFVs, rnLPat, rnOverLit, rnPatsAndThen, rnLit,
35 mkOpFormRn, mkOpAppRn, mkNegAppRn, checkSectionPrec,
36 rnHsRecFields, checkTupSize )
37 import DynFlags ( DynFlag(..) )
38 import BasicTypes ( FixityDirection(..) )
39 import SrcLoc ( SrcSpan )
40 import PrelNames ( thFAKE, hasKey, assertIdKey, assertErrorName,
41 loopAName, choiceAName, appAName, arrAName, composeAName, firstAName,
42 negateName, thenMName, bindMName, failMName )
44 import Name ( Name, nameOccName, nameIsLocalOrFrom )
46 import RdrName ( RdrName, extendLocalRdrEnv, lookupLocalRdrEnv, hideSomeUnquals )
47 import LoadIface ( loadInterfaceForName )
48 import UniqFM ( isNullUFM )
49 import UniqSet ( emptyUniqSet )
51 import Util ( isSingleton )
52 import ListSetOps ( removeDups )
53 import Maybes ( expectJust )
55 import SrcLoc ( Located(..), unLoc, getLoc )
58 import List ( unzip4 )
62 %************************************************************************
64 \subsubsection{Expressions}
66 %************************************************************************
69 rnExprs :: [LHsExpr RdrName] -> RnM ([LHsExpr Name], FreeVars)
70 rnExprs ls = rnExprs' ls emptyUniqSet
72 rnExprs' [] acc = returnM ([], acc)
73 rnExprs' (expr:exprs) acc
74 = rnLExpr expr `thenM` \ (expr', fvExpr) ->
76 -- Now we do a "seq" on the free vars because typically it's small
77 -- or empty, especially in very long lists of constants
79 acc' = acc `plusFV` fvExpr
81 (grubby_seqNameSet acc' rnExprs') exprs acc' `thenM` \ (exprs', fvExprs) ->
82 returnM (expr':exprs', fvExprs)
84 -- Grubby little function to do "seq" on namesets; replace by proper seq when GHC can do seq
85 grubby_seqNameSet ns result | isNullUFM ns = result
89 Variables. We look up the variable and return the resulting name.
92 rnLExpr :: LHsExpr RdrName -> RnM (LHsExpr Name, FreeVars)
93 rnLExpr = wrapLocFstM rnExpr
95 rnExpr :: HsExpr RdrName -> RnM (HsExpr Name, FreeVars)
98 = do name <- lookupOccRn v
99 ignore_asserts <- doptM Opt_IgnoreAsserts
100 finish_var ignore_asserts name
102 finish_var ignore_asserts name
103 | ignore_asserts || not (name `hasKey` assertIdKey)
104 = return (HsVar name, unitFV name)
106 = do { (e, fvs) <- mkAssertErrorExpr
107 ; return (e, fvs `addOneFV` name) }
110 = newIPNameRn v `thenM` \ name ->
111 returnM (HsIPVar name, emptyFVs)
113 rnExpr (HsLit lit@(HsString s))
115 opt_OverloadedStrings <- doptM Opt_OverloadedStrings
116 ; if opt_OverloadedStrings then
117 rnExpr (HsOverLit (mkHsIsString s))
118 else -- Same as below
120 returnM (HsLit lit, emptyFVs)
125 returnM (HsLit lit, emptyFVs)
127 rnExpr (HsOverLit lit)
128 = rnOverLit lit `thenM` \ (lit', fvs) ->
129 returnM (HsOverLit lit', fvs)
131 rnExpr (HsApp fun arg)
132 = rnLExpr fun `thenM` \ (fun',fvFun) ->
133 rnLExpr arg `thenM` \ (arg',fvArg) ->
134 returnM (HsApp fun' arg', fvFun `plusFV` fvArg)
136 rnExpr (OpApp e1 op _ e2)
137 = rnLExpr e1 `thenM` \ (e1', fv_e1) ->
138 rnLExpr e2 `thenM` \ (e2', fv_e2) ->
139 rnLExpr op `thenM` \ (op'@(L _ (HsVar op_name)), fv_op) ->
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 lookupFixityRn op_name `thenM` \ fixity ->
147 mkOpAppRn e1' op' fixity e2' `thenM` \ final_e ->
150 fv_e1 `plusFV` fv_op `plusFV` fv_e2)
153 = rnLExpr e `thenM` \ (e', fv_e) ->
154 lookupSyntaxName negateName `thenM` \ (neg_name, fv_neg) ->
155 mkNegAppRn e' neg_name `thenM` \ final_e ->
156 returnM (final_e, fv_e `plusFV` fv_neg)
159 = rnLExpr e `thenM` \ (e', fvs_e) ->
160 returnM (HsPar e', fvs_e)
162 -- Template Haskell extensions
163 -- Don't ifdef-GHCI them because we want to fail gracefully
164 -- (not with an rnExpr crash) in a stage-1 compiler.
165 rnExpr e@(HsBracket br_body)
166 = checkTH e "bracket" `thenM_`
167 rnBracket br_body `thenM` \ (body', fvs_e) ->
168 returnM (HsBracket body', fvs_e)
170 rnExpr e@(HsSpliceE splice)
171 = rnSplice splice `thenM` \ (splice', fvs) ->
172 returnM (HsSpliceE splice', fvs)
174 rnExpr section@(SectionL expr op)
175 = rnLExpr expr `thenM` \ (expr', fvs_expr) ->
176 rnLExpr op `thenM` \ (op', fvs_op) ->
177 checkSectionPrec InfixL section op' expr' `thenM_`
178 returnM (SectionL expr' op', fvs_op `plusFV` fvs_expr)
180 rnExpr section@(SectionR op expr)
181 = rnLExpr op `thenM` \ (op', fvs_op) ->
182 rnLExpr expr `thenM` \ (expr', fvs_expr) ->
183 checkSectionPrec InfixR section op' expr' `thenM_`
184 returnM (SectionR op' expr', fvs_op `plusFV` fvs_expr)
186 rnExpr (HsCoreAnn ann expr)
187 = rnLExpr expr `thenM` \ (expr', fvs_expr) ->
188 returnM (HsCoreAnn ann expr', fvs_expr)
190 rnExpr (HsSCC lbl expr)
191 = rnLExpr expr `thenM` \ (expr', fvs_expr) ->
192 returnM (HsSCC lbl expr', fvs_expr)
193 rnExpr (HsTickPragma info expr)
194 = rnLExpr expr `thenM` \ (expr', fvs_expr) ->
195 returnM (HsTickPragma info expr', fvs_expr)
197 rnExpr (HsLam matches)
198 = rnMatchGroup LambdaExpr matches `thenM` \ (matches', fvMatch) ->
199 returnM (HsLam matches', fvMatch)
201 rnExpr (HsCase expr matches)
202 = rnLExpr expr `thenM` \ (new_expr, e_fvs) ->
203 rnMatchGroup CaseAlt matches `thenM` \ (new_matches, ms_fvs) ->
204 returnM (HsCase new_expr new_matches, e_fvs `plusFV` ms_fvs)
206 rnExpr (HsLet binds expr)
207 = rnLocalBindsAndThen binds $ \ binds' ->
208 rnLExpr expr `thenM` \ (expr',fvExpr) ->
209 returnM (HsLet binds' expr', fvExpr)
211 rnExpr e@(HsDo do_or_lc stmts body _)
212 = do { ((stmts', body'), fvs) <- rnStmts do_or_lc stmts $
214 ; return (HsDo do_or_lc stmts' body' placeHolderType, fvs) }
216 rnExpr (ExplicitList _ exps)
217 = rnExprs exps `thenM` \ (exps', fvs) ->
218 returnM (ExplicitList placeHolderType exps', fvs)
220 rnExpr (ExplicitPArr _ exps)
221 = rnExprs exps `thenM` \ (exps', fvs) ->
222 returnM (ExplicitPArr placeHolderType exps', fvs)
224 rnExpr e@(ExplicitTuple exps boxity)
225 = checkTupSize (length exps) `thenM_`
226 rnExprs exps `thenM` \ (exps', fvs) ->
227 returnM (ExplicitTuple exps' boxity, fvs)
229 rnExpr (RecordCon con_id _ rbinds)
230 = do { conname <- lookupLocatedOccRn con_id
231 ; (rbinds', fvRbinds) <- rnHsRecFields "construction" (Just conname)
233 ; return (RecordCon conname noPostTcExpr rbinds',
234 fvRbinds `addOneFV` unLoc conname) }
236 rnExpr (RecordUpd expr rbinds _ _ _)
237 = do { (expr', fvExpr) <- rnLExpr expr
238 ; (rbinds', fvRbinds) <- rnHsRecFields "update" Nothing rnLExpr HsVar rbinds
239 ; return (RecordUpd expr' rbinds' [] [] [],
240 fvExpr `plusFV` fvRbinds) }
242 rnExpr (ExprWithTySig expr pty)
243 = do { (pty', fvTy) <- rnHsTypeFVs doc pty
244 ; (expr', fvExpr) <- bindSigTyVarsFV (hsExplicitTvs pty') $
246 ; return (ExprWithTySig expr' pty', fvExpr `plusFV` fvTy) }
248 doc = text "In an expression type signature"
250 rnExpr (HsIf p b1 b2)
251 = rnLExpr p `thenM` \ (p', fvP) ->
252 rnLExpr b1 `thenM` \ (b1', fvB1) ->
253 rnLExpr b2 `thenM` \ (b2', fvB2) ->
254 returnM (HsIf p' b1' b2', plusFVs [fvP, fvB1, fvB2])
257 = rnHsTypeFVs doc a `thenM` \ (t, fvT) ->
258 returnM (HsType t, fvT)
260 doc = text "In a type argument"
262 rnExpr (ArithSeq _ seq)
263 = rnArithSeq seq `thenM` \ (new_seq, fvs) ->
264 returnM (ArithSeq noPostTcExpr new_seq, fvs)
266 rnExpr (PArrSeq _ seq)
267 = rnArithSeq seq `thenM` \ (new_seq, fvs) ->
268 returnM (PArrSeq noPostTcExpr new_seq, fvs)
271 These three are pattern syntax appearing in expressions.
272 Since all the symbols are reservedops we can simply reject them.
273 We return a (bogus) EWildPat in each case.
276 rnExpr e@EWildPat = patSynErr e
277 rnExpr e@(EAsPat {}) = patSynErr e
278 rnExpr e@(ELazyPat {}) = patSynErr e
281 %************************************************************************
285 %************************************************************************
288 rnExpr (HsProc pat body)
290 rnPatsAndThen ProcExpr [pat] $ \ [pat'] ->
291 rnCmdTop body `thenM` \ (body',fvBody) ->
292 returnM (HsProc pat' body', fvBody)
294 rnExpr (HsArrApp arrow arg _ ho rtl)
295 = select_arrow_scope (rnLExpr arrow) `thenM` \ (arrow',fvArrow) ->
296 rnLExpr arg `thenM` \ (arg',fvArg) ->
297 returnM (HsArrApp arrow' arg' placeHolderType ho rtl,
298 fvArrow `plusFV` fvArg)
300 select_arrow_scope tc = case ho of
301 HsHigherOrderApp -> tc
302 HsFirstOrderApp -> escapeArrowScope tc
305 rnExpr (HsArrForm op (Just _) [arg1, arg2])
306 = escapeArrowScope (rnLExpr op)
307 `thenM` \ (op'@(L _ (HsVar op_name)),fv_op) ->
308 rnCmdTop arg1 `thenM` \ (arg1',fv_arg1) ->
309 rnCmdTop arg2 `thenM` \ (arg2',fv_arg2) ->
313 lookupFixityRn op_name `thenM` \ fixity ->
314 mkOpFormRn arg1' op' fixity arg2' `thenM` \ final_e ->
317 fv_arg1 `plusFV` fv_op `plusFV` fv_arg2)
319 rnExpr (HsArrForm op fixity cmds)
320 = escapeArrowScope (rnLExpr op) `thenM` \ (op',fvOp) ->
321 rnCmdArgs cmds `thenM` \ (cmds',fvCmds) ->
322 returnM (HsArrForm op' fixity cmds', fvOp `plusFV` fvCmds)
324 rnExpr other = pprPanic "rnExpr: unexpected expression" (ppr other)
329 %************************************************************************
333 %************************************************************************
336 rnCmdArgs [] = returnM ([], emptyFVs)
338 = rnCmdTop arg `thenM` \ (arg',fvArg) ->
339 rnCmdArgs args `thenM` \ (args',fvArgs) ->
340 returnM (arg':args', fvArg `plusFV` fvArgs)
343 rnCmdTop = wrapLocFstM rnCmdTop'
345 rnCmdTop' (HsCmdTop cmd _ _ _)
346 = rnLExpr (convertOpFormsLCmd cmd) `thenM` \ (cmd', fvCmd) ->
348 cmd_names = [arrAName, composeAName, firstAName] ++
349 nameSetToList (methodNamesCmd (unLoc cmd'))
351 -- Generate the rebindable syntax for the monad
352 lookupSyntaxTable cmd_names `thenM` \ (cmd_names', cmd_fvs) ->
354 returnM (HsCmdTop cmd' [] placeHolderType cmd_names',
355 fvCmd `plusFV` cmd_fvs)
357 ---------------------------------------------------
358 -- convert OpApp's in a command context to HsArrForm's
360 convertOpFormsLCmd :: LHsCmd id -> LHsCmd id
361 convertOpFormsLCmd = fmap convertOpFormsCmd
363 convertOpFormsCmd :: HsCmd id -> HsCmd id
365 convertOpFormsCmd (HsApp c e) = HsApp (convertOpFormsLCmd c) e
366 convertOpFormsCmd (HsLam match) = HsLam (convertOpFormsMatch match)
367 convertOpFormsCmd (OpApp c1 op fixity c2)
369 arg1 = L (getLoc c1) $ HsCmdTop (convertOpFormsLCmd c1) [] placeHolderType []
370 arg2 = L (getLoc c2) $ HsCmdTop (convertOpFormsLCmd c2) [] placeHolderType []
372 HsArrForm op (Just fixity) [arg1, arg2]
374 convertOpFormsCmd (HsPar c) = HsPar (convertOpFormsLCmd c)
377 convertOpFormsCmd (HsCase exp matches)
378 = HsCase exp (convertOpFormsMatch matches)
380 convertOpFormsCmd (HsIf exp c1 c2)
381 = HsIf exp (convertOpFormsLCmd c1) (convertOpFormsLCmd c2)
383 convertOpFormsCmd (HsLet binds cmd)
384 = HsLet binds (convertOpFormsLCmd cmd)
386 convertOpFormsCmd (HsDo ctxt stmts body ty)
387 = HsDo ctxt (map (fmap convertOpFormsStmt) stmts)
388 (convertOpFormsLCmd body) ty
390 -- Anything else is unchanged. This includes HsArrForm (already done),
391 -- things with no sub-commands, and illegal commands (which will be
392 -- caught by the type checker)
393 convertOpFormsCmd c = c
395 convertOpFormsStmt (BindStmt pat cmd _ _)
396 = BindStmt pat (convertOpFormsLCmd cmd) noSyntaxExpr noSyntaxExpr
397 convertOpFormsStmt (ExprStmt cmd _ _)
398 = ExprStmt (convertOpFormsLCmd cmd) noSyntaxExpr placeHolderType
399 convertOpFormsStmt (RecStmt stmts lvs rvs es binds)
400 = RecStmt (map (fmap convertOpFormsStmt) stmts) lvs rvs es binds
401 convertOpFormsStmt stmt = stmt
403 convertOpFormsMatch (MatchGroup ms ty)
404 = MatchGroup (map (fmap convert) ms) ty
405 where convert (Match pat mty grhss)
406 = Match pat mty (convertOpFormsGRHSs grhss)
408 convertOpFormsGRHSs (GRHSs grhss binds)
409 = GRHSs (map convertOpFormsGRHS grhss) binds
411 convertOpFormsGRHS = fmap convert
413 convert (GRHS stmts cmd) = GRHS stmts (convertOpFormsLCmd cmd)
415 ---------------------------------------------------
416 type CmdNeeds = FreeVars -- Only inhabitants are
417 -- appAName, choiceAName, loopAName
419 -- find what methods the Cmd needs (loop, choice, apply)
420 methodNamesLCmd :: LHsCmd Name -> CmdNeeds
421 methodNamesLCmd = methodNamesCmd . unLoc
423 methodNamesCmd :: HsCmd Name -> CmdNeeds
425 methodNamesCmd cmd@(HsArrApp _arrow _arg _ HsFirstOrderApp _rtl)
427 methodNamesCmd cmd@(HsArrApp _arrow _arg _ HsHigherOrderApp _rtl)
429 methodNamesCmd cmd@(HsArrForm {}) = emptyFVs
431 methodNamesCmd (HsPar c) = methodNamesLCmd c
433 methodNamesCmd (HsIf p c1 c2)
434 = methodNamesLCmd c1 `plusFV` methodNamesLCmd c2 `addOneFV` choiceAName
436 methodNamesCmd (HsLet b c) = methodNamesLCmd c
438 methodNamesCmd (HsDo sc stmts body ty)
439 = methodNamesStmts stmts `plusFV` methodNamesLCmd body
441 methodNamesCmd (HsApp c e) = methodNamesLCmd c
443 methodNamesCmd (HsLam match) = methodNamesMatch match
445 methodNamesCmd (HsCase scrut matches)
446 = methodNamesMatch matches `addOneFV` choiceAName
448 methodNamesCmd other = emptyFVs
449 -- Other forms can't occur in commands, but it's not convenient
450 -- to error here so we just do what's convenient.
451 -- The type checker will complain later
453 ---------------------------------------------------
454 methodNamesMatch (MatchGroup ms _)
455 = plusFVs (map do_one ms)
457 do_one (L _ (Match pats sig_ty grhss)) = methodNamesGRHSs grhss
459 -------------------------------------------------
461 methodNamesGRHSs (GRHSs grhss binds) = plusFVs (map methodNamesGRHS grhss)
463 -------------------------------------------------
464 methodNamesGRHS (L _ (GRHS stmts rhs)) = methodNamesLCmd rhs
466 ---------------------------------------------------
467 methodNamesStmts stmts = plusFVs (map methodNamesLStmt stmts)
469 ---------------------------------------------------
470 methodNamesLStmt = methodNamesStmt . unLoc
472 methodNamesStmt (ExprStmt cmd _ _) = methodNamesLCmd cmd
473 methodNamesStmt (BindStmt pat cmd _ _) = methodNamesLCmd cmd
474 methodNamesStmt (RecStmt stmts _ _ _ _)
475 = methodNamesStmts stmts `addOneFV` loopAName
476 methodNamesStmt (LetStmt b) = emptyFVs
477 methodNamesStmt (ParStmt ss) = emptyFVs
478 -- ParStmt can't occur in commands, but it's not convenient to error
479 -- here so we just do what's convenient
483 %************************************************************************
487 %************************************************************************
490 rnArithSeq (From expr)
491 = rnLExpr expr `thenM` \ (expr', fvExpr) ->
492 returnM (From expr', fvExpr)
494 rnArithSeq (FromThen expr1 expr2)
495 = rnLExpr expr1 `thenM` \ (expr1', fvExpr1) ->
496 rnLExpr expr2 `thenM` \ (expr2', fvExpr2) ->
497 returnM (FromThen expr1' expr2', fvExpr1 `plusFV` fvExpr2)
499 rnArithSeq (FromTo expr1 expr2)
500 = rnLExpr expr1 `thenM` \ (expr1', fvExpr1) ->
501 rnLExpr expr2 `thenM` \ (expr2', fvExpr2) ->
502 returnM (FromTo expr1' expr2', fvExpr1 `plusFV` fvExpr2)
504 rnArithSeq (FromThenTo expr1 expr2 expr3)
505 = rnLExpr expr1 `thenM` \ (expr1', fvExpr1) ->
506 rnLExpr expr2 `thenM` \ (expr2', fvExpr2) ->
507 rnLExpr expr3 `thenM` \ (expr3', fvExpr3) ->
508 returnM (FromThenTo expr1' expr2' expr3',
509 plusFVs [fvExpr1, fvExpr2, fvExpr3])
512 %************************************************************************
514 Template Haskell brackets
516 %************************************************************************
519 rnBracket (VarBr n) = do { name <- lookupOccRn n
520 ; this_mod <- getModule
521 ; checkM (nameIsLocalOrFrom this_mod name) $ -- Reason: deprecation checking asumes the
522 do { loadInterfaceForName msg name -- home interface is loaded, and this is the
523 ; return () } -- only way that is going to happen
524 ; returnM (VarBr name, unitFV name) }
526 msg = ptext SLIT("Need interface for Template Haskell quoted Name")
528 rnBracket (ExpBr e) = do { (e', fvs) <- rnLExpr e
529 ; return (ExpBr e', fvs) }
530 rnBracket (PatBr p) = do { (p', fvs) <- rnLPat p
531 ; return (PatBr p', fvs) }
532 rnBracket (TypBr t) = do { (t', fvs) <- rnHsTypeFVs doc t
533 ; return (TypBr t', fvs) }
535 doc = ptext SLIT("In a Template-Haskell quoted type")
536 rnBracket (DecBr group)
537 = do { gbl_env <- getGblEnv
539 ; let gbl_env1 = gbl_env { tcg_mod = thFAKE }
540 -- Note the thFAKE. The top-level names from the bracketed
541 -- declarations will go into the name cache, and we don't want them to
542 -- confuse the Names for the current module.
543 -- By using a pretend module, thFAKE, we keep them safely out of the way.
545 ; avails <- getLocalDeclBinders gbl_env1 group
546 ; let names = concatMap availNames avails
548 ; let new_occs = map nameOccName names
549 trimmed_rdr_env = hideSomeUnquals (tcg_rdr_env gbl_env) new_occs
551 ; rdr_env' <- extendRdrEnvRn trimmed_rdr_env avails
552 -- In this situation we want to *shadow* top-level bindings.
554 -- bar = [d| foo = 1|]
555 -- If we don't shadow, we'll get an ambiguity complaint when we do
556 -- a lookupTopBndrRn (which uses lookupGreLocalRn) on the binder of the 'foo'
558 -- Furthermore, arguably if the splice does define foo, that should hide
559 -- any foo's further out
561 -- The shadowing is acheived by the call to hideSomeUnquals, which removes
562 -- the unqualified bindings of things defined by the bracket
564 ; setGblEnv (gbl_env { tcg_rdr_env = rdr_env',
565 tcg_dus = emptyDUs }) $ do
566 -- The emptyDUs is so that we just collect uses for this group alone
568 { (tcg_env, group') <- rnSrcDecls group
569 -- Discard the tcg_env; it contains only extra info about fixity
570 ; return (DecBr group', allUses (tcg_dus tcg_env)) } }
573 %************************************************************************
575 \subsubsection{@Stmt@s: in @do@ expressions}
577 %************************************************************************
580 rnStmts :: HsStmtContext Name -> [LStmt RdrName]
581 -> RnM (thing, FreeVars)
582 -> RnM (([LStmt Name], thing), FreeVars)
584 rnStmts (MDoExpr _) = rnMDoStmts
585 rnStmts ctxt = rnNormalStmts ctxt
587 rnNormalStmts :: HsStmtContext Name -> [LStmt RdrName]
588 -> RnM (thing, FreeVars)
589 -> RnM (([LStmt Name], thing), FreeVars)
590 -- Used for cases *other* than recursive mdo
591 -- Implements nested scopes
593 rnNormalStmts ctxt [] thing_inside
594 = do { (thing, fvs) <- thing_inside
595 ; return (([],thing), fvs) }
597 rnNormalStmts ctxt (L loc stmt : stmts) thing_inside
598 = do { ((stmt', (stmts', thing)), fvs)
599 <- rnStmt ctxt stmt $
600 rnNormalStmts ctxt stmts thing_inside
601 ; return (((L loc stmt' : stmts'), thing), fvs) }
603 rnStmt :: HsStmtContext Name -> Stmt RdrName
604 -> RnM (thing, FreeVars)
605 -> RnM ((Stmt Name, thing), FreeVars)
607 rnStmt ctxt (ExprStmt expr _ _) thing_inside
608 = do { (expr', fv_expr) <- rnLExpr expr
609 ; (then_op, fvs1) <- lookupSyntaxName thenMName
610 ; (thing, fvs2) <- thing_inside
611 ; return ((ExprStmt expr' then_op placeHolderType, thing),
612 fv_expr `plusFV` fvs1 `plusFV` fvs2) }
614 rnStmt ctxt (BindStmt pat expr _ _) thing_inside
615 = do { (expr', fv_expr) <- rnLExpr expr
616 -- The binders do not scope over the expression
617 ; (bind_op, fvs1) <- lookupSyntaxName bindMName
618 ; (fail_op, fvs2) <- lookupSyntaxName failMName
619 ; rnPatsAndThen (StmtCtxt ctxt) [pat] $ \ [pat'] -> do
620 { (thing, fvs3) <- thing_inside
621 ; return ((BindStmt pat' expr' bind_op fail_op, thing),
622 fv_expr `plusFV` fvs1 `plusFV` fvs2 `plusFV` fvs3) }}
623 -- fv_expr shouldn't really be filtered by the rnPatsAndThen
624 -- but it does not matter because the names are unique
626 rnStmt ctxt (LetStmt binds) thing_inside
627 = do { checkErr (ok ctxt binds)
628 (badIpBinds (ptext SLIT("a parallel list comprehension:")) binds)
629 ; rnLocalBindsAndThen binds $ \ binds' -> do
630 { (thing, fvs) <- thing_inside
631 ; return ((LetStmt binds', thing), fvs) }}
633 -- We do not allow implicit-parameter bindings in a parallel
634 -- list comprehension. I'm not sure what it might mean.
635 ok (ParStmtCtxt _) (HsIPBinds _) = False
638 rnStmt ctxt (RecStmt rec_stmts _ _ _ _) thing_inside
639 = bindLocatedLocalsRn doc (collectLStmtsBinders rec_stmts) $ \ bndrs ->
640 rn_rec_stmts bndrs rec_stmts `thenM` \ segs ->
641 thing_inside `thenM` \ (thing, fvs) ->
643 segs_w_fwd_refs = addFwdRefs segs
644 (ds, us, fs, rec_stmts') = unzip4 segs_w_fwd_refs
645 later_vars = nameSetToList (plusFVs ds `intersectNameSet` fvs)
646 fwd_vars = nameSetToList (plusFVs fs)
648 rec_stmt = RecStmt rec_stmts' later_vars fwd_vars [] emptyLHsBinds
650 returnM ((rec_stmt, thing), uses `plusFV` fvs)
652 doc = text "In a recursive do statement"
654 rnStmt ctxt (ParStmt segs) thing_inside
655 = do { parallel_list_comp <- doptM Opt_ParallelListComp
656 ; checkM parallel_list_comp parStmtErr
657 ; orig_lcl_env <- getLocalRdrEnv
658 ; ((segs',thing), fvs) <- go orig_lcl_env [] segs
659 ; return ((ParStmt segs', thing), fvs) }
661 -- type ParSeg id = [([LStmt id], [id])]
662 -- go :: NameSet -> [ParSeg RdrName]
663 -- -> RnM (([ParSeg Name], thing), FreeVars)
665 go orig_lcl_env bndrs []
666 = do { let { (bndrs', dups) = removeDups cmpByOcc bndrs
667 ; inner_env = extendLocalRdrEnv orig_lcl_env bndrs' }
669 ; (thing, fvs) <- setLocalRdrEnv inner_env thing_inside
670 ; return (([], thing), fvs) }
672 go orig_lcl_env bndrs_so_far ((stmts, _) : segs)
673 = do { ((stmts', (bndrs, segs', thing)), fvs)
674 <- rnNormalStmts par_ctxt stmts $ do
675 { -- Find the Names that are bound by stmts
676 lcl_env <- getLocalRdrEnv
677 ; let { rdr_bndrs = collectLStmtsBinders stmts
678 ; bndrs = map ( expectJust "rnStmt"
679 . lookupLocalRdrEnv lcl_env
681 ; new_bndrs = nub bndrs ++ bndrs_so_far
682 -- The nub is because there might be shadowing
684 -- So we'll look up (Unqual x) twice, getting
685 -- the second binding both times, which is the
688 -- Typecheck the thing inside, passing on all
689 -- the Names bound, but separately; revert the envt
690 ; ((segs', thing), fvs) <- setLocalRdrEnv orig_lcl_env $
691 go orig_lcl_env new_bndrs segs
693 -- Figure out which of the bound names are used
694 ; let used_bndrs = filter (`elemNameSet` fvs) bndrs
695 ; return ((used_bndrs, segs', thing), fvs) }
697 ; let seg' = (stmts', bndrs)
698 ; return (((seg':segs'), thing),
699 delListFromNameSet fvs bndrs) }
701 par_ctxt = ParStmtCtxt ctxt
703 cmpByOcc n1 n2 = nameOccName n1 `compare` nameOccName n2
704 dupErr vs = addErr (ptext SLIT("Duplicate binding in parallel list comprehension for:")
705 <+> quotes (ppr (head vs)))
709 %************************************************************************
711 \subsubsection{mdo expressions}
713 %************************************************************************
716 type FwdRefs = NameSet
717 type Segment stmts = (Defs,
718 Uses, -- May include defs
719 FwdRefs, -- A subset of uses that are
720 -- (a) used before they are bound in this segment, or
721 -- (b) used here, and bound in subsequent segments
722 stmts) -- Either Stmt or [Stmt]
725 ----------------------------------------------------
726 rnMDoStmts :: [LStmt RdrName]
727 -> RnM (thing, FreeVars)
728 -> RnM (([LStmt Name], thing), FreeVars)
729 rnMDoStmts stmts thing_inside
730 = -- Step1: bring all the binders of the mdo into scope
731 -- Remember that this also removes the binders from the
732 -- finally-returned free-vars
733 bindLocatedLocalsRn doc (collectLStmtsBinders stmts) $ \ bndrs ->
735 -- Step 2: Rename each individual stmt, making a
736 -- singleton segment. At this stage the FwdRefs field
737 -- isn't finished: it's empty for all except a BindStmt
738 -- for which it's the fwd refs within the bind itself
739 -- (This set may not be empty, because we're in a recursive
741 segs <- rn_rec_stmts bndrs stmts
743 ; (thing, fvs_later) <- thing_inside
746 -- Step 3: Fill in the fwd refs.
747 -- The segments are all singletons, but their fwd-ref
748 -- field mentions all the things used by the segment
749 -- that are bound after their use
750 segs_w_fwd_refs = addFwdRefs segs
752 -- Step 4: Group together the segments to make bigger segments
753 -- Invariant: in the result, no segment uses a variable
754 -- bound in a later segment
755 grouped_segs = glomSegments segs_w_fwd_refs
757 -- Step 5: Turn the segments into Stmts
758 -- Use RecStmt when and only when there are fwd refs
759 -- Also gather up the uses from the end towards the
760 -- start, so we can tell the RecStmt which things are
761 -- used 'after' the RecStmt
762 (stmts', fvs) = segsToStmts grouped_segs fvs_later
764 ; return ((stmts', thing), fvs) }
766 doc = text "In a recursive mdo-expression"
768 ---------------------------------------------
769 rn_rec_stmts :: [Name] -> [LStmt RdrName] -> RnM [Segment (LStmt Name)]
770 rn_rec_stmts bndrs stmts = mappM (rn_rec_stmt bndrs) stmts `thenM` \ segs_s ->
771 returnM (concat segs_s)
773 ----------------------------------------------------
774 rn_rec_stmt :: [Name] -> LStmt RdrName -> RnM [Segment (LStmt Name)]
775 -- Rename a Stmt that is inside a RecStmt (or mdo)
776 -- Assumes all binders are already in scope
777 -- Turns each stmt into a singleton Stmt
779 rn_rec_stmt all_bndrs (L loc (ExprStmt expr _ _))
780 = rnLExpr expr `thenM` \ (expr', fvs) ->
781 lookupSyntaxName thenMName `thenM` \ (then_op, fvs1) ->
782 returnM [(emptyNameSet, fvs `plusFV` fvs1, emptyNameSet,
783 L loc (ExprStmt expr' then_op placeHolderType))]
785 rn_rec_stmt all_bndrs (L loc (BindStmt pat expr _ _))
786 = rnLExpr expr `thenM` \ (expr', fv_expr) ->
787 rnLPat pat `thenM` \ (pat', fv_pat) ->
788 lookupSyntaxName bindMName `thenM` \ (bind_op, fvs1) ->
789 lookupSyntaxName failMName `thenM` \ (fail_op, fvs2) ->
791 bndrs = mkNameSet (collectPatBinders pat')
792 fvs = fv_expr `plusFV` fv_pat `plusFV` fvs1 `plusFV` fvs2
794 returnM [(bndrs, fvs, bndrs `intersectNameSet` fvs,
795 L loc (BindStmt pat' expr' bind_op fail_op))]
797 rn_rec_stmt all_bndrs (L loc (LetStmt binds@(HsIPBinds _)))
798 = do { addErr (badIpBinds (ptext SLIT("an mdo expression")) binds)
801 rn_rec_stmt all_bndrs (L loc (LetStmt (HsValBinds binds)))
802 = rnValBinds (trimWith all_bndrs) binds `thenM` \ (binds', du_binds) ->
803 returnM [(duDefs du_binds, duUses du_binds,
804 emptyNameSet, L loc (LetStmt (HsValBinds binds')))]
806 rn_rec_stmt all_bndrs (L loc (RecStmt stmts _ _ _ _)) -- Flatten Rec inside Rec
807 = rn_rec_stmts all_bndrs stmts
809 rn_rec_stmt all_bndrs stmt@(L _ (ParStmt _)) -- Syntactically illegal in mdo
810 = pprPanic "rn_rec_stmt" (ppr stmt)
812 ---------------------------------------------
813 addFwdRefs :: [Segment a] -> [Segment a]
814 -- So far the segments only have forward refs *within* the Stmt
815 -- (which happens for bind: x <- ...x...)
816 -- This function adds the cross-seg fwd ref info
819 = fst (foldr mk_seg ([], emptyNameSet) pairs)
821 mk_seg (defs, uses, fwds, stmts) (segs, later_defs)
822 = (new_seg : segs, all_defs)
824 new_seg = (defs, uses, new_fwds, stmts)
825 all_defs = later_defs `unionNameSets` defs
826 new_fwds = fwds `unionNameSets` (uses `intersectNameSet` later_defs)
827 -- Add the downstream fwd refs here
829 ----------------------------------------------------
830 -- Glomming the singleton segments of an mdo into
831 -- minimal recursive groups.
833 -- At first I thought this was just strongly connected components, but
834 -- there's an important constraint: the order of the stmts must not change.
837 -- mdo { x <- ...y...
844 -- Here, the first stmt mention 'y', which is bound in the third.
845 -- But that means that the innocent second stmt (p <- z) gets caught
846 -- up in the recursion. And that in turn means that the binding for
847 -- 'z' has to be included... and so on.
849 -- Start at the tail { r <- x }
850 -- Now add the next one { z <- y ; r <- x }
851 -- Now add one more { q <- x ; z <- y ; r <- x }
852 -- Now one more... but this time we have to group a bunch into rec
853 -- { rec { y <- ...x... ; q <- x ; z <- y } ; r <- x }
854 -- Now one more, which we can add on without a rec
856 -- rec { y <- ...x... ; q <- x ; z <- y } ;
858 -- Finally we add the last one; since it mentions y we have to
859 -- glom it togeher with the first two groups
860 -- { rec { x <- ...y...; p <- z ; y <- ...x... ;
861 -- q <- x ; z <- y } ;
864 glomSegments :: [Segment (LStmt Name)] -> [Segment [LStmt Name]]
867 glomSegments ((defs,uses,fwds,stmt) : segs)
868 -- Actually stmts will always be a singleton
869 = (seg_defs, seg_uses, seg_fwds, seg_stmts) : others
871 segs' = glomSegments segs
872 (extras, others) = grab uses segs'
873 (ds, us, fs, ss) = unzip4 extras
875 seg_defs = plusFVs ds `plusFV` defs
876 seg_uses = plusFVs us `plusFV` uses
877 seg_fwds = plusFVs fs `plusFV` fwds
878 seg_stmts = stmt : concat ss
880 grab :: NameSet -- The client
882 -> ([Segment a], -- Needed by the 'client'
883 [Segment a]) -- Not needed by the client
884 -- The result is simply a split of the input
886 = (reverse yeses, reverse noes)
888 (noes, yeses) = span not_needed (reverse dus)
889 not_needed (defs,_,_,_) = not (intersectsNameSet defs uses)
892 ----------------------------------------------------
893 segsToStmts :: [Segment [LStmt Name]]
894 -> FreeVars -- Free vars used 'later'
895 -> ([LStmt Name], FreeVars)
897 segsToStmts [] fvs_later = ([], fvs_later)
898 segsToStmts ((defs, uses, fwds, ss) : segs) fvs_later
899 = ASSERT( not (null ss) )
900 (new_stmt : later_stmts, later_uses `plusFV` uses)
902 (later_stmts, later_uses) = segsToStmts segs fvs_later
903 new_stmt | non_rec = head ss
904 | otherwise = L (getLoc (head ss)) $
905 RecStmt ss (nameSetToList used_later) (nameSetToList fwds)
908 non_rec = isSingleton ss && isEmptyNameSet fwds
909 used_later = defs `intersectNameSet` later_uses
910 -- The ones needed after the RecStmt
913 %************************************************************************
915 \subsubsection{Assertion utils}
917 %************************************************************************
920 srcSpanPrimLit :: SrcSpan -> HsExpr Name
921 srcSpanPrimLit span = HsLit (HsStringPrim (mkFastString (showSDoc (ppr span))))
923 mkAssertErrorExpr :: RnM (HsExpr Name, FreeVars)
924 -- Return an expression for (assertError "Foo.hs:27")
926 = getSrcSpanM `thenM` \ sloc ->
928 expr = HsApp (L sloc (HsVar assertErrorName))
929 (L sloc (srcSpanPrimLit sloc))
931 returnM (expr, emptyFVs)
934 %************************************************************************
936 \subsubsection{Errors}
938 %************************************************************************
941 patSynErr e = do { addErr (sep [ptext SLIT("Pattern syntax in expression context:"),
943 ; return (EWildPat, emptyFVs) }
945 parStmtErr = addErr (ptext SLIT("Illegal parallel list comprehension: use -XParallelListComp"))
947 badIpBinds what binds
948 = hang (ptext SLIT("Implicit-parameter bindings illegal in") <+> what)