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"
19 import RnSource ( rnSrcDecls, rnSplice, checkTH )
20 import RnBinds ( rnLocalBindsAndThen, rnValBinds,
21 rnMatchGroup, trimWith )
25 import HscTypes ( availNames )
26 import RnNames ( getLocalDeclBinders, extendRdrEnvRn )
27 import RnTypes ( rnHsTypeFVs, rnLPat, rnOverLit, rnPatsAndThen, rnLit,
28 mkOpFormRn, mkOpAppRn, mkNegAppRn, checkSectionPrec,
29 rnHsRecFields, checkTupSize )
30 import DynFlags ( DynFlag(..) )
31 import BasicTypes ( FixityDirection(..) )
32 import SrcLoc ( SrcSpan )
33 import PrelNames ( thFAKE, hasKey, assertIdKey, assertErrorName,
34 loopAName, choiceAName, appAName, arrAName, composeAName, firstAName,
35 negateName, thenMName, bindMName, failMName )
37 import Name ( Name, nameOccName, nameIsLocalOrFrom )
39 import RdrName ( RdrName, extendLocalRdrEnv, lookupLocalRdrEnv, hideSomeUnquals )
40 import LoadIface ( loadInterfaceForName )
41 import UniqFM ( isNullUFM )
42 import UniqSet ( emptyUniqSet )
44 import Util ( isSingleton )
45 import ListSetOps ( removeDups )
46 import Maybes ( expectJust )
48 import SrcLoc ( Located(..), unLoc, getLoc, cmpLocated )
51 import List ( unzip4 )
55 %************************************************************************
57 \subsubsection{Expressions}
59 %************************************************************************
62 rnExprs :: [LHsExpr RdrName] -> RnM ([LHsExpr Name], FreeVars)
63 rnExprs ls = rnExprs' ls emptyUniqSet
65 rnExprs' [] acc = returnM ([], acc)
66 rnExprs' (expr:exprs) acc
67 = rnLExpr expr `thenM` \ (expr', fvExpr) ->
69 -- Now we do a "seq" on the free vars because typically it's small
70 -- or empty, especially in very long lists of constants
72 acc' = acc `plusFV` fvExpr
74 (grubby_seqNameSet acc' rnExprs') exprs acc' `thenM` \ (exprs', fvExprs) ->
75 returnM (expr':exprs', fvExprs)
77 -- Grubby little function to do "seq" on namesets; replace by proper seq when GHC can do seq
78 grubby_seqNameSet ns result | isNullUFM ns = result
82 Variables. We look up the variable and return the resulting name.
85 rnLExpr :: LHsExpr RdrName -> RnM (LHsExpr Name, FreeVars)
86 rnLExpr = wrapLocFstM rnExpr
88 rnExpr :: HsExpr RdrName -> RnM (HsExpr Name, FreeVars)
91 = do name <- lookupOccRn v
92 ignore_asserts <- doptM Opt_IgnoreAsserts
93 finish_var ignore_asserts name
95 finish_var ignore_asserts name
96 | ignore_asserts || not (name `hasKey` assertIdKey)
97 = return (HsVar name, unitFV name)
99 = do { (e, fvs) <- mkAssertErrorExpr
100 ; return (e, fvs `addOneFV` name) }
103 = newIPNameRn v `thenM` \ name ->
104 returnM (HsIPVar name, emptyFVs)
106 rnExpr (HsLit lit@(HsString s))
108 opt_OverloadedStrings <- doptM Opt_OverloadedStrings
109 ; if opt_OverloadedStrings then
110 rnExpr (HsOverLit (mkHsIsString s))
111 else -- Same as below
113 returnM (HsLit lit, emptyFVs)
118 returnM (HsLit lit, emptyFVs)
120 rnExpr (HsOverLit lit)
121 = rnOverLit lit `thenM` \ (lit', fvs) ->
122 returnM (HsOverLit lit', fvs)
124 rnExpr (HsApp fun arg)
125 = rnLExpr fun `thenM` \ (fun',fvFun) ->
126 rnLExpr arg `thenM` \ (arg',fvArg) ->
127 returnM (HsApp fun' arg', fvFun `plusFV` fvArg)
129 rnExpr (OpApp e1 op _ e2)
130 = rnLExpr e1 `thenM` \ (e1', fv_e1) ->
131 rnLExpr e2 `thenM` \ (e2', fv_e2) ->
132 rnLExpr op `thenM` \ (op'@(L _ (HsVar op_name)), fv_op) ->
135 -- When renaming code synthesised from "deriving" declarations
136 -- we used to avoid fixity stuff, but we can't easily tell any
137 -- more, so I've removed the test. Adding HsPars in TcGenDeriv
138 -- should prevent bad things happening.
139 lookupFixityRn op_name `thenM` \ fixity ->
140 mkOpAppRn e1' op' fixity e2' `thenM` \ final_e ->
143 fv_e1 `plusFV` fv_op `plusFV` fv_e2)
146 = rnLExpr e `thenM` \ (e', fv_e) ->
147 lookupSyntaxName negateName `thenM` \ (neg_name, fv_neg) ->
148 mkNegAppRn e' neg_name `thenM` \ final_e ->
149 returnM (final_e, fv_e `plusFV` fv_neg)
152 = rnLExpr e `thenM` \ (e', fvs_e) ->
153 returnM (HsPar e', fvs_e)
155 -- Template Haskell extensions
156 -- Don't ifdef-GHCI them because we want to fail gracefully
157 -- (not with an rnExpr crash) in a stage-1 compiler.
158 rnExpr e@(HsBracket br_body)
159 = checkTH e "bracket" `thenM_`
160 rnBracket br_body `thenM` \ (body', fvs_e) ->
161 returnM (HsBracket body', fvs_e)
163 rnExpr e@(HsSpliceE splice)
164 = rnSplice splice `thenM` \ (splice', fvs) ->
165 returnM (HsSpliceE splice', fvs)
167 rnExpr section@(SectionL expr op)
168 = rnLExpr expr `thenM` \ (expr', fvs_expr) ->
169 rnLExpr op `thenM` \ (op', fvs_op) ->
170 checkSectionPrec InfixL section op' expr' `thenM_`
171 returnM (SectionL expr' op', fvs_op `plusFV` fvs_expr)
173 rnExpr section@(SectionR op expr)
174 = rnLExpr op `thenM` \ (op', fvs_op) ->
175 rnLExpr expr `thenM` \ (expr', fvs_expr) ->
176 checkSectionPrec InfixR section op' expr' `thenM_`
177 returnM (SectionR op' expr', fvs_op `plusFV` fvs_expr)
179 rnExpr (HsCoreAnn ann expr)
180 = rnLExpr expr `thenM` \ (expr', fvs_expr) ->
181 returnM (HsCoreAnn ann expr', fvs_expr)
183 rnExpr (HsSCC lbl expr)
184 = rnLExpr expr `thenM` \ (expr', fvs_expr) ->
185 returnM (HsSCC lbl expr', fvs_expr)
186 rnExpr (HsTickPragma info expr)
187 = rnLExpr expr `thenM` \ (expr', fvs_expr) ->
188 returnM (HsTickPragma info expr', fvs_expr)
190 rnExpr (HsLam matches)
191 = rnMatchGroup LambdaExpr matches `thenM` \ (matches', fvMatch) ->
192 returnM (HsLam matches', fvMatch)
194 rnExpr (HsCase expr matches)
195 = rnLExpr expr `thenM` \ (new_expr, e_fvs) ->
196 rnMatchGroup CaseAlt matches `thenM` \ (new_matches, ms_fvs) ->
197 returnM (HsCase new_expr new_matches, e_fvs `plusFV` ms_fvs)
199 rnExpr (HsLet binds expr)
200 = rnLocalBindsAndThen binds $ \ binds' ->
201 rnLExpr expr `thenM` \ (expr',fvExpr) ->
202 returnM (HsLet binds' expr', fvExpr)
204 rnExpr e@(HsDo do_or_lc stmts body _)
205 = do { ((stmts', body'), fvs) <- rnStmts do_or_lc stmts $
207 ; return (HsDo do_or_lc stmts' body' placeHolderType, fvs) }
209 rnExpr (ExplicitList _ exps)
210 = rnExprs exps `thenM` \ (exps', fvs) ->
211 returnM (ExplicitList placeHolderType exps', fvs)
213 rnExpr (ExplicitPArr _ exps)
214 = rnExprs exps `thenM` \ (exps', fvs) ->
215 returnM (ExplicitPArr placeHolderType exps', fvs)
217 rnExpr e@(ExplicitTuple exps boxity)
218 = checkTupSize (length exps) `thenM_`
219 rnExprs exps `thenM` \ (exps', fvs) ->
220 returnM (ExplicitTuple exps' boxity, fvs)
222 rnExpr (RecordCon con_id _ rbinds)
223 = do { conname <- lookupLocatedOccRn con_id
224 ; (rbinds', fvRbinds) <- rnHsRecFields "construction" (Just conname)
226 ; return (RecordCon conname noPostTcExpr rbinds',
227 fvRbinds `addOneFV` unLoc conname) }
229 rnExpr (RecordUpd expr rbinds _ _ _)
230 = do { (expr', fvExpr) <- rnLExpr expr
231 ; (rbinds', fvRbinds) <- rnHsRecFields "update" Nothing rnLExpr HsVar rbinds
232 ; return (RecordUpd expr' rbinds' [] [] [],
233 fvExpr `plusFV` fvRbinds) }
235 rnExpr (ExprWithTySig expr pty)
236 = do { (pty', fvTy) <- rnHsTypeFVs doc pty
237 ; (expr', fvExpr) <- bindSigTyVarsFV (hsExplicitTvs pty') $
239 ; return (ExprWithTySig expr' pty', fvExpr `plusFV` fvTy) }
241 doc = text "In an expression type signature"
243 rnExpr (HsIf p b1 b2)
244 = rnLExpr p `thenM` \ (p', fvP) ->
245 rnLExpr b1 `thenM` \ (b1', fvB1) ->
246 rnLExpr b2 `thenM` \ (b2', fvB2) ->
247 returnM (HsIf p' b1' b2', plusFVs [fvP, fvB1, fvB2])
250 = rnHsTypeFVs doc a `thenM` \ (t, fvT) ->
251 returnM (HsType t, fvT)
253 doc = text "In a type argument"
255 rnExpr (ArithSeq _ seq)
256 = rnArithSeq seq `thenM` \ (new_seq, fvs) ->
257 returnM (ArithSeq noPostTcExpr new_seq, fvs)
259 rnExpr (PArrSeq _ seq)
260 = rnArithSeq seq `thenM` \ (new_seq, fvs) ->
261 returnM (PArrSeq noPostTcExpr new_seq, fvs)
264 These three are pattern syntax appearing in expressions.
265 Since all the symbols are reservedops we can simply reject them.
266 We return a (bogus) EWildPat in each case.
269 rnExpr e@EWildPat = patSynErr e
270 rnExpr e@(EAsPat {}) = patSynErr e
271 rnExpr e@(ELazyPat {}) = patSynErr e
274 %************************************************************************
278 %************************************************************************
281 rnExpr (HsProc pat body)
283 rnPatsAndThen ProcExpr [pat] $ \ [pat'] ->
284 rnCmdTop body `thenM` \ (body',fvBody) ->
285 returnM (HsProc pat' body', fvBody)
287 rnExpr (HsArrApp arrow arg _ ho rtl)
288 = select_arrow_scope (rnLExpr arrow) `thenM` \ (arrow',fvArrow) ->
289 rnLExpr arg `thenM` \ (arg',fvArg) ->
290 returnM (HsArrApp arrow' arg' placeHolderType ho rtl,
291 fvArrow `plusFV` fvArg)
293 select_arrow_scope tc = case ho of
294 HsHigherOrderApp -> tc
295 HsFirstOrderApp -> escapeArrowScope tc
298 rnExpr (HsArrForm op (Just _) [arg1, arg2])
299 = escapeArrowScope (rnLExpr op)
300 `thenM` \ (op'@(L _ (HsVar op_name)),fv_op) ->
301 rnCmdTop arg1 `thenM` \ (arg1',fv_arg1) ->
302 rnCmdTop arg2 `thenM` \ (arg2',fv_arg2) ->
306 lookupFixityRn op_name `thenM` \ fixity ->
307 mkOpFormRn arg1' op' fixity arg2' `thenM` \ final_e ->
310 fv_arg1 `plusFV` fv_op `plusFV` fv_arg2)
312 rnExpr (HsArrForm op fixity cmds)
313 = escapeArrowScope (rnLExpr op) `thenM` \ (op',fvOp) ->
314 rnCmdArgs cmds `thenM` \ (cmds',fvCmds) ->
315 returnM (HsArrForm op' fixity cmds', fvOp `plusFV` fvCmds)
317 rnExpr other = pprPanic "rnExpr: unexpected expression" (ppr other)
322 %************************************************************************
326 %************************************************************************
329 rnCmdArgs [] = returnM ([], emptyFVs)
331 = rnCmdTop arg `thenM` \ (arg',fvArg) ->
332 rnCmdArgs args `thenM` \ (args',fvArgs) ->
333 returnM (arg':args', fvArg `plusFV` fvArgs)
336 rnCmdTop = wrapLocFstM rnCmdTop'
338 rnCmdTop' (HsCmdTop cmd _ _ _)
339 = rnLExpr (convertOpFormsLCmd cmd) `thenM` \ (cmd', fvCmd) ->
341 cmd_names = [arrAName, composeAName, firstAName] ++
342 nameSetToList (methodNamesCmd (unLoc cmd'))
344 -- Generate the rebindable syntax for the monad
345 lookupSyntaxTable cmd_names `thenM` \ (cmd_names', cmd_fvs) ->
347 returnM (HsCmdTop cmd' [] placeHolderType cmd_names',
348 fvCmd `plusFV` cmd_fvs)
350 ---------------------------------------------------
351 -- convert OpApp's in a command context to HsArrForm's
353 convertOpFormsLCmd :: LHsCmd id -> LHsCmd id
354 convertOpFormsLCmd = fmap convertOpFormsCmd
356 convertOpFormsCmd :: HsCmd id -> HsCmd id
358 convertOpFormsCmd (HsApp c e) = HsApp (convertOpFormsLCmd c) e
359 convertOpFormsCmd (HsLam match) = HsLam (convertOpFormsMatch match)
360 convertOpFormsCmd (OpApp c1 op fixity c2)
362 arg1 = L (getLoc c1) $ HsCmdTop (convertOpFormsLCmd c1) [] placeHolderType []
363 arg2 = L (getLoc c2) $ HsCmdTop (convertOpFormsLCmd c2) [] placeHolderType []
365 HsArrForm op (Just fixity) [arg1, arg2]
367 convertOpFormsCmd (HsPar c) = HsPar (convertOpFormsLCmd c)
370 convertOpFormsCmd (HsCase exp matches)
371 = HsCase exp (convertOpFormsMatch matches)
373 convertOpFormsCmd (HsIf exp c1 c2)
374 = HsIf exp (convertOpFormsLCmd c1) (convertOpFormsLCmd c2)
376 convertOpFormsCmd (HsLet binds cmd)
377 = HsLet binds (convertOpFormsLCmd cmd)
379 convertOpFormsCmd (HsDo ctxt stmts body ty)
380 = HsDo ctxt (map (fmap convertOpFormsStmt) stmts)
381 (convertOpFormsLCmd body) ty
383 -- Anything else is unchanged. This includes HsArrForm (already done),
384 -- things with no sub-commands, and illegal commands (which will be
385 -- caught by the type checker)
386 convertOpFormsCmd c = c
388 convertOpFormsStmt (BindStmt pat cmd _ _)
389 = BindStmt pat (convertOpFormsLCmd cmd) noSyntaxExpr noSyntaxExpr
390 convertOpFormsStmt (ExprStmt cmd _ _)
391 = ExprStmt (convertOpFormsLCmd cmd) noSyntaxExpr placeHolderType
392 convertOpFormsStmt (RecStmt stmts lvs rvs es binds)
393 = RecStmt (map (fmap convertOpFormsStmt) stmts) lvs rvs es binds
394 convertOpFormsStmt stmt = stmt
396 convertOpFormsMatch (MatchGroup ms ty)
397 = MatchGroup (map (fmap convert) ms) ty
398 where convert (Match pat mty grhss)
399 = Match pat mty (convertOpFormsGRHSs grhss)
401 convertOpFormsGRHSs (GRHSs grhss binds)
402 = GRHSs (map convertOpFormsGRHS grhss) binds
404 convertOpFormsGRHS = fmap convert
406 convert (GRHS stmts cmd) = GRHS stmts (convertOpFormsLCmd cmd)
408 ---------------------------------------------------
409 type CmdNeeds = FreeVars -- Only inhabitants are
410 -- appAName, choiceAName, loopAName
412 -- find what methods the Cmd needs (loop, choice, apply)
413 methodNamesLCmd :: LHsCmd Name -> CmdNeeds
414 methodNamesLCmd = methodNamesCmd . unLoc
416 methodNamesCmd :: HsCmd Name -> CmdNeeds
418 methodNamesCmd cmd@(HsArrApp _arrow _arg _ HsFirstOrderApp _rtl)
420 methodNamesCmd cmd@(HsArrApp _arrow _arg _ HsHigherOrderApp _rtl)
422 methodNamesCmd cmd@(HsArrForm {}) = emptyFVs
424 methodNamesCmd (HsPar c) = methodNamesLCmd c
426 methodNamesCmd (HsIf p c1 c2)
427 = methodNamesLCmd c1 `plusFV` methodNamesLCmd c2 `addOneFV` choiceAName
429 methodNamesCmd (HsLet b c) = methodNamesLCmd c
431 methodNamesCmd (HsDo sc stmts body ty)
432 = methodNamesStmts stmts `plusFV` methodNamesLCmd body
434 methodNamesCmd (HsApp c e) = methodNamesLCmd c
436 methodNamesCmd (HsLam match) = methodNamesMatch match
438 methodNamesCmd (HsCase scrut matches)
439 = methodNamesMatch matches `addOneFV` choiceAName
441 methodNamesCmd other = emptyFVs
442 -- Other forms can't occur in commands, but it's not convenient
443 -- to error here so we just do what's convenient.
444 -- The type checker will complain later
446 ---------------------------------------------------
447 methodNamesMatch (MatchGroup ms _)
448 = plusFVs (map do_one ms)
450 do_one (L _ (Match pats sig_ty grhss)) = methodNamesGRHSs grhss
452 -------------------------------------------------
454 methodNamesGRHSs (GRHSs grhss binds) = plusFVs (map methodNamesGRHS grhss)
456 -------------------------------------------------
457 methodNamesGRHS (L _ (GRHS stmts rhs)) = methodNamesLCmd rhs
459 ---------------------------------------------------
460 methodNamesStmts stmts = plusFVs (map methodNamesLStmt stmts)
462 ---------------------------------------------------
463 methodNamesLStmt = methodNamesStmt . unLoc
465 methodNamesStmt (ExprStmt cmd _ _) = methodNamesLCmd cmd
466 methodNamesStmt (BindStmt pat cmd _ _) = methodNamesLCmd cmd
467 methodNamesStmt (RecStmt stmts _ _ _ _)
468 = methodNamesStmts stmts `addOneFV` loopAName
469 methodNamesStmt (LetStmt b) = emptyFVs
470 methodNamesStmt (ParStmt ss) = emptyFVs
471 -- ParStmt can't occur in commands, but it's not convenient to error
472 -- here so we just do what's convenient
476 %************************************************************************
480 %************************************************************************
483 rnArithSeq (From expr)
484 = rnLExpr expr `thenM` \ (expr', fvExpr) ->
485 returnM (From expr', fvExpr)
487 rnArithSeq (FromThen expr1 expr2)
488 = rnLExpr expr1 `thenM` \ (expr1', fvExpr1) ->
489 rnLExpr expr2 `thenM` \ (expr2', fvExpr2) ->
490 returnM (FromThen expr1' expr2', fvExpr1 `plusFV` fvExpr2)
492 rnArithSeq (FromTo expr1 expr2)
493 = rnLExpr expr1 `thenM` \ (expr1', fvExpr1) ->
494 rnLExpr expr2 `thenM` \ (expr2', fvExpr2) ->
495 returnM (FromTo expr1' expr2', fvExpr1 `plusFV` fvExpr2)
497 rnArithSeq (FromThenTo expr1 expr2 expr3)
498 = rnLExpr expr1 `thenM` \ (expr1', fvExpr1) ->
499 rnLExpr expr2 `thenM` \ (expr2', fvExpr2) ->
500 rnLExpr expr3 `thenM` \ (expr3', fvExpr3) ->
501 returnM (FromThenTo expr1' expr2' expr3',
502 plusFVs [fvExpr1, fvExpr2, fvExpr3])
505 %************************************************************************
507 Template Haskell brackets
509 %************************************************************************
512 rnBracket (VarBr n) = do { name <- lookupOccRn n
513 ; this_mod <- getModule
514 ; checkM (nameIsLocalOrFrom this_mod name) $ -- Reason: deprecation checking asumes the
515 do { loadInterfaceForName msg name -- home interface is loaded, and this is the
516 ; return () } -- only way that is going to happen
517 ; returnM (VarBr name, unitFV name) }
519 msg = ptext SLIT("Need interface for Template Haskell quoted Name")
521 rnBracket (ExpBr e) = do { (e', fvs) <- rnLExpr e
522 ; return (ExpBr e', fvs) }
523 rnBracket (PatBr p) = do { (p', fvs) <- rnLPat p
524 ; return (PatBr p', fvs) }
525 rnBracket (TypBr t) = do { (t', fvs) <- rnHsTypeFVs doc t
526 ; return (TypBr t', fvs) }
528 doc = ptext SLIT("In a Template-Haskell quoted type")
529 rnBracket (DecBr group)
530 = do { gbl_env <- getGblEnv
532 ; let gbl_env1 = gbl_env { tcg_mod = thFAKE }
533 -- Note the thFAKE. The top-level names from the bracketed
534 -- declarations will go into the name cache, and we don't want them to
535 -- confuse the Names for the current module.
536 -- By using a pretend module, thFAKE, we keep them safely out of the way.
538 ; avails <- getLocalDeclBinders gbl_env1 group
539 ; let names = concatMap availNames avails
541 ; let new_occs = map nameOccName names
542 trimmed_rdr_env = hideSomeUnquals (tcg_rdr_env gbl_env) new_occs
544 ; rdr_env' <- extendRdrEnvRn trimmed_rdr_env avails
545 -- In this situation we want to *shadow* top-level bindings.
547 -- bar = [d| foo = 1|]
548 -- If we don't shadow, we'll get an ambiguity complaint when we do
549 -- a lookupTopBndrRn (which uses lookupGreLocalRn) on the binder of the 'foo'
551 -- Furthermore, arguably if the splice does define foo, that should hide
552 -- any foo's further out
554 -- The shadowing is acheived by the call to hideSomeUnquals, which removes
555 -- the unqualified bindings of things defined by the bracket
557 ; setGblEnv (gbl_env { tcg_rdr_env = rdr_env',
558 tcg_dus = emptyDUs }) $ do
559 -- The emptyDUs is so that we just collect uses for this group alone
561 { (tcg_env, group') <- rnSrcDecls group
562 -- Discard the tcg_env; it contains only extra info about fixity
563 ; return (DecBr group', allUses (tcg_dus tcg_env)) } }
566 %************************************************************************
568 \subsubsection{@Stmt@s: in @do@ expressions}
570 %************************************************************************
573 rnStmts :: HsStmtContext Name -> [LStmt RdrName]
574 -> RnM (thing, FreeVars)
575 -> RnM (([LStmt Name], thing), FreeVars)
577 rnStmts (MDoExpr _) = rnMDoStmts
578 rnStmts ctxt = rnNormalStmts ctxt
580 rnNormalStmts :: HsStmtContext Name -> [LStmt RdrName]
581 -> RnM (thing, FreeVars)
582 -> RnM (([LStmt Name], thing), FreeVars)
583 -- Used for cases *other* than recursive mdo
584 -- Implements nested scopes
586 rnNormalStmts ctxt [] thing_inside
587 = do { (thing, fvs) <- thing_inside
588 ; return (([],thing), fvs) }
590 rnNormalStmts ctxt (L loc stmt : stmts) thing_inside
591 = do { ((stmt', (stmts', thing)), fvs)
592 <- rnStmt ctxt stmt $
593 rnNormalStmts ctxt stmts thing_inside
594 ; return (((L loc stmt' : stmts'), thing), fvs) }
596 rnStmt :: HsStmtContext Name -> Stmt RdrName
597 -> RnM (thing, FreeVars)
598 -> RnM ((Stmt Name, thing), FreeVars)
600 rnStmt ctxt (ExprStmt expr _ _) thing_inside
601 = do { (expr', fv_expr) <- rnLExpr expr
602 ; (then_op, fvs1) <- lookupSyntaxName thenMName
603 ; (thing, fvs2) <- thing_inside
604 ; return ((ExprStmt expr' then_op placeHolderType, thing),
605 fv_expr `plusFV` fvs1 `plusFV` fvs2) }
607 rnStmt ctxt (BindStmt pat expr _ _) thing_inside
608 = do { (expr', fv_expr) <- rnLExpr expr
609 -- The binders do not scope over the expression
610 ; (bind_op, fvs1) <- lookupSyntaxName bindMName
611 ; (fail_op, fvs2) <- lookupSyntaxName failMName
612 ; rnPatsAndThen (StmtCtxt ctxt) [pat] $ \ [pat'] -> do
613 { (thing, fvs3) <- thing_inside
614 ; return ((BindStmt pat' expr' bind_op fail_op, thing),
615 fv_expr `plusFV` fvs1 `plusFV` fvs2 `plusFV` fvs3) }}
616 -- fv_expr shouldn't really be filtered by the rnPatsAndThen
617 -- but it does not matter because the names are unique
619 rnStmt ctxt (LetStmt binds) thing_inside
620 = do { checkErr (ok ctxt binds)
621 (badIpBinds (ptext SLIT("a parallel list comprehension:")) binds)
622 ; rnLocalBindsAndThen binds $ \ binds' -> do
623 { (thing, fvs) <- thing_inside
624 ; return ((LetStmt binds', thing), fvs) }}
626 -- We do not allow implicit-parameter bindings in a parallel
627 -- list comprehension. I'm not sure what it might mean.
628 ok (ParStmtCtxt _) (HsIPBinds _) = False
631 rnStmt ctxt (RecStmt rec_stmts _ _ _ _) thing_inside
632 = bindLocatedLocalsRn doc (collectLStmtsBinders rec_stmts) $ \ bndrs ->
633 rn_rec_stmts bndrs rec_stmts `thenM` \ segs ->
634 thing_inside `thenM` \ (thing, fvs) ->
636 segs_w_fwd_refs = addFwdRefs segs
637 (ds, us, fs, rec_stmts') = unzip4 segs_w_fwd_refs
638 later_vars = nameSetToList (plusFVs ds `intersectNameSet` fvs)
639 fwd_vars = nameSetToList (plusFVs fs)
641 rec_stmt = RecStmt rec_stmts' later_vars fwd_vars [] emptyLHsBinds
643 returnM ((rec_stmt, thing), uses `plusFV` fvs)
645 doc = text "In a recursive do statement"
647 rnStmt ctxt (ParStmt segs) thing_inside
648 = do { parallel_list_comp <- doptM Opt_ParallelListComp
649 ; checkM parallel_list_comp parStmtErr
650 ; orig_lcl_env <- getLocalRdrEnv
651 ; ((segs',thing), fvs) <- go orig_lcl_env [] segs
652 ; return ((ParStmt segs', thing), fvs) }
654 -- type ParSeg id = [([LStmt id], [id])]
655 -- go :: NameSet -> [ParSeg RdrName]
656 -- -> RnM (([ParSeg Name], thing), FreeVars)
658 go orig_lcl_env bndrs []
659 = do { let { (bndrs', dups) = removeDups cmpByOcc bndrs
660 ; inner_env = extendLocalRdrEnv orig_lcl_env bndrs' }
662 ; (thing, fvs) <- setLocalRdrEnv inner_env thing_inside
663 ; return (([], thing), fvs) }
665 go orig_lcl_env bndrs_so_far ((stmts, _) : segs)
666 = do { ((stmts', (bndrs, segs', thing)), fvs)
667 <- rnNormalStmts par_ctxt stmts $ do
668 { -- Find the Names that are bound by stmts
669 lcl_env <- getLocalRdrEnv
670 ; let { rdr_bndrs = collectLStmtsBinders stmts
671 ; bndrs = map ( expectJust "rnStmt"
672 . lookupLocalRdrEnv lcl_env
674 ; new_bndrs = nub bndrs ++ bndrs_so_far
675 -- The nub is because there might be shadowing
677 -- So we'll look up (Unqual x) twice, getting
678 -- the second binding both times, which is the
681 -- Typecheck the thing inside, passing on all
682 -- the Names bound, but separately; revert the envt
683 ; ((segs', thing), fvs) <- setLocalRdrEnv orig_lcl_env $
684 go orig_lcl_env new_bndrs segs
686 -- Figure out which of the bound names are used
687 ; let used_bndrs = filter (`elemNameSet` fvs) bndrs
688 ; return ((used_bndrs, segs', thing), fvs) }
690 ; let seg' = (stmts', bndrs)
691 ; return (((seg':segs'), thing),
692 delListFromNameSet fvs bndrs) }
694 par_ctxt = ParStmtCtxt ctxt
696 cmpByOcc n1 n2 = nameOccName n1 `compare` nameOccName n2
697 dupErr vs = addErr (ptext SLIT("Duplicate binding in parallel list comprehension for:")
698 <+> quotes (ppr (head vs)))
702 %************************************************************************
704 \subsubsection{mdo expressions}
706 %************************************************************************
709 type FwdRefs = NameSet
710 type Segment stmts = (Defs,
711 Uses, -- May include defs
712 FwdRefs, -- A subset of uses that are
713 -- (a) used before they are bound in this segment, or
714 -- (b) used here, and bound in subsequent segments
715 stmts) -- Either Stmt or [Stmt]
718 ----------------------------------------------------
719 rnMDoStmts :: [LStmt RdrName]
720 -> RnM (thing, FreeVars)
721 -> RnM (([LStmt Name], thing), FreeVars)
722 rnMDoStmts stmts thing_inside
723 = -- Step1: bring all the binders of the mdo into scope
724 -- Remember that this also removes the binders from the
725 -- finally-returned free-vars
726 bindLocatedLocalsRn doc (collectLStmtsBinders stmts) $ \ bndrs ->
728 -- Step 2: Rename each individual stmt, making a
729 -- singleton segment. At this stage the FwdRefs field
730 -- isn't finished: it's empty for all except a BindStmt
731 -- for which it's the fwd refs within the bind itself
732 -- (This set may not be empty, because we're in a recursive
734 segs <- rn_rec_stmts bndrs stmts
736 ; (thing, fvs_later) <- thing_inside
739 -- Step 3: Fill in the fwd refs.
740 -- The segments are all singletons, but their fwd-ref
741 -- field mentions all the things used by the segment
742 -- that are bound after their use
743 segs_w_fwd_refs = addFwdRefs segs
745 -- Step 4: Group together the segments to make bigger segments
746 -- Invariant: in the result, no segment uses a variable
747 -- bound in a later segment
748 grouped_segs = glomSegments segs_w_fwd_refs
750 -- Step 5: Turn the segments into Stmts
751 -- Use RecStmt when and only when there are fwd refs
752 -- Also gather up the uses from the end towards the
753 -- start, so we can tell the RecStmt which things are
754 -- used 'after' the RecStmt
755 (stmts', fvs) = segsToStmts grouped_segs fvs_later
757 ; return ((stmts', thing), fvs) }
759 doc = text "In a recursive mdo-expression"
761 ---------------------------------------------
762 rn_rec_stmts :: [Name] -> [LStmt RdrName] -> RnM [Segment (LStmt Name)]
763 rn_rec_stmts bndrs stmts = mappM (rn_rec_stmt bndrs) stmts `thenM` \ segs_s ->
764 returnM (concat segs_s)
766 ----------------------------------------------------
767 rn_rec_stmt :: [Name] -> LStmt RdrName -> RnM [Segment (LStmt Name)]
768 -- Rename a Stmt that is inside a RecStmt (or mdo)
769 -- Assumes all binders are already in scope
770 -- Turns each stmt into a singleton Stmt
772 rn_rec_stmt all_bndrs (L loc (ExprStmt expr _ _))
773 = rnLExpr expr `thenM` \ (expr', fvs) ->
774 lookupSyntaxName thenMName `thenM` \ (then_op, fvs1) ->
775 returnM [(emptyNameSet, fvs `plusFV` fvs1, emptyNameSet,
776 L loc (ExprStmt expr' then_op placeHolderType))]
778 rn_rec_stmt all_bndrs (L loc (BindStmt pat expr _ _))
779 = rnLExpr expr `thenM` \ (expr', fv_expr) ->
780 rnLPat pat `thenM` \ (pat', fv_pat) ->
781 lookupSyntaxName bindMName `thenM` \ (bind_op, fvs1) ->
782 lookupSyntaxName failMName `thenM` \ (fail_op, fvs2) ->
784 bndrs = mkNameSet (collectPatBinders pat')
785 fvs = fv_expr `plusFV` fv_pat `plusFV` fvs1 `plusFV` fvs2
787 returnM [(bndrs, fvs, bndrs `intersectNameSet` fvs,
788 L loc (BindStmt pat' expr' bind_op fail_op))]
790 rn_rec_stmt all_bndrs (L loc (LetStmt binds@(HsIPBinds _)))
791 = do { addErr (badIpBinds (ptext SLIT("an mdo expression")) binds)
794 rn_rec_stmt all_bndrs (L loc (LetStmt (HsValBinds binds)))
795 = rnValBinds (trimWith all_bndrs) binds `thenM` \ (binds', du_binds) ->
796 returnM [(duDefs du_binds, duUses du_binds,
797 emptyNameSet, L loc (LetStmt (HsValBinds binds')))]
799 rn_rec_stmt all_bndrs (L loc (RecStmt stmts _ _ _ _)) -- Flatten Rec inside Rec
800 = rn_rec_stmts all_bndrs stmts
802 rn_rec_stmt all_bndrs stmt@(L _ (ParStmt _)) -- Syntactically illegal in mdo
803 = pprPanic "rn_rec_stmt" (ppr stmt)
805 ---------------------------------------------
806 addFwdRefs :: [Segment a] -> [Segment a]
807 -- So far the segments only have forward refs *within* the Stmt
808 -- (which happens for bind: x <- ...x...)
809 -- This function adds the cross-seg fwd ref info
812 = fst (foldr mk_seg ([], emptyNameSet) pairs)
814 mk_seg (defs, uses, fwds, stmts) (segs, later_defs)
815 = (new_seg : segs, all_defs)
817 new_seg = (defs, uses, new_fwds, stmts)
818 all_defs = later_defs `unionNameSets` defs
819 new_fwds = fwds `unionNameSets` (uses `intersectNameSet` later_defs)
820 -- Add the downstream fwd refs here
822 ----------------------------------------------------
823 -- Glomming the singleton segments of an mdo into
824 -- minimal recursive groups.
826 -- At first I thought this was just strongly connected components, but
827 -- there's an important constraint: the order of the stmts must not change.
830 -- mdo { x <- ...y...
837 -- Here, the first stmt mention 'y', which is bound in the third.
838 -- But that means that the innocent second stmt (p <- z) gets caught
839 -- up in the recursion. And that in turn means that the binding for
840 -- 'z' has to be included... and so on.
842 -- Start at the tail { r <- x }
843 -- Now add the next one { z <- y ; r <- x }
844 -- Now add one more { q <- x ; z <- y ; r <- x }
845 -- Now one more... but this time we have to group a bunch into rec
846 -- { rec { y <- ...x... ; q <- x ; z <- y } ; r <- x }
847 -- Now one more, which we can add on without a rec
849 -- rec { y <- ...x... ; q <- x ; z <- y } ;
851 -- Finally we add the last one; since it mentions y we have to
852 -- glom it togeher with the first two groups
853 -- { rec { x <- ...y...; p <- z ; y <- ...x... ;
854 -- q <- x ; z <- y } ;
857 glomSegments :: [Segment (LStmt Name)] -> [Segment [LStmt Name]]
860 glomSegments ((defs,uses,fwds,stmt) : segs)
861 -- Actually stmts will always be a singleton
862 = (seg_defs, seg_uses, seg_fwds, seg_stmts) : others
864 segs' = glomSegments segs
865 (extras, others) = grab uses segs'
866 (ds, us, fs, ss) = unzip4 extras
868 seg_defs = plusFVs ds `plusFV` defs
869 seg_uses = plusFVs us `plusFV` uses
870 seg_fwds = plusFVs fs `plusFV` fwds
871 seg_stmts = stmt : concat ss
873 grab :: NameSet -- The client
875 -> ([Segment a], -- Needed by the 'client'
876 [Segment a]) -- Not needed by the client
877 -- The result is simply a split of the input
879 = (reverse yeses, reverse noes)
881 (noes, yeses) = span not_needed (reverse dus)
882 not_needed (defs,_,_,_) = not (intersectsNameSet defs uses)
885 ----------------------------------------------------
886 segsToStmts :: [Segment [LStmt Name]]
887 -> FreeVars -- Free vars used 'later'
888 -> ([LStmt Name], FreeVars)
890 segsToStmts [] fvs_later = ([], fvs_later)
891 segsToStmts ((defs, uses, fwds, ss) : segs) fvs_later
892 = ASSERT( not (null ss) )
893 (new_stmt : later_stmts, later_uses `plusFV` uses)
895 (later_stmts, later_uses) = segsToStmts segs fvs_later
896 new_stmt | non_rec = head ss
897 | otherwise = L (getLoc (head ss)) $
898 RecStmt ss (nameSetToList used_later) (nameSetToList fwds)
901 non_rec = isSingleton ss && isEmptyNameSet fwds
902 used_later = defs `intersectNameSet` later_uses
903 -- The ones needed after the RecStmt
906 %************************************************************************
908 \subsubsection{Assertion utils}
910 %************************************************************************
913 srcSpanPrimLit :: SrcSpan -> HsExpr Name
914 srcSpanPrimLit span = HsLit (HsStringPrim (mkFastString (showSDoc (ppr span))))
916 mkAssertErrorExpr :: RnM (HsExpr Name, FreeVars)
917 -- Return an expression for (assertError "Foo.hs:27")
919 = getSrcSpanM `thenM` \ sloc ->
921 expr = HsApp (L sloc (HsVar assertErrorName))
922 (L sloc (srcSpanPrimLit sloc))
924 returnM (expr, emptyFVs)
927 %************************************************************************
929 \subsubsection{Errors}
931 %************************************************************************
934 patSynErr e = do { addErr (sep [ptext SLIT("Pattern syntax in expression context:"),
936 ; return (EWildPat, emptyFVs) }
938 parStmtErr = addErr (ptext SLIT("Illegal parallel list comprehension: use -XParallelListComp"))
940 badIpBinds what binds
941 = hang (ptext SLIT("Implicit-parameter bindings illegal in") <+> what)