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 )
26 import OccName ( plusOccEnv )
27 import RnNames ( getLocalDeclBinders, extendRdrEnvRn )
28 import RnTypes ( rnHsTypeFVs, rnLPat, rnOverLit, rnPatsAndThen, rnLit,
29 mkOpFormRn, mkOpAppRn, mkNegAppRn, checkSectionPrec,
30 dupFieldErr, checkTupSize )
31 import DynFlags ( DynFlag(..) )
32 import BasicTypes ( FixityDirection(..) )
33 import PrelNames ( thFAKE, hasKey, assertIdKey, assertErrorName,
34 loopAName, choiceAName, appAName, arrAName, composeAName, firstAName,
35 negateName, thenMName, bindMName, failMName )
36 import Name ( Name, nameOccName, nameIsLocalOrFrom )
38 import RdrName ( RdrName, emptyGlobalRdrEnv, extendLocalRdrEnv, lookupLocalRdrEnv )
39 import LoadIface ( loadHomeInterface )
40 import UniqFM ( isNullUFM )
41 import UniqSet ( emptyUniqSet )
43 import Util ( isSingleton )
44 import ListSetOps ( removeDups )
45 import Maybes ( fromJust )
47 import SrcLoc ( Located(..), unLoc, getLoc, cmpLocated )
50 import List ( unzip4 )
54 %************************************************************************
56 \subsubsection{Expressions}
58 %************************************************************************
61 rnExprs :: [LHsExpr RdrName] -> RnM ([LHsExpr Name], FreeVars)
62 rnExprs ls = rnExprs' ls emptyUniqSet
64 rnExprs' [] acc = returnM ([], acc)
65 rnExprs' (expr:exprs) acc
66 = rnLExpr expr `thenM` \ (expr', fvExpr) ->
68 -- Now we do a "seq" on the free vars because typically it's small
69 -- or empty, especially in very long lists of constants
71 acc' = acc `plusFV` fvExpr
73 (grubby_seqNameSet acc' rnExprs') exprs acc' `thenM` \ (exprs', fvExprs) ->
74 returnM (expr':exprs', fvExprs)
76 -- Grubby little function to do "seq" on namesets; replace by proper seq when GHC can do seq
77 grubby_seqNameSet ns result | isNullUFM ns = result
81 Variables. We look up the variable and return the resulting name.
84 rnLExpr :: LHsExpr RdrName -> RnM (LHsExpr Name, FreeVars)
85 rnLExpr = wrapLocFstM rnExpr
87 rnExpr :: HsExpr RdrName -> RnM (HsExpr Name, FreeVars)
90 = lookupOccRn v `thenM` \ name ->
91 doptM Opt_IgnoreAsserts `thenM` \ ignore_asserts ->
92 if name `hasKey` assertIdKey && not ignore_asserts then
93 -- We expand it to (GHC.Err.assertError location_string)
94 mkAssertErrorExpr `thenM` \ (e, fvs) ->
95 returnM (e, fvs `addOneFV` name)
96 -- Keep 'assert' as a free var, to ensure it's not reported as unused!
98 -- The normal case. Even if the Id was 'assert', if we are
99 -- ignoring assertions we leave it as GHC.Base.assert;
100 -- this function just ignores its first arg.
101 returnM (HsVar name, unitFV name)
104 = newIPNameRn v `thenM` \ name ->
105 returnM (HsIPVar name, emptyFVs)
109 returnM (HsLit lit, emptyFVs)
111 rnExpr (HsOverLit lit)
112 = rnOverLit lit `thenM` \ (lit', fvs) ->
113 returnM (HsOverLit lit', fvs)
115 rnExpr (HsApp fun arg)
116 = rnLExpr fun `thenM` \ (fun',fvFun) ->
117 rnLExpr arg `thenM` \ (arg',fvArg) ->
118 returnM (HsApp fun' arg', fvFun `plusFV` fvArg)
120 rnExpr (OpApp e1 op _ e2)
121 = rnLExpr e1 `thenM` \ (e1', fv_e1) ->
122 rnLExpr e2 `thenM` \ (e2', fv_e2) ->
123 rnLExpr op `thenM` \ (op'@(L _ (HsVar op_name)), fv_op) ->
126 -- When renaming code synthesised from "deriving" declarations
127 -- we used to avoid fixity stuff, but we can't easily tell any
128 -- more, so I've removed the test. Adding HsPars in TcGenDeriv
129 -- should prevent bad things happening.
130 lookupFixityRn op_name `thenM` \ fixity ->
131 mkOpAppRn e1' op' fixity e2' `thenM` \ final_e ->
134 fv_e1 `plusFV` fv_op `plusFV` fv_e2)
137 = rnLExpr e `thenM` \ (e', fv_e) ->
138 lookupSyntaxName negateName `thenM` \ (neg_name, fv_neg) ->
139 mkNegAppRn e' neg_name `thenM` \ final_e ->
140 returnM (final_e, fv_e `plusFV` fv_neg)
143 = rnLExpr e `thenM` \ (e', fvs_e) ->
144 returnM (HsPar e', fvs_e)
146 -- Template Haskell extensions
147 -- Don't ifdef-GHCI them because we want to fail gracefully
148 -- (not with an rnExpr crash) in a stage-1 compiler.
149 rnExpr e@(HsBracket br_body)
150 = checkTH e "bracket" `thenM_`
151 rnBracket br_body `thenM` \ (body', fvs_e) ->
152 returnM (HsBracket body', fvs_e)
154 rnExpr e@(HsSpliceE splice)
155 = rnSplice splice `thenM` \ (splice', fvs) ->
156 returnM (HsSpliceE splice', fvs)
158 rnExpr section@(SectionL expr op)
159 = rnLExpr expr `thenM` \ (expr', fvs_expr) ->
160 rnLExpr op `thenM` \ (op', fvs_op) ->
161 checkSectionPrec InfixL section op' expr' `thenM_`
162 returnM (SectionL expr' op', fvs_op `plusFV` fvs_expr)
164 rnExpr section@(SectionR op expr)
165 = rnLExpr op `thenM` \ (op', fvs_op) ->
166 rnLExpr expr `thenM` \ (expr', fvs_expr) ->
167 checkSectionPrec InfixR section op' expr' `thenM_`
168 returnM (SectionR op' expr', fvs_op `plusFV` fvs_expr)
170 rnExpr (HsCoreAnn ann expr)
171 = rnLExpr expr `thenM` \ (expr', fvs_expr) ->
172 returnM (HsCoreAnn ann expr', fvs_expr)
174 rnExpr (HsSCC lbl expr)
175 = rnLExpr expr `thenM` \ (expr', fvs_expr) ->
176 returnM (HsSCC lbl expr', fvs_expr)
178 rnExpr (HsLam matches)
179 = rnMatchGroup LambdaExpr matches `thenM` \ (matches', fvMatch) ->
180 returnM (HsLam matches', fvMatch)
182 rnExpr (HsCase expr matches)
183 = rnLExpr expr `thenM` \ (new_expr, e_fvs) ->
184 rnMatchGroup CaseAlt matches `thenM` \ (new_matches, ms_fvs) ->
185 returnM (HsCase new_expr new_matches, e_fvs `plusFV` ms_fvs)
187 rnExpr (HsLet binds expr)
188 = rnLocalBindsAndThen binds $ \ binds' ->
189 rnLExpr expr `thenM` \ (expr',fvExpr) ->
190 returnM (HsLet binds' expr', fvExpr)
192 rnExpr e@(HsDo do_or_lc stmts body _)
193 = do { ((stmts', body'), fvs) <- rnStmts do_or_lc stmts $
195 ; return (HsDo do_or_lc stmts' body' placeHolderType, fvs) }
197 rnExpr (ExplicitList _ exps)
198 = rnExprs exps `thenM` \ (exps', fvs) ->
199 returnM (ExplicitList placeHolderType exps', fvs `addOneFV` listTyCon_name)
201 rnExpr (ExplicitPArr _ exps)
202 = rnExprs exps `thenM` \ (exps', fvs) ->
203 returnM (ExplicitPArr placeHolderType exps', fvs)
205 rnExpr e@(ExplicitTuple exps boxity)
206 = checkTupSize tup_size `thenM_`
207 rnExprs exps `thenM` \ (exps', fvs) ->
208 returnM (ExplicitTuple exps' boxity, fvs `addOneFV` tycon_name)
210 tup_size = length exps
211 tycon_name = tupleTyCon_name boxity tup_size
213 rnExpr (RecordCon con_id _ rbinds)
214 = lookupLocatedOccRn con_id `thenM` \ conname ->
215 rnRbinds "construction" rbinds `thenM` \ (rbinds', fvRbinds) ->
216 returnM (RecordCon conname noPostTcExpr rbinds',
217 fvRbinds `addOneFV` unLoc conname)
219 rnExpr (RecordUpd expr rbinds _ _)
220 = rnLExpr expr `thenM` \ (expr', fvExpr) ->
221 rnRbinds "update" rbinds `thenM` \ (rbinds', fvRbinds) ->
222 returnM (RecordUpd expr' rbinds' placeHolderType placeHolderType,
223 fvExpr `plusFV` fvRbinds)
225 rnExpr (ExprWithTySig expr pty)
226 = rnLExpr expr `thenM` \ (expr', fvExpr) ->
227 rnHsTypeFVs doc pty `thenM` \ (pty', fvTy) ->
228 returnM (ExprWithTySig expr' pty', fvExpr `plusFV` fvTy)
230 doc = text "In an expression type signature"
232 rnExpr (HsIf p b1 b2)
233 = rnLExpr p `thenM` \ (p', fvP) ->
234 rnLExpr b1 `thenM` \ (b1', fvB1) ->
235 rnLExpr b2 `thenM` \ (b2', fvB2) ->
236 returnM (HsIf p' b1' b2', plusFVs [fvP, fvB1, fvB2])
239 = rnHsTypeFVs doc a `thenM` \ (t, fvT) ->
240 returnM (HsType t, fvT)
242 doc = text "In a type argument"
244 rnExpr (ArithSeq _ seq)
245 = rnArithSeq seq `thenM` \ (new_seq, fvs) ->
246 returnM (ArithSeq noPostTcExpr new_seq, fvs)
248 rnExpr (PArrSeq _ seq)
249 = rnArithSeq seq `thenM` \ (new_seq, fvs) ->
250 returnM (PArrSeq noPostTcExpr new_seq, fvs)
253 These three are pattern syntax appearing in expressions.
254 Since all the symbols are reservedops we can simply reject them.
255 We return a (bogus) EWildPat in each case.
258 rnExpr e@EWildPat = addErr (patSynErr e) `thenM_`
259 returnM (EWildPat, emptyFVs)
261 rnExpr e@(EAsPat _ _) = addErr (patSynErr e) `thenM_`
262 returnM (EWildPat, emptyFVs)
264 rnExpr e@(ELazyPat _) = addErr (patSynErr e) `thenM_`
265 returnM (EWildPat, emptyFVs)
268 %************************************************************************
272 %************************************************************************
275 rnExpr (HsProc pat body)
277 rnPatsAndThen ProcExpr [pat] $ \ [pat'] ->
278 rnCmdTop body `thenM` \ (body',fvBody) ->
279 returnM (HsProc pat' body', fvBody)
281 rnExpr (HsArrApp arrow arg _ ho rtl)
282 = select_arrow_scope (rnLExpr arrow) `thenM` \ (arrow',fvArrow) ->
283 rnLExpr arg `thenM` \ (arg',fvArg) ->
284 returnM (HsArrApp arrow' arg' placeHolderType ho rtl,
285 fvArrow `plusFV` fvArg)
287 select_arrow_scope tc = case ho of
288 HsHigherOrderApp -> tc
289 HsFirstOrderApp -> escapeArrowScope tc
292 rnExpr (HsArrForm op (Just _) [arg1, arg2])
293 = escapeArrowScope (rnLExpr op)
294 `thenM` \ (op'@(L _ (HsVar op_name)),fv_op) ->
295 rnCmdTop arg1 `thenM` \ (arg1',fv_arg1) ->
296 rnCmdTop arg2 `thenM` \ (arg2',fv_arg2) ->
300 lookupFixityRn op_name `thenM` \ fixity ->
301 mkOpFormRn arg1' op' fixity arg2' `thenM` \ final_e ->
304 fv_arg1 `plusFV` fv_op `plusFV` fv_arg2)
306 rnExpr (HsArrForm op fixity cmds)
307 = escapeArrowScope (rnLExpr op) `thenM` \ (op',fvOp) ->
308 rnCmdArgs cmds `thenM` \ (cmds',fvCmds) ->
309 returnM (HsArrForm op' fixity cmds', fvOp `plusFV` fvCmds)
311 rnExpr other = pprPanic "rnExpr: unexpected expression" (ppr other)
312 -- DictApp, DictLam, TyApp, TyLam
316 %************************************************************************
320 %************************************************************************
323 rnCmdArgs [] = returnM ([], emptyFVs)
325 = rnCmdTop arg `thenM` \ (arg',fvArg) ->
326 rnCmdArgs args `thenM` \ (args',fvArgs) ->
327 returnM (arg':args', fvArg `plusFV` fvArgs)
330 rnCmdTop = wrapLocFstM rnCmdTop'
332 rnCmdTop' (HsCmdTop cmd _ _ _)
333 = rnLExpr (convertOpFormsLCmd cmd) `thenM` \ (cmd', fvCmd) ->
335 cmd_names = [arrAName, composeAName, firstAName] ++
336 nameSetToList (methodNamesCmd (unLoc cmd'))
338 -- Generate the rebindable syntax for the monad
339 lookupSyntaxTable cmd_names `thenM` \ (cmd_names', cmd_fvs) ->
341 returnM (HsCmdTop cmd' [] placeHolderType cmd_names',
342 fvCmd `plusFV` cmd_fvs)
344 ---------------------------------------------------
345 -- convert OpApp's in a command context to HsArrForm's
347 convertOpFormsLCmd :: LHsCmd id -> LHsCmd id
348 convertOpFormsLCmd = fmap convertOpFormsCmd
350 convertOpFormsCmd :: HsCmd id -> HsCmd id
352 convertOpFormsCmd (HsApp c e) = HsApp (convertOpFormsLCmd c) e
353 convertOpFormsCmd (HsLam match) = HsLam (convertOpFormsMatch match)
354 convertOpFormsCmd (OpApp c1 op fixity c2)
356 arg1 = L (getLoc c1) $ HsCmdTop (convertOpFormsLCmd c1) [] placeHolderType []
357 arg2 = L (getLoc c2) $ HsCmdTop (convertOpFormsLCmd c2) [] placeHolderType []
359 HsArrForm op (Just fixity) [arg1, arg2]
361 convertOpFormsCmd (HsPar c) = HsPar (convertOpFormsLCmd c)
364 convertOpFormsCmd (HsCase exp matches)
365 = HsCase exp (convertOpFormsMatch matches)
367 convertOpFormsCmd (HsIf exp c1 c2)
368 = HsIf exp (convertOpFormsLCmd c1) (convertOpFormsLCmd c2)
370 convertOpFormsCmd (HsLet binds cmd)
371 = HsLet binds (convertOpFormsLCmd cmd)
373 convertOpFormsCmd (HsDo ctxt stmts body ty)
374 = HsDo ctxt (map (fmap convertOpFormsStmt) stmts)
375 (convertOpFormsLCmd body) ty
377 -- Anything else is unchanged. This includes HsArrForm (already done),
378 -- things with no sub-commands, and illegal commands (which will be
379 -- caught by the type checker)
380 convertOpFormsCmd c = c
382 convertOpFormsStmt (BindStmt pat cmd _ _)
383 = BindStmt pat (convertOpFormsLCmd cmd) noSyntaxExpr noSyntaxExpr
384 convertOpFormsStmt (ExprStmt cmd _ _)
385 = ExprStmt (convertOpFormsLCmd cmd) noSyntaxExpr placeHolderType
386 convertOpFormsStmt (RecStmt stmts lvs rvs es binds)
387 = RecStmt (map (fmap convertOpFormsStmt) stmts) lvs rvs es binds
388 convertOpFormsStmt stmt = stmt
390 convertOpFormsMatch (MatchGroup ms ty)
391 = MatchGroup (map (fmap convert) ms) ty
392 where convert (Match pat mty grhss)
393 = Match pat mty (convertOpFormsGRHSs grhss)
395 convertOpFormsGRHSs (GRHSs grhss binds)
396 = GRHSs (map convertOpFormsGRHS grhss) binds
398 convertOpFormsGRHS = fmap convert
400 convert (GRHS stmts cmd) = GRHS stmts (convertOpFormsLCmd cmd)
402 ---------------------------------------------------
403 type CmdNeeds = FreeVars -- Only inhabitants are
404 -- appAName, choiceAName, loopAName
406 -- find what methods the Cmd needs (loop, choice, apply)
407 methodNamesLCmd :: LHsCmd Name -> CmdNeeds
408 methodNamesLCmd = methodNamesCmd . unLoc
410 methodNamesCmd :: HsCmd Name -> CmdNeeds
412 methodNamesCmd cmd@(HsArrApp _arrow _arg _ HsFirstOrderApp _rtl)
414 methodNamesCmd cmd@(HsArrApp _arrow _arg _ HsHigherOrderApp _rtl)
416 methodNamesCmd cmd@(HsArrForm {}) = emptyFVs
418 methodNamesCmd (HsPar c) = methodNamesLCmd c
420 methodNamesCmd (HsIf p c1 c2)
421 = methodNamesLCmd c1 `plusFV` methodNamesLCmd c2 `addOneFV` choiceAName
423 methodNamesCmd (HsLet b c) = methodNamesLCmd c
425 methodNamesCmd (HsDo sc stmts body ty)
426 = methodNamesStmts stmts `plusFV` methodNamesLCmd body
428 methodNamesCmd (HsApp c e) = methodNamesLCmd c
430 methodNamesCmd (HsLam match) = methodNamesMatch match
432 methodNamesCmd (HsCase scrut matches)
433 = methodNamesMatch matches `addOneFV` choiceAName
435 methodNamesCmd other = emptyFVs
436 -- Other forms can't occur in commands, but it's not convenient
437 -- to error here so we just do what's convenient.
438 -- The type checker will complain later
440 ---------------------------------------------------
441 methodNamesMatch (MatchGroup ms ty)
442 = plusFVs (map do_one ms)
444 do_one (L _ (Match pats sig_ty grhss)) = methodNamesGRHSs grhss
446 -------------------------------------------------
448 methodNamesGRHSs (GRHSs grhss binds) = plusFVs (map methodNamesGRHS grhss)
450 -------------------------------------------------
451 methodNamesGRHS (L _ (GRHS stmts rhs)) = methodNamesLCmd rhs
453 ---------------------------------------------------
454 methodNamesStmts stmts = plusFVs (map methodNamesLStmt stmts)
456 ---------------------------------------------------
457 methodNamesLStmt = methodNamesStmt . unLoc
459 methodNamesStmt (ExprStmt cmd _ _) = methodNamesLCmd cmd
460 methodNamesStmt (BindStmt pat cmd _ _) = methodNamesLCmd cmd
461 methodNamesStmt (RecStmt stmts _ _ _ _)
462 = methodNamesStmts stmts `addOneFV` loopAName
463 methodNamesStmt (LetStmt b) = emptyFVs
464 methodNamesStmt (ParStmt ss) = emptyFVs
465 -- ParStmt can't occur in commands, but it's not convenient to error
466 -- here so we just do what's convenient
470 %************************************************************************
474 %************************************************************************
477 rnArithSeq (From expr)
478 = rnLExpr expr `thenM` \ (expr', fvExpr) ->
479 returnM (From expr', fvExpr)
481 rnArithSeq (FromThen expr1 expr2)
482 = rnLExpr expr1 `thenM` \ (expr1', fvExpr1) ->
483 rnLExpr expr2 `thenM` \ (expr2', fvExpr2) ->
484 returnM (FromThen expr1' expr2', fvExpr1 `plusFV` fvExpr2)
486 rnArithSeq (FromTo expr1 expr2)
487 = rnLExpr expr1 `thenM` \ (expr1', fvExpr1) ->
488 rnLExpr expr2 `thenM` \ (expr2', fvExpr2) ->
489 returnM (FromTo expr1' expr2', fvExpr1 `plusFV` fvExpr2)
491 rnArithSeq (FromThenTo expr1 expr2 expr3)
492 = rnLExpr expr1 `thenM` \ (expr1', fvExpr1) ->
493 rnLExpr expr2 `thenM` \ (expr2', fvExpr2) ->
494 rnLExpr expr3 `thenM` \ (expr3', fvExpr3) ->
495 returnM (FromThenTo expr1' expr2' expr3',
496 plusFVs [fvExpr1, fvExpr2, fvExpr3])
500 %************************************************************************
502 \subsubsection{@Rbinds@s and @Rpats@s: in record expressions}
504 %************************************************************************
508 = mappM_ field_dup_err dup_fields `thenM_`
509 mapFvRn rn_rbind rbinds `thenM` \ (rbinds', fvRbind) ->
510 returnM (rbinds', fvRbind)
512 (_, dup_fields) = removeDups cmpLocated [ f | (f,_) <- rbinds ]
514 field_dup_err dups = mappM_ (\f -> addLocErr f (dupFieldErr str)) dups
516 rn_rbind (field, expr)
517 = lookupLocatedGlobalOccRn field `thenM` \ fieldname ->
518 rnLExpr expr `thenM` \ (expr', fvExpr) ->
519 returnM ((fieldname, expr'), fvExpr `addOneFV` unLoc fieldname)
522 %************************************************************************
524 Template Haskell brackets
526 %************************************************************************
529 rnBracket (VarBr n) = do { name <- lookupOccRn n
530 ; this_mod <- getModule
531 ; checkM (nameIsLocalOrFrom this_mod name) $ -- Reason: deprecation checking asumes the
532 do { loadHomeInterface msg name -- home interface is loaded, and this is the
533 ; return () } -- only way that is going to happen
534 ; returnM (VarBr name, unitFV name) }
536 msg = ptext SLIT("Need interface for Template Haskell quoted Name")
538 rnBracket (ExpBr e) = do { (e', fvs) <- rnLExpr e
539 ; return (ExpBr e', fvs) }
540 rnBracket (PatBr p) = do { (p', fvs) <- rnLPat p
541 ; return (PatBr p', fvs) }
542 rnBracket (TypBr t) = do { (t', fvs) <- rnHsTypeFVs doc t
543 ; return (TypBr t', fvs) }
545 doc = ptext SLIT("In a Template-Haskell quoted type")
546 rnBracket (DecBr group)
547 = do { gbl_env <- getGblEnv
549 ; let gbl_env1 = gbl_env { tcg_mod = thFAKE }
550 -- Note the thFAKE. The top-level names from the bracketed
551 -- declarations will go into the name cache, and we don't want them to
552 -- confuse the Names for the current module.
553 -- By using a pretend module, thFAKE, we keep them safely out of the way.
555 ; names <- getLocalDeclBinders gbl_env1 group
556 ; rdr_env' <- extendRdrEnvRn emptyGlobalRdrEnv names
557 -- Furthermore, the names in the bracket shouldn't conflict with
558 -- existing top-level names E.g.
560 -- bar = [d| foo = 1|]
561 -- But both 'foo's get a LocalDef provenance, so we'd get a complaint unless
562 -- we start with an emptyGlobalRdrEnv
564 ; setGblEnv (gbl_env { tcg_rdr_env = tcg_rdr_env gbl_env1 `plusOccEnv` rdr_env',
565 tcg_dus = emptyDUs }) $ do
566 -- Notice plusOccEnv, not plusGlobalRdrEnv. In this situation we want
567 -- to *shadow* top-level bindings. (See the 'foo' example above.)
568 -- If we don't shadow, we'll get an ambiguity complaint when we do
569 -- a lookupTopBndrRn (which uses lookupGreLocalRn) on the binder of the 'foo'
571 -- Furthermore, arguably if the splice does define foo, that should hide
572 -- any foo's further out
574 -- The emptyDUs is so that we just collect uses for this group alone
576 { (tcg_env, group') <- rnSrcDecls group
577 -- Discard the tcg_env; it contains only extra info about fixity
578 ; return (DecBr group', allUses (tcg_dus tcg_env)) } }
581 %************************************************************************
583 \subsubsection{@Stmt@s: in @do@ expressions}
585 %************************************************************************
588 rnStmts :: HsStmtContext Name -> [LStmt RdrName]
589 -> RnM (thing, FreeVars)
590 -> RnM (([LStmt Name], thing), FreeVars)
592 rnStmts (MDoExpr _) = rnMDoStmts
593 rnStmts ctxt = rnNormalStmts ctxt
595 rnNormalStmts :: HsStmtContext Name -> [LStmt RdrName]
596 -> RnM (thing, FreeVars)
597 -> RnM (([LStmt Name], thing), FreeVars)
598 -- Used for cases *other* than recursive mdo
599 -- Implements nested scopes
601 rnNormalStmts ctxt [] thing_inside
602 = do { (thing, fvs) <- thing_inside
603 ; return (([],thing), fvs) }
605 rnNormalStmts ctxt (L loc stmt : stmts) thing_inside
606 = do { ((stmt', (stmts', thing)), fvs)
607 <- rnStmt ctxt stmt $
608 rnNormalStmts ctxt stmts thing_inside
609 ; return (((L loc stmt' : stmts'), thing), fvs) }
611 rnStmt :: HsStmtContext Name -> Stmt RdrName
612 -> RnM (thing, FreeVars)
613 -> RnM ((Stmt Name, thing), FreeVars)
615 rnStmt ctxt (ExprStmt expr _ _) thing_inside
616 = do { (expr', fv_expr) <- rnLExpr expr
617 ; (then_op, fvs1) <- lookupSyntaxName thenMName
618 ; (thing, fvs2) <- thing_inside
619 ; return ((ExprStmt expr' then_op placeHolderType, thing),
620 fv_expr `plusFV` fvs1 `plusFV` fvs2) }
622 rnStmt ctxt (BindStmt pat expr _ _) thing_inside
623 = do { (expr', fv_expr) <- rnLExpr expr
624 -- The binders do not scope over the expression
625 ; (bind_op, fvs1) <- lookupSyntaxName bindMName
626 ; (fail_op, fvs2) <- lookupSyntaxName failMName
627 ; rnPatsAndThen (StmtCtxt ctxt) [pat] $ \ [pat'] -> do
628 { (thing, fvs3) <- thing_inside
629 ; return ((BindStmt pat' expr' bind_op fail_op, thing),
630 fv_expr `plusFV` fvs1 `plusFV` fvs2 `plusFV` fvs3) }}
631 -- fv_expr shouldn't really be filtered by the rnPatsAndThen
632 -- but it does not matter because the names are unique
634 rnStmt ctxt (LetStmt binds) thing_inside
635 = do { checkErr (ok ctxt binds)
636 (badIpBinds (ptext SLIT("a parallel list comprehension:")) binds)
637 ; rnLocalBindsAndThen binds $ \ binds' -> do
638 { (thing, fvs) <- thing_inside
639 ; return ((LetStmt binds', thing), fvs) }}
641 -- We do not allow implicit-parameter bindings in a parallel
642 -- list comprehension. I'm not sure what it might mean.
643 ok (ParStmtCtxt _) (HsIPBinds _) = False
646 rnStmt ctxt (RecStmt rec_stmts _ _ _ _) thing_inside
647 = bindLocatedLocalsRn doc (collectLStmtsBinders rec_stmts) $ \ bndrs ->
648 rn_rec_stmts bndrs rec_stmts `thenM` \ segs ->
649 thing_inside `thenM` \ (thing, fvs) ->
651 segs_w_fwd_refs = addFwdRefs segs
652 (ds, us, fs, rec_stmts') = unzip4 segs_w_fwd_refs
653 later_vars = nameSetToList (plusFVs ds `intersectNameSet` fvs)
654 fwd_vars = nameSetToList (plusFVs fs)
656 rec_stmt = RecStmt rec_stmts' later_vars fwd_vars [] emptyLHsBinds
658 returnM ((rec_stmt, thing), uses `plusFV` fvs)
660 doc = text "In a recursive do statement"
662 rnStmt ctxt (ParStmt segs) thing_inside
663 = do { opt_GlasgowExts <- doptM Opt_GlasgowExts
664 ; checkM opt_GlasgowExts parStmtErr
665 ; orig_lcl_env <- getLocalRdrEnv
666 ; ((segs',thing), fvs) <- go orig_lcl_env [] segs
667 ; return ((ParStmt segs', thing), fvs) }
669 -- type ParSeg id = [([LStmt id], [id])]
670 -- go :: NameSet -> [ParSeg RdrName]
671 -- -> RnM (([ParSeg Name], thing), FreeVars)
673 go orig_lcl_env bndrs []
674 = do { let { (bndrs', dups) = removeDups cmpByOcc bndrs
675 ; inner_env = extendLocalRdrEnv orig_lcl_env bndrs' }
677 ; (thing, fvs) <- setLocalRdrEnv inner_env thing_inside
678 ; return (([], thing), fvs) }
680 go orig_lcl_env bndrs_so_far ((stmts, _) : segs)
681 = do { ((stmts', (bndrs, segs', thing)), fvs)
682 <- rnNormalStmts par_ctxt stmts $ do
683 { -- Find the Names that are bound by stmts
684 lcl_env <- getLocalRdrEnv
685 ; let { rdr_bndrs = collectLStmtsBinders stmts
686 ; bndrs = map ( fromJust
687 . lookupLocalRdrEnv lcl_env
689 ; new_bndrs = nub bndrs ++ bndrs_so_far
690 -- The nub is because there might be shadowing
692 -- So we'll look up (Unqual x) twice, getting
693 -- the second binding both times, which is the
696 -- Typecheck the thing inside, passing on all
697 -- the Names bound, but separately; revert the envt
698 ; ((segs', thing), fvs) <- setLocalRdrEnv orig_lcl_env $
699 go orig_lcl_env new_bndrs segs
701 -- Figure out which of the bound names are used
702 ; let used_bndrs = filter (`elemNameSet` fvs) bndrs
703 ; return ((used_bndrs, segs', thing), fvs) }
705 ; let seg' = (stmts', bndrs)
706 ; return (((seg':segs'), thing),
707 delListFromNameSet fvs bndrs) }
709 par_ctxt = ParStmtCtxt ctxt
711 cmpByOcc n1 n2 = nameOccName n1 `compare` nameOccName n2
712 dupErr vs = addErr (ptext SLIT("Duplicate binding in parallel list comprehension for:")
713 <+> quotes (ppr (head vs)))
717 %************************************************************************
719 \subsubsection{mdo expressions}
721 %************************************************************************
724 type FwdRefs = NameSet
725 type Segment stmts = (Defs,
726 Uses, -- May include defs
727 FwdRefs, -- A subset of uses that are
728 -- (a) used before they are bound in this segment, or
729 -- (b) used here, and bound in subsequent segments
730 stmts) -- Either Stmt or [Stmt]
733 ----------------------------------------------------
734 rnMDoStmts :: [LStmt RdrName]
735 -> RnM (thing, FreeVars)
736 -> RnM (([LStmt Name], thing), FreeVars)
737 rnMDoStmts stmts thing_inside
738 = -- Step1: bring all the binders of the mdo into scope
739 -- Remember that this also removes the binders from the
740 -- finally-returned free-vars
741 bindLocatedLocalsRn doc (collectLStmtsBinders stmts) $ \ bndrs ->
743 -- Step 2: Rename each individual stmt, making a
744 -- singleton segment. At this stage the FwdRefs field
745 -- isn't finished: it's empty for all except a BindStmt
746 -- for which it's the fwd refs within the bind itself
747 -- (This set may not be empty, because we're in a recursive
749 segs <- rn_rec_stmts bndrs stmts
751 ; (thing, fvs_later) <- thing_inside
754 -- Step 3: Fill in the fwd refs.
755 -- The segments are all singletons, but their fwd-ref
756 -- field mentions all the things used by the segment
757 -- that are bound after their use
758 segs_w_fwd_refs = addFwdRefs segs
760 -- Step 4: Group together the segments to make bigger segments
761 -- Invariant: in the result, no segment uses a variable
762 -- bound in a later segment
763 grouped_segs = glomSegments segs_w_fwd_refs
765 -- Step 5: Turn the segments into Stmts
766 -- Use RecStmt when and only when there are fwd refs
767 -- Also gather up the uses from the end towards the
768 -- start, so we can tell the RecStmt which things are
769 -- used 'after' the RecStmt
770 (stmts', fvs) = segsToStmts grouped_segs fvs_later
772 ; return ((stmts', thing), fvs) }
774 doc = text "In a recursive mdo-expression"
776 ---------------------------------------------
777 rn_rec_stmts :: [Name] -> [LStmt RdrName] -> RnM [Segment (LStmt Name)]
778 rn_rec_stmts bndrs stmts = mappM (rn_rec_stmt bndrs) stmts `thenM` \ segs_s ->
779 returnM (concat segs_s)
781 ----------------------------------------------------
782 rn_rec_stmt :: [Name] -> LStmt RdrName -> RnM [Segment (LStmt Name)]
783 -- Rename a Stmt that is inside a RecStmt (or mdo)
784 -- Assumes all binders are already in scope
785 -- Turns each stmt into a singleton Stmt
787 rn_rec_stmt all_bndrs (L loc (ExprStmt expr _ _))
788 = rnLExpr expr `thenM` \ (expr', fvs) ->
789 lookupSyntaxName thenMName `thenM` \ (then_op, fvs1) ->
790 returnM [(emptyNameSet, fvs `plusFV` fvs1, emptyNameSet,
791 L loc (ExprStmt expr' then_op placeHolderType))]
793 rn_rec_stmt all_bndrs (L loc (BindStmt pat expr _ _))
794 = rnLExpr expr `thenM` \ (expr', fv_expr) ->
795 rnLPat pat `thenM` \ (pat', fv_pat) ->
796 lookupSyntaxName bindMName `thenM` \ (bind_op, fvs1) ->
797 lookupSyntaxName failMName `thenM` \ (fail_op, fvs2) ->
799 bndrs = mkNameSet (collectPatBinders pat')
800 fvs = fv_expr `plusFV` fv_pat `plusFV` fvs1 `plusFV` fvs2
802 returnM [(bndrs, fvs, bndrs `intersectNameSet` fvs,
803 L loc (BindStmt pat' expr' bind_op fail_op))]
805 rn_rec_stmt all_bndrs (L loc (LetStmt binds@(HsIPBinds _)))
806 = do { addErr (badIpBinds (ptext SLIT("an mdo expression")) binds)
809 rn_rec_stmt all_bndrs (L loc (LetStmt (HsValBinds binds)))
810 = rnValBinds (trimWith all_bndrs) binds `thenM` \ (binds', du_binds) ->
811 returnM [(duDefs du_binds, duUses du_binds,
812 emptyNameSet, L loc (LetStmt (HsValBinds binds')))]
814 rn_rec_stmt all_bndrs (L loc (RecStmt stmts _ _ _ _)) -- Flatten Rec inside Rec
815 = rn_rec_stmts all_bndrs stmts
817 rn_rec_stmt all_bndrs stmt@(L _ (ParStmt _)) -- Syntactically illegal in mdo
818 = pprPanic "rn_rec_stmt" (ppr stmt)
820 ---------------------------------------------
821 addFwdRefs :: [Segment a] -> [Segment a]
822 -- So far the segments only have forward refs *within* the Stmt
823 -- (which happens for bind: x <- ...x...)
824 -- This function adds the cross-seg fwd ref info
827 = fst (foldr mk_seg ([], emptyNameSet) pairs)
829 mk_seg (defs, uses, fwds, stmts) (segs, later_defs)
830 = (new_seg : segs, all_defs)
832 new_seg = (defs, uses, new_fwds, stmts)
833 all_defs = later_defs `unionNameSets` defs
834 new_fwds = fwds `unionNameSets` (uses `intersectNameSet` later_defs)
835 -- Add the downstream fwd refs here
837 ----------------------------------------------------
838 -- Glomming the singleton segments of an mdo into
839 -- minimal recursive groups.
841 -- At first I thought this was just strongly connected components, but
842 -- there's an important constraint: the order of the stmts must not change.
845 -- mdo { x <- ...y...
852 -- Here, the first stmt mention 'y', which is bound in the third.
853 -- But that means that the innocent second stmt (p <- z) gets caught
854 -- up in the recursion. And that in turn means that the binding for
855 -- 'z' has to be included... and so on.
857 -- Start at the tail { r <- x }
858 -- Now add the next one { z <- y ; r <- x }
859 -- Now add one more { q <- x ; z <- y ; r <- x }
860 -- Now one more... but this time we have to group a bunch into rec
861 -- { rec { y <- ...x... ; q <- x ; z <- y } ; r <- x }
862 -- Now one more, which we can add on without a rec
864 -- rec { y <- ...x... ; q <- x ; z <- y } ;
866 -- Finally we add the last one; since it mentions y we have to
867 -- glom it togeher with the first two groups
868 -- { rec { x <- ...y...; p <- z ; y <- ...x... ;
869 -- q <- x ; z <- y } ;
872 glomSegments :: [Segment (LStmt Name)] -> [Segment [LStmt Name]]
875 glomSegments ((defs,uses,fwds,stmt) : segs)
876 -- Actually stmts will always be a singleton
877 = (seg_defs, seg_uses, seg_fwds, seg_stmts) : others
879 segs' = glomSegments segs
880 (extras, others) = grab uses segs'
881 (ds, us, fs, ss) = unzip4 extras
883 seg_defs = plusFVs ds `plusFV` defs
884 seg_uses = plusFVs us `plusFV` uses
885 seg_fwds = plusFVs fs `plusFV` fwds
886 seg_stmts = stmt : concat ss
888 grab :: NameSet -- The client
890 -> ([Segment a], -- Needed by the 'client'
891 [Segment a]) -- Not needed by the client
892 -- The result is simply a split of the input
894 = (reverse yeses, reverse noes)
896 (noes, yeses) = span not_needed (reverse dus)
897 not_needed (defs,_,_,_) = not (intersectsNameSet defs uses)
900 ----------------------------------------------------
901 segsToStmts :: [Segment [LStmt Name]]
902 -> FreeVars -- Free vars used 'later'
903 -> ([LStmt Name], FreeVars)
905 segsToStmts [] fvs_later = ([], fvs_later)
906 segsToStmts ((defs, uses, fwds, ss) : segs) fvs_later
907 = ASSERT( not (null ss) )
908 (new_stmt : later_stmts, later_uses `plusFV` uses)
910 (later_stmts, later_uses) = segsToStmts segs fvs_later
911 new_stmt | non_rec = head ss
912 | otherwise = L (getLoc (head ss)) $
913 RecStmt ss (nameSetToList used_later) (nameSetToList fwds)
916 non_rec = isSingleton ss && isEmptyNameSet fwds
917 used_later = defs `intersectNameSet` later_uses
918 -- The ones needed after the RecStmt
921 %************************************************************************
923 \subsubsection{Assertion utils}
925 %************************************************************************
928 mkAssertErrorExpr :: RnM (HsExpr Name, FreeVars)
929 -- Return an expression for (assertError "Foo.hs:27")
931 = getSrcSpanM `thenM` \ sloc ->
933 expr = HsApp (L sloc (HsVar assertErrorName)) (L sloc (HsLit msg))
934 msg = HsStringPrim (mkFastString (showSDoc (ppr sloc)))
936 returnM (expr, emptyFVs)
939 %************************************************************************
941 \subsubsection{Errors}
943 %************************************************************************
947 = sep [ptext SLIT("Pattern syntax in expression context:"),
950 parStmtErr = addErr (ptext SLIT("Illegal parallel list comprehension: use -fglasgow-exts"))
952 badIpBinds what binds
953 = hang (ptext SLIT("Implicit-parameter bindings illegal in") <+> what)