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 = patSynErr e
259 rnExpr e@(EAsPat {}) = patSynErr e
260 rnExpr e@(ELazyPat {}) = patSynErr e
263 %************************************************************************
267 %************************************************************************
270 rnExpr (HsProc pat body)
272 rnPatsAndThen ProcExpr [pat] $ \ [pat'] ->
273 rnCmdTop body `thenM` \ (body',fvBody) ->
274 returnM (HsProc pat' body', fvBody)
276 rnExpr (HsArrApp arrow arg _ ho rtl)
277 = select_arrow_scope (rnLExpr arrow) `thenM` \ (arrow',fvArrow) ->
278 rnLExpr arg `thenM` \ (arg',fvArg) ->
279 returnM (HsArrApp arrow' arg' placeHolderType ho rtl,
280 fvArrow `plusFV` fvArg)
282 select_arrow_scope tc = case ho of
283 HsHigherOrderApp -> tc
284 HsFirstOrderApp -> escapeArrowScope tc
287 rnExpr (HsArrForm op (Just _) [arg1, arg2])
288 = escapeArrowScope (rnLExpr op)
289 `thenM` \ (op'@(L _ (HsVar op_name)),fv_op) ->
290 rnCmdTop arg1 `thenM` \ (arg1',fv_arg1) ->
291 rnCmdTop arg2 `thenM` \ (arg2',fv_arg2) ->
295 lookupFixityRn op_name `thenM` \ fixity ->
296 mkOpFormRn arg1' op' fixity arg2' `thenM` \ final_e ->
299 fv_arg1 `plusFV` fv_op `plusFV` fv_arg2)
301 rnExpr (HsArrForm op fixity cmds)
302 = escapeArrowScope (rnLExpr op) `thenM` \ (op',fvOp) ->
303 rnCmdArgs cmds `thenM` \ (cmds',fvCmds) ->
304 returnM (HsArrForm op' fixity cmds', fvOp `plusFV` fvCmds)
306 rnExpr other = pprPanic "rnExpr: unexpected expression" (ppr other)
307 -- DictApp, DictLam, TyApp, TyLam
311 %************************************************************************
315 %************************************************************************
318 rnCmdArgs [] = returnM ([], emptyFVs)
320 = rnCmdTop arg `thenM` \ (arg',fvArg) ->
321 rnCmdArgs args `thenM` \ (args',fvArgs) ->
322 returnM (arg':args', fvArg `plusFV` fvArgs)
325 rnCmdTop = wrapLocFstM rnCmdTop'
327 rnCmdTop' (HsCmdTop cmd _ _ _)
328 = rnLExpr (convertOpFormsLCmd cmd) `thenM` \ (cmd', fvCmd) ->
330 cmd_names = [arrAName, composeAName, firstAName] ++
331 nameSetToList (methodNamesCmd (unLoc cmd'))
333 -- Generate the rebindable syntax for the monad
334 lookupSyntaxTable cmd_names `thenM` \ (cmd_names', cmd_fvs) ->
336 returnM (HsCmdTop cmd' [] placeHolderType cmd_names',
337 fvCmd `plusFV` cmd_fvs)
339 ---------------------------------------------------
340 -- convert OpApp's in a command context to HsArrForm's
342 convertOpFormsLCmd :: LHsCmd id -> LHsCmd id
343 convertOpFormsLCmd = fmap convertOpFormsCmd
345 convertOpFormsCmd :: HsCmd id -> HsCmd id
347 convertOpFormsCmd (HsApp c e) = HsApp (convertOpFormsLCmd c) e
348 convertOpFormsCmd (HsLam match) = HsLam (convertOpFormsMatch match)
349 convertOpFormsCmd (OpApp c1 op fixity c2)
351 arg1 = L (getLoc c1) $ HsCmdTop (convertOpFormsLCmd c1) [] placeHolderType []
352 arg2 = L (getLoc c2) $ HsCmdTop (convertOpFormsLCmd c2) [] placeHolderType []
354 HsArrForm op (Just fixity) [arg1, arg2]
356 convertOpFormsCmd (HsPar c) = HsPar (convertOpFormsLCmd c)
359 convertOpFormsCmd (HsCase exp matches)
360 = HsCase exp (convertOpFormsMatch matches)
362 convertOpFormsCmd (HsIf exp c1 c2)
363 = HsIf exp (convertOpFormsLCmd c1) (convertOpFormsLCmd c2)
365 convertOpFormsCmd (HsLet binds cmd)
366 = HsLet binds (convertOpFormsLCmd cmd)
368 convertOpFormsCmd (HsDo ctxt stmts body ty)
369 = HsDo ctxt (map (fmap convertOpFormsStmt) stmts)
370 (convertOpFormsLCmd body) ty
372 -- Anything else is unchanged. This includes HsArrForm (already done),
373 -- things with no sub-commands, and illegal commands (which will be
374 -- caught by the type checker)
375 convertOpFormsCmd c = c
377 convertOpFormsStmt (BindStmt pat cmd _ _)
378 = BindStmt pat (convertOpFormsLCmd cmd) noSyntaxExpr noSyntaxExpr
379 convertOpFormsStmt (ExprStmt cmd _ _)
380 = ExprStmt (convertOpFormsLCmd cmd) noSyntaxExpr placeHolderType
381 convertOpFormsStmt (RecStmt stmts lvs rvs es binds)
382 = RecStmt (map (fmap convertOpFormsStmt) stmts) lvs rvs es binds
383 convertOpFormsStmt stmt = stmt
385 convertOpFormsMatch (MatchGroup ms ty)
386 = MatchGroup (map (fmap convert) ms) ty
387 where convert (Match pat mty grhss)
388 = Match pat mty (convertOpFormsGRHSs grhss)
390 convertOpFormsGRHSs (GRHSs grhss binds)
391 = GRHSs (map convertOpFormsGRHS grhss) binds
393 convertOpFormsGRHS = fmap convert
395 convert (GRHS stmts cmd) = GRHS stmts (convertOpFormsLCmd cmd)
397 ---------------------------------------------------
398 type CmdNeeds = FreeVars -- Only inhabitants are
399 -- appAName, choiceAName, loopAName
401 -- find what methods the Cmd needs (loop, choice, apply)
402 methodNamesLCmd :: LHsCmd Name -> CmdNeeds
403 methodNamesLCmd = methodNamesCmd . unLoc
405 methodNamesCmd :: HsCmd Name -> CmdNeeds
407 methodNamesCmd cmd@(HsArrApp _arrow _arg _ HsFirstOrderApp _rtl)
409 methodNamesCmd cmd@(HsArrApp _arrow _arg _ HsHigherOrderApp _rtl)
411 methodNamesCmd cmd@(HsArrForm {}) = emptyFVs
413 methodNamesCmd (HsPar c) = methodNamesLCmd c
415 methodNamesCmd (HsIf p c1 c2)
416 = methodNamesLCmd c1 `plusFV` methodNamesLCmd c2 `addOneFV` choiceAName
418 methodNamesCmd (HsLet b c) = methodNamesLCmd c
420 methodNamesCmd (HsDo sc stmts body ty)
421 = methodNamesStmts stmts `plusFV` methodNamesLCmd body
423 methodNamesCmd (HsApp c e) = methodNamesLCmd c
425 methodNamesCmd (HsLam match) = methodNamesMatch match
427 methodNamesCmd (HsCase scrut matches)
428 = methodNamesMatch matches `addOneFV` choiceAName
430 methodNamesCmd other = emptyFVs
431 -- Other forms can't occur in commands, but it's not convenient
432 -- to error here so we just do what's convenient.
433 -- The type checker will complain later
435 ---------------------------------------------------
436 methodNamesMatch (MatchGroup ms ty)
437 = plusFVs (map do_one ms)
439 do_one (L _ (Match pats sig_ty grhss)) = methodNamesGRHSs grhss
441 -------------------------------------------------
443 methodNamesGRHSs (GRHSs grhss binds) = plusFVs (map methodNamesGRHS grhss)
445 -------------------------------------------------
446 methodNamesGRHS (L _ (GRHS stmts rhs)) = methodNamesLCmd rhs
448 ---------------------------------------------------
449 methodNamesStmts stmts = plusFVs (map methodNamesLStmt stmts)
451 ---------------------------------------------------
452 methodNamesLStmt = methodNamesStmt . unLoc
454 methodNamesStmt (ExprStmt cmd _ _) = methodNamesLCmd cmd
455 methodNamesStmt (BindStmt pat cmd _ _) = methodNamesLCmd cmd
456 methodNamesStmt (RecStmt stmts _ _ _ _)
457 = methodNamesStmts stmts `addOneFV` loopAName
458 methodNamesStmt (LetStmt b) = emptyFVs
459 methodNamesStmt (ParStmt ss) = emptyFVs
460 -- ParStmt can't occur in commands, but it's not convenient to error
461 -- here so we just do what's convenient
465 %************************************************************************
469 %************************************************************************
472 rnArithSeq (From expr)
473 = rnLExpr expr `thenM` \ (expr', fvExpr) ->
474 returnM (From expr', fvExpr)
476 rnArithSeq (FromThen expr1 expr2)
477 = rnLExpr expr1 `thenM` \ (expr1', fvExpr1) ->
478 rnLExpr expr2 `thenM` \ (expr2', fvExpr2) ->
479 returnM (FromThen expr1' expr2', fvExpr1 `plusFV` fvExpr2)
481 rnArithSeq (FromTo expr1 expr2)
482 = rnLExpr expr1 `thenM` \ (expr1', fvExpr1) ->
483 rnLExpr expr2 `thenM` \ (expr2', fvExpr2) ->
484 returnM (FromTo expr1' expr2', fvExpr1 `plusFV` fvExpr2)
486 rnArithSeq (FromThenTo expr1 expr2 expr3)
487 = rnLExpr expr1 `thenM` \ (expr1', fvExpr1) ->
488 rnLExpr expr2 `thenM` \ (expr2', fvExpr2) ->
489 rnLExpr expr3 `thenM` \ (expr3', fvExpr3) ->
490 returnM (FromThenTo expr1' expr2' expr3',
491 plusFVs [fvExpr1, fvExpr2, fvExpr3])
495 %************************************************************************
497 \subsubsection{@Rbinds@s and @Rpats@s: in record expressions}
499 %************************************************************************
503 = mappM_ field_dup_err dup_fields `thenM_`
504 mapFvRn rn_rbind rbinds `thenM` \ (rbinds', fvRbind) ->
505 returnM (rbinds', fvRbind)
507 (_, dup_fields) = removeDups cmpLocated [ f | (f,_) <- rbinds ]
509 field_dup_err dups = mappM_ (\f -> addLocErr f (dupFieldErr str)) dups
511 rn_rbind (field, expr)
512 = lookupLocatedGlobalOccRn field `thenM` \ fieldname ->
513 rnLExpr expr `thenM` \ (expr', fvExpr) ->
514 returnM ((fieldname, expr'), fvExpr `addOneFV` unLoc fieldname)
517 %************************************************************************
519 Template Haskell brackets
521 %************************************************************************
524 rnBracket (VarBr n) = do { name <- lookupOccRn n
525 ; this_mod <- getModule
526 ; checkM (nameIsLocalOrFrom this_mod name) $ -- Reason: deprecation checking asumes the
527 do { loadHomeInterface msg name -- home interface is loaded, and this is the
528 ; return () } -- only way that is going to happen
529 ; returnM (VarBr name, unitFV name) }
531 msg = ptext SLIT("Need interface for Template Haskell quoted Name")
533 rnBracket (ExpBr e) = do { (e', fvs) <- rnLExpr e
534 ; return (ExpBr e', fvs) }
535 rnBracket (PatBr p) = do { (p', fvs) <- rnLPat p
536 ; return (PatBr p', fvs) }
537 rnBracket (TypBr t) = do { (t', fvs) <- rnHsTypeFVs doc t
538 ; return (TypBr t', fvs) }
540 doc = ptext SLIT("In a Template-Haskell quoted type")
541 rnBracket (DecBr group)
542 = do { gbl_env <- getGblEnv
544 ; let gbl_env1 = gbl_env { tcg_mod = thFAKE }
545 -- Note the thFAKE. The top-level names from the bracketed
546 -- declarations will go into the name cache, and we don't want them to
547 -- confuse the Names for the current module.
548 -- By using a pretend module, thFAKE, we keep them safely out of the way.
550 ; names <- getLocalDeclBinders gbl_env1 group
551 ; rdr_env' <- extendRdrEnvRn emptyGlobalRdrEnv names
552 -- Furthermore, the names in the bracket shouldn't conflict with
553 -- existing top-level names E.g.
555 -- bar = [d| foo = 1|]
556 -- But both 'foo's get a LocalDef provenance, so we'd get a complaint unless
557 -- we start with an emptyGlobalRdrEnv
559 ; setGblEnv (gbl_env { tcg_rdr_env = tcg_rdr_env gbl_env1 `plusOccEnv` rdr_env',
560 tcg_dus = emptyDUs }) $ do
561 -- Notice plusOccEnv, not plusGlobalRdrEnv. In this situation we want
562 -- to *shadow* top-level bindings. (See the 'foo' example above.)
563 -- If we don't shadow, we'll get an ambiguity complaint when we do
564 -- a lookupTopBndrRn (which uses lookupGreLocalRn) on the binder of the 'foo'
566 -- Furthermore, arguably if the splice does define foo, that should hide
567 -- any foo's further out
569 -- The emptyDUs is so that we just collect uses for this group alone
571 { (tcg_env, group') <- rnSrcDecls group
572 -- Discard the tcg_env; it contains only extra info about fixity
573 ; return (DecBr group', allUses (tcg_dus tcg_env)) } }
576 %************************************************************************
578 \subsubsection{@Stmt@s: in @do@ expressions}
580 %************************************************************************
583 rnStmts :: HsStmtContext Name -> [LStmt RdrName]
584 -> RnM (thing, FreeVars)
585 -> RnM (([LStmt Name], thing), FreeVars)
587 rnStmts (MDoExpr _) = rnMDoStmts
588 rnStmts ctxt = rnNormalStmts ctxt
590 rnNormalStmts :: HsStmtContext Name -> [LStmt RdrName]
591 -> RnM (thing, FreeVars)
592 -> RnM (([LStmt Name], thing), FreeVars)
593 -- Used for cases *other* than recursive mdo
594 -- Implements nested scopes
596 rnNormalStmts ctxt [] thing_inside
597 = do { (thing, fvs) <- thing_inside
598 ; return (([],thing), fvs) }
600 rnNormalStmts ctxt (L loc stmt : stmts) thing_inside
601 = do { ((stmt', (stmts', thing)), fvs)
602 <- rnStmt ctxt stmt $
603 rnNormalStmts ctxt stmts thing_inside
604 ; return (((L loc stmt' : stmts'), thing), fvs) }
606 rnStmt :: HsStmtContext Name -> Stmt RdrName
607 -> RnM (thing, FreeVars)
608 -> RnM ((Stmt Name, thing), FreeVars)
610 rnStmt ctxt (ExprStmt expr _ _) thing_inside
611 = do { (expr', fv_expr) <- rnLExpr expr
612 ; (then_op, fvs1) <- lookupSyntaxName thenMName
613 ; (thing, fvs2) <- thing_inside
614 ; return ((ExprStmt expr' then_op placeHolderType, thing),
615 fv_expr `plusFV` fvs1 `plusFV` fvs2) }
617 rnStmt ctxt (BindStmt pat expr _ _) thing_inside
618 = do { (expr', fv_expr) <- rnLExpr expr
619 -- The binders do not scope over the expression
620 ; (bind_op, fvs1) <- lookupSyntaxName bindMName
621 ; (fail_op, fvs2) <- lookupSyntaxName failMName
622 ; rnPatsAndThen (StmtCtxt ctxt) [pat] $ \ [pat'] -> do
623 { (thing, fvs3) <- thing_inside
624 ; return ((BindStmt pat' expr' bind_op fail_op, thing),
625 fv_expr `plusFV` fvs1 `plusFV` fvs2 `plusFV` fvs3) }}
626 -- fv_expr shouldn't really be filtered by the rnPatsAndThen
627 -- but it does not matter because the names are unique
629 rnStmt ctxt (LetStmt binds) thing_inside
630 = do { checkErr (ok ctxt binds)
631 (badIpBinds (ptext SLIT("a parallel list comprehension:")) binds)
632 ; rnLocalBindsAndThen binds $ \ binds' -> do
633 { (thing, fvs) <- thing_inside
634 ; return ((LetStmt binds', thing), fvs) }}
636 -- We do not allow implicit-parameter bindings in a parallel
637 -- list comprehension. I'm not sure what it might mean.
638 ok (ParStmtCtxt _) (HsIPBinds _) = False
641 rnStmt ctxt (RecStmt rec_stmts _ _ _ _) thing_inside
642 = bindLocatedLocalsRn doc (collectLStmtsBinders rec_stmts) $ \ bndrs ->
643 rn_rec_stmts bndrs rec_stmts `thenM` \ segs ->
644 thing_inside `thenM` \ (thing, fvs) ->
646 segs_w_fwd_refs = addFwdRefs segs
647 (ds, us, fs, rec_stmts') = unzip4 segs_w_fwd_refs
648 later_vars = nameSetToList (plusFVs ds `intersectNameSet` fvs)
649 fwd_vars = nameSetToList (plusFVs fs)
651 rec_stmt = RecStmt rec_stmts' later_vars fwd_vars [] emptyLHsBinds
653 returnM ((rec_stmt, thing), uses `plusFV` fvs)
655 doc = text "In a recursive do statement"
657 rnStmt ctxt (ParStmt segs) thing_inside
658 = do { opt_GlasgowExts <- doptM Opt_GlasgowExts
659 ; checkM opt_GlasgowExts parStmtErr
660 ; orig_lcl_env <- getLocalRdrEnv
661 ; ((segs',thing), fvs) <- go orig_lcl_env [] segs
662 ; return ((ParStmt segs', thing), fvs) }
664 -- type ParSeg id = [([LStmt id], [id])]
665 -- go :: NameSet -> [ParSeg RdrName]
666 -- -> RnM (([ParSeg Name], thing), FreeVars)
668 go orig_lcl_env bndrs []
669 = do { let { (bndrs', dups) = removeDups cmpByOcc bndrs
670 ; inner_env = extendLocalRdrEnv orig_lcl_env bndrs' }
672 ; (thing, fvs) <- setLocalRdrEnv inner_env thing_inside
673 ; return (([], thing), fvs) }
675 go orig_lcl_env bndrs_so_far ((stmts, _) : segs)
676 = do { ((stmts', (bndrs, segs', thing)), fvs)
677 <- rnNormalStmts par_ctxt stmts $ do
678 { -- Find the Names that are bound by stmts
679 lcl_env <- getLocalRdrEnv
680 ; let { rdr_bndrs = collectLStmtsBinders stmts
681 ; bndrs = map ( fromJust
682 . lookupLocalRdrEnv lcl_env
684 ; new_bndrs = nub bndrs ++ bndrs_so_far
685 -- The nub is because there might be shadowing
687 -- So we'll look up (Unqual x) twice, getting
688 -- the second binding both times, which is the
691 -- Typecheck the thing inside, passing on all
692 -- the Names bound, but separately; revert the envt
693 ; ((segs', thing), fvs) <- setLocalRdrEnv orig_lcl_env $
694 go orig_lcl_env new_bndrs segs
696 -- Figure out which of the bound names are used
697 ; let used_bndrs = filter (`elemNameSet` fvs) bndrs
698 ; return ((used_bndrs, segs', thing), fvs) }
700 ; let seg' = (stmts', bndrs)
701 ; return (((seg':segs'), thing),
702 delListFromNameSet fvs bndrs) }
704 par_ctxt = ParStmtCtxt ctxt
706 cmpByOcc n1 n2 = nameOccName n1 `compare` nameOccName n2
707 dupErr vs = addErr (ptext SLIT("Duplicate binding in parallel list comprehension for:")
708 <+> quotes (ppr (head vs)))
712 %************************************************************************
714 \subsubsection{mdo expressions}
716 %************************************************************************
719 type FwdRefs = NameSet
720 type Segment stmts = (Defs,
721 Uses, -- May include defs
722 FwdRefs, -- A subset of uses that are
723 -- (a) used before they are bound in this segment, or
724 -- (b) used here, and bound in subsequent segments
725 stmts) -- Either Stmt or [Stmt]
728 ----------------------------------------------------
729 rnMDoStmts :: [LStmt RdrName]
730 -> RnM (thing, FreeVars)
731 -> RnM (([LStmt Name], thing), FreeVars)
732 rnMDoStmts stmts thing_inside
733 = -- Step1: bring all the binders of the mdo into scope
734 -- Remember that this also removes the binders from the
735 -- finally-returned free-vars
736 bindLocatedLocalsRn doc (collectLStmtsBinders stmts) $ \ bndrs ->
738 -- Step 2: Rename each individual stmt, making a
739 -- singleton segment. At this stage the FwdRefs field
740 -- isn't finished: it's empty for all except a BindStmt
741 -- for which it's the fwd refs within the bind itself
742 -- (This set may not be empty, because we're in a recursive
744 segs <- rn_rec_stmts bndrs stmts
746 ; (thing, fvs_later) <- thing_inside
749 -- Step 3: Fill in the fwd refs.
750 -- The segments are all singletons, but their fwd-ref
751 -- field mentions all the things used by the segment
752 -- that are bound after their use
753 segs_w_fwd_refs = addFwdRefs segs
755 -- Step 4: Group together the segments to make bigger segments
756 -- Invariant: in the result, no segment uses a variable
757 -- bound in a later segment
758 grouped_segs = glomSegments segs_w_fwd_refs
760 -- Step 5: Turn the segments into Stmts
761 -- Use RecStmt when and only when there are fwd refs
762 -- Also gather up the uses from the end towards the
763 -- start, so we can tell the RecStmt which things are
764 -- used 'after' the RecStmt
765 (stmts', fvs) = segsToStmts grouped_segs fvs_later
767 ; return ((stmts', thing), fvs) }
769 doc = text "In a recursive mdo-expression"
771 ---------------------------------------------
772 rn_rec_stmts :: [Name] -> [LStmt RdrName] -> RnM [Segment (LStmt Name)]
773 rn_rec_stmts bndrs stmts = mappM (rn_rec_stmt bndrs) stmts `thenM` \ segs_s ->
774 returnM (concat segs_s)
776 ----------------------------------------------------
777 rn_rec_stmt :: [Name] -> LStmt RdrName -> RnM [Segment (LStmt Name)]
778 -- Rename a Stmt that is inside a RecStmt (or mdo)
779 -- Assumes all binders are already in scope
780 -- Turns each stmt into a singleton Stmt
782 rn_rec_stmt all_bndrs (L loc (ExprStmt expr _ _))
783 = rnLExpr expr `thenM` \ (expr', fvs) ->
784 lookupSyntaxName thenMName `thenM` \ (then_op, fvs1) ->
785 returnM [(emptyNameSet, fvs `plusFV` fvs1, emptyNameSet,
786 L loc (ExprStmt expr' then_op placeHolderType))]
788 rn_rec_stmt all_bndrs (L loc (BindStmt pat expr _ _))
789 = rnLExpr expr `thenM` \ (expr', fv_expr) ->
790 rnLPat pat `thenM` \ (pat', fv_pat) ->
791 lookupSyntaxName bindMName `thenM` \ (bind_op, fvs1) ->
792 lookupSyntaxName failMName `thenM` \ (fail_op, fvs2) ->
794 bndrs = mkNameSet (collectPatBinders pat')
795 fvs = fv_expr `plusFV` fv_pat `plusFV` fvs1 `plusFV` fvs2
797 returnM [(bndrs, fvs, bndrs `intersectNameSet` fvs,
798 L loc (BindStmt pat' expr' bind_op fail_op))]
800 rn_rec_stmt all_bndrs (L loc (LetStmt binds@(HsIPBinds _)))
801 = do { addErr (badIpBinds (ptext SLIT("an mdo expression")) binds)
804 rn_rec_stmt all_bndrs (L loc (LetStmt (HsValBinds binds)))
805 = rnValBinds (trimWith all_bndrs) binds `thenM` \ (binds', du_binds) ->
806 returnM [(duDefs du_binds, duUses du_binds,
807 emptyNameSet, L loc (LetStmt (HsValBinds binds')))]
809 rn_rec_stmt all_bndrs (L loc (RecStmt stmts _ _ _ _)) -- Flatten Rec inside Rec
810 = rn_rec_stmts all_bndrs stmts
812 rn_rec_stmt all_bndrs stmt@(L _ (ParStmt _)) -- Syntactically illegal in mdo
813 = pprPanic "rn_rec_stmt" (ppr stmt)
815 ---------------------------------------------
816 addFwdRefs :: [Segment a] -> [Segment a]
817 -- So far the segments only have forward refs *within* the Stmt
818 -- (which happens for bind: x <- ...x...)
819 -- This function adds the cross-seg fwd ref info
822 = fst (foldr mk_seg ([], emptyNameSet) pairs)
824 mk_seg (defs, uses, fwds, stmts) (segs, later_defs)
825 = (new_seg : segs, all_defs)
827 new_seg = (defs, uses, new_fwds, stmts)
828 all_defs = later_defs `unionNameSets` defs
829 new_fwds = fwds `unionNameSets` (uses `intersectNameSet` later_defs)
830 -- Add the downstream fwd refs here
832 ----------------------------------------------------
833 -- Glomming the singleton segments of an mdo into
834 -- minimal recursive groups.
836 -- At first I thought this was just strongly connected components, but
837 -- there's an important constraint: the order of the stmts must not change.
840 -- mdo { x <- ...y...
847 -- Here, the first stmt mention 'y', which is bound in the third.
848 -- But that means that the innocent second stmt (p <- z) gets caught
849 -- up in the recursion. And that in turn means that the binding for
850 -- 'z' has to be included... and so on.
852 -- Start at the tail { r <- x }
853 -- Now add the next one { z <- y ; r <- x }
854 -- Now add one more { q <- x ; z <- y ; r <- x }
855 -- Now one more... but this time we have to group a bunch into rec
856 -- { rec { y <- ...x... ; q <- x ; z <- y } ; r <- x }
857 -- Now one more, which we can add on without a rec
859 -- rec { y <- ...x... ; q <- x ; z <- y } ;
861 -- Finally we add the last one; since it mentions y we have to
862 -- glom it togeher with the first two groups
863 -- { rec { x <- ...y...; p <- z ; y <- ...x... ;
864 -- q <- x ; z <- y } ;
867 glomSegments :: [Segment (LStmt Name)] -> [Segment [LStmt Name]]
870 glomSegments ((defs,uses,fwds,stmt) : segs)
871 -- Actually stmts will always be a singleton
872 = (seg_defs, seg_uses, seg_fwds, seg_stmts) : others
874 segs' = glomSegments segs
875 (extras, others) = grab uses segs'
876 (ds, us, fs, ss) = unzip4 extras
878 seg_defs = plusFVs ds `plusFV` defs
879 seg_uses = plusFVs us `plusFV` uses
880 seg_fwds = plusFVs fs `plusFV` fwds
881 seg_stmts = stmt : concat ss
883 grab :: NameSet -- The client
885 -> ([Segment a], -- Needed by the 'client'
886 [Segment a]) -- Not needed by the client
887 -- The result is simply a split of the input
889 = (reverse yeses, reverse noes)
891 (noes, yeses) = span not_needed (reverse dus)
892 not_needed (defs,_,_,_) = not (intersectsNameSet defs uses)
895 ----------------------------------------------------
896 segsToStmts :: [Segment [LStmt Name]]
897 -> FreeVars -- Free vars used 'later'
898 -> ([LStmt Name], FreeVars)
900 segsToStmts [] fvs_later = ([], fvs_later)
901 segsToStmts ((defs, uses, fwds, ss) : segs) fvs_later
902 = ASSERT( not (null ss) )
903 (new_stmt : later_stmts, later_uses `plusFV` uses)
905 (later_stmts, later_uses) = segsToStmts segs fvs_later
906 new_stmt | non_rec = head ss
907 | otherwise = L (getLoc (head ss)) $
908 RecStmt ss (nameSetToList used_later) (nameSetToList fwds)
911 non_rec = isSingleton ss && isEmptyNameSet fwds
912 used_later = defs `intersectNameSet` later_uses
913 -- The ones needed after the RecStmt
916 %************************************************************************
918 \subsubsection{Assertion utils}
920 %************************************************************************
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)) (L sloc (HsLit msg))
929 msg = HsStringPrim (mkFastString (showSDoc (ppr 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 -fglasgow-exts"))
947 badIpBinds what binds
948 = hang (ptext SLIT("Implicit-parameter bindings illegal in") <+> what)