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 #if defined(GHCI) && defined(BREAKPOINT)
37 import PrelNames ( breakpointJumpName, undefined_RDR, breakpointIdKey )
38 import UniqFM ( eltsUFM )
39 import DynFlags ( GhcMode(..) )
40 import SrcLoc ( srcSpanFile, srcSpanStartLine )
41 import Name ( isTyVarName )
43 import Name ( Name, nameOccName, nameIsLocalOrFrom )
45 import RdrName ( RdrName, emptyGlobalRdrEnv, extendLocalRdrEnv, lookupLocalRdrEnv )
46 import LoadIface ( loadHomeInterface )
47 import UniqFM ( isNullUFM )
48 import UniqSet ( emptyUniqSet )
50 import Util ( isSingleton )
51 import ListSetOps ( removeDups )
52 import Maybes ( expectJust )
54 import SrcLoc ( Located(..), unLoc, getLoc, cmpLocated )
57 import List ( unzip4 )
61 %************************************************************************
63 \subsubsection{Expressions}
65 %************************************************************************
68 rnExprs :: [LHsExpr RdrName] -> RnM ([LHsExpr Name], FreeVars)
69 rnExprs ls = rnExprs' ls emptyUniqSet
71 rnExprs' [] acc = returnM ([], acc)
72 rnExprs' (expr:exprs) acc
73 = rnLExpr expr `thenM` \ (expr', fvExpr) ->
75 -- Now we do a "seq" on the free vars because typically it's small
76 -- or empty, especially in very long lists of constants
78 acc' = acc `plusFV` fvExpr
80 (grubby_seqNameSet acc' rnExprs') exprs acc' `thenM` \ (exprs', fvExprs) ->
81 returnM (expr':exprs', fvExprs)
83 -- Grubby little function to do "seq" on namesets; replace by proper seq when GHC can do seq
84 grubby_seqNameSet ns result | isNullUFM ns = result
88 Variables. We look up the variable and return the resulting name.
91 rnLExpr :: LHsExpr RdrName -> RnM (LHsExpr Name, FreeVars)
92 rnLExpr = wrapLocFstM rnExpr
94 rnExpr :: HsExpr RdrName -> RnM (HsExpr Name, FreeVars)
97 = do name <- lookupOccRn v
98 localRdrEnv <- getLocalRdrEnv
100 ignore_asserts <- doptM Opt_IgnoreAsserts
101 ignore_breakpoints <- doptM Opt_IgnoreBreakpoints
102 let conds = [ (name `hasKey` assertIdKey
103 && not ignore_asserts,
104 do (e, fvs) <- mkAssertErrorExpr
105 return (e, fvs `addOneFV` name))
106 #if defined(GHCI) && defined(BREAKPOINT)
107 , (name `hasKey` breakpointIdKey
108 && not ignore_breakpoints,
109 do ghcMode <- getGhcMode
112 -> do let isWantedName = not.isTyVarName
113 (e, fvs) <- mkBreakPointExpr (filter isWantedName (eltsUFM localRdrEnv))
114 return (e, fvs `addOneFV` name)
115 _ -> return (HsVar name, unitFV name)
119 case lookup True conds of
120 Just action -> action
121 Nothing -> return (HsVar name, unitFV name)
124 = newIPNameRn v `thenM` \ name ->
125 returnM (HsIPVar name, emptyFVs)
129 returnM (HsLit lit, emptyFVs)
131 rnExpr (HsOverLit lit)
132 = rnOverLit lit `thenM` \ (lit', fvs) ->
133 returnM (HsOverLit lit', fvs)
135 rnExpr (HsApp fun arg)
136 = rnLExpr fun `thenM` \ (fun',fvFun) ->
137 rnLExpr arg `thenM` \ (arg',fvArg) ->
138 returnM (HsApp fun' arg', fvFun `plusFV` fvArg)
140 rnExpr (OpApp e1 op _ e2)
141 = rnLExpr e1 `thenM` \ (e1', fv_e1) ->
142 rnLExpr e2 `thenM` \ (e2', fv_e2) ->
143 rnLExpr op `thenM` \ (op'@(L _ (HsVar op_name)), fv_op) ->
146 -- When renaming code synthesised from "deriving" declarations
147 -- we used to avoid fixity stuff, but we can't easily tell any
148 -- more, so I've removed the test. Adding HsPars in TcGenDeriv
149 -- should prevent bad things happening.
150 lookupFixityRn op_name `thenM` \ fixity ->
151 mkOpAppRn e1' op' fixity e2' `thenM` \ final_e ->
154 fv_e1 `plusFV` fv_op `plusFV` fv_e2)
157 = rnLExpr e `thenM` \ (e', fv_e) ->
158 lookupSyntaxName negateName `thenM` \ (neg_name, fv_neg) ->
159 mkNegAppRn e' neg_name `thenM` \ final_e ->
160 returnM (final_e, fv_e `plusFV` fv_neg)
163 = rnLExpr e `thenM` \ (e', fvs_e) ->
164 returnM (HsPar e', fvs_e)
166 -- Template Haskell extensions
167 -- Don't ifdef-GHCI them because we want to fail gracefully
168 -- (not with an rnExpr crash) in a stage-1 compiler.
169 rnExpr e@(HsBracket br_body)
170 = checkTH e "bracket" `thenM_`
171 rnBracket br_body `thenM` \ (body', fvs_e) ->
172 returnM (HsBracket body', fvs_e)
174 rnExpr e@(HsSpliceE splice)
175 = rnSplice splice `thenM` \ (splice', fvs) ->
176 returnM (HsSpliceE splice', fvs)
178 rnExpr section@(SectionL expr op)
179 = rnLExpr expr `thenM` \ (expr', fvs_expr) ->
180 rnLExpr op `thenM` \ (op', fvs_op) ->
181 checkSectionPrec InfixL section op' expr' `thenM_`
182 returnM (SectionL expr' op', fvs_op `plusFV` fvs_expr)
184 rnExpr section@(SectionR op expr)
185 = rnLExpr op `thenM` \ (op', fvs_op) ->
186 rnLExpr expr `thenM` \ (expr', fvs_expr) ->
187 checkSectionPrec InfixR section op' expr' `thenM_`
188 returnM (SectionR op' expr', fvs_op `plusFV` fvs_expr)
190 rnExpr (HsCoreAnn ann expr)
191 = rnLExpr expr `thenM` \ (expr', fvs_expr) ->
192 returnM (HsCoreAnn ann expr', fvs_expr)
194 rnExpr (HsSCC lbl expr)
195 = rnLExpr expr `thenM` \ (expr', fvs_expr) ->
196 returnM (HsSCC lbl expr', fvs_expr)
198 rnExpr (HsLam matches)
199 = rnMatchGroup LambdaExpr matches `thenM` \ (matches', fvMatch) ->
200 returnM (HsLam matches', fvMatch)
202 rnExpr (HsCase expr matches)
203 = rnLExpr expr `thenM` \ (new_expr, e_fvs) ->
204 rnMatchGroup CaseAlt matches `thenM` \ (new_matches, ms_fvs) ->
205 returnM (HsCase new_expr new_matches, e_fvs `plusFV` ms_fvs)
207 rnExpr (HsLet binds expr)
208 = rnLocalBindsAndThen binds $ \ binds' ->
209 rnLExpr expr `thenM` \ (expr',fvExpr) ->
210 returnM (HsLet binds' expr', fvExpr)
212 rnExpr e@(HsDo do_or_lc stmts body _)
213 = do { ((stmts', body'), fvs) <- rnStmts do_or_lc stmts $
215 ; return (HsDo do_or_lc stmts' body' placeHolderType, fvs) }
217 rnExpr (ExplicitList _ exps)
218 = rnExprs exps `thenM` \ (exps', fvs) ->
219 returnM (ExplicitList placeHolderType exps', fvs `addOneFV` listTyCon_name)
221 rnExpr (ExplicitPArr _ exps)
222 = rnExprs exps `thenM` \ (exps', fvs) ->
223 returnM (ExplicitPArr placeHolderType exps', fvs)
225 rnExpr e@(ExplicitTuple exps boxity)
226 = checkTupSize tup_size `thenM_`
227 rnExprs exps `thenM` \ (exps', fvs) ->
228 returnM (ExplicitTuple exps' boxity, fvs `addOneFV` tycon_name)
230 tup_size = length exps
231 tycon_name = tupleTyCon_name boxity tup_size
233 rnExpr (RecordCon con_id _ rbinds)
234 = lookupLocatedOccRn con_id `thenM` \ conname ->
235 rnRbinds "construction" rbinds `thenM` \ (rbinds', fvRbinds) ->
236 returnM (RecordCon conname noPostTcExpr rbinds',
237 fvRbinds `addOneFV` unLoc conname)
239 rnExpr (RecordUpd expr rbinds _ _)
240 = rnLExpr expr `thenM` \ (expr', fvExpr) ->
241 rnRbinds "update" rbinds `thenM` \ (rbinds', fvRbinds) ->
242 returnM (RecordUpd expr' rbinds' placeHolderType placeHolderType,
243 fvExpr `plusFV` fvRbinds)
245 rnExpr (ExprWithTySig expr pty)
246 = rnLExpr expr `thenM` \ (expr', fvExpr) ->
247 rnHsTypeFVs doc pty `thenM` \ (pty', fvTy) ->
248 returnM (ExprWithTySig expr' pty', fvExpr `plusFV` fvTy)
250 doc = text "In an expression type signature"
252 rnExpr (HsIf p b1 b2)
253 = rnLExpr p `thenM` \ (p', fvP) ->
254 rnLExpr b1 `thenM` \ (b1', fvB1) ->
255 rnLExpr b2 `thenM` \ (b2', fvB2) ->
256 returnM (HsIf p' b1' b2', plusFVs [fvP, fvB1, fvB2])
259 = rnHsTypeFVs doc a `thenM` \ (t, fvT) ->
260 returnM (HsType t, fvT)
262 doc = text "In a type argument"
264 rnExpr (ArithSeq _ seq)
265 = rnArithSeq seq `thenM` \ (new_seq, fvs) ->
266 returnM (ArithSeq noPostTcExpr new_seq, fvs)
268 rnExpr (PArrSeq _ seq)
269 = rnArithSeq seq `thenM` \ (new_seq, fvs) ->
270 returnM (PArrSeq noPostTcExpr new_seq, fvs)
273 These three are pattern syntax appearing in expressions.
274 Since all the symbols are reservedops we can simply reject them.
275 We return a (bogus) EWildPat in each case.
278 rnExpr e@EWildPat = patSynErr e
279 rnExpr e@(EAsPat {}) = patSynErr e
280 rnExpr e@(ELazyPat {}) = patSynErr e
283 %************************************************************************
287 %************************************************************************
290 rnExpr (HsProc pat body)
292 rnPatsAndThen ProcExpr [pat] $ \ [pat'] ->
293 rnCmdTop body `thenM` \ (body',fvBody) ->
294 returnM (HsProc pat' body', fvBody)
296 rnExpr (HsArrApp arrow arg _ ho rtl)
297 = select_arrow_scope (rnLExpr arrow) `thenM` \ (arrow',fvArrow) ->
298 rnLExpr arg `thenM` \ (arg',fvArg) ->
299 returnM (HsArrApp arrow' arg' placeHolderType ho rtl,
300 fvArrow `plusFV` fvArg)
302 select_arrow_scope tc = case ho of
303 HsHigherOrderApp -> tc
304 HsFirstOrderApp -> escapeArrowScope tc
307 rnExpr (HsArrForm op (Just _) [arg1, arg2])
308 = escapeArrowScope (rnLExpr op)
309 `thenM` \ (op'@(L _ (HsVar op_name)),fv_op) ->
310 rnCmdTop arg1 `thenM` \ (arg1',fv_arg1) ->
311 rnCmdTop arg2 `thenM` \ (arg2',fv_arg2) ->
315 lookupFixityRn op_name `thenM` \ fixity ->
316 mkOpFormRn arg1' op' fixity arg2' `thenM` \ final_e ->
319 fv_arg1 `plusFV` fv_op `plusFV` fv_arg2)
321 rnExpr (HsArrForm op fixity cmds)
322 = escapeArrowScope (rnLExpr op) `thenM` \ (op',fvOp) ->
323 rnCmdArgs cmds `thenM` \ (cmds',fvCmds) ->
324 returnM (HsArrForm op' fixity cmds', fvOp `plusFV` fvCmds)
326 rnExpr other = pprPanic "rnExpr: unexpected expression" (ppr other)
327 -- DictApp, DictLam, TyApp, TyLam
331 %************************************************************************
335 %************************************************************************
338 rnCmdArgs [] = returnM ([], emptyFVs)
340 = rnCmdTop arg `thenM` \ (arg',fvArg) ->
341 rnCmdArgs args `thenM` \ (args',fvArgs) ->
342 returnM (arg':args', fvArg `plusFV` fvArgs)
345 rnCmdTop = wrapLocFstM rnCmdTop'
347 rnCmdTop' (HsCmdTop cmd _ _ _)
348 = rnLExpr (convertOpFormsLCmd cmd) `thenM` \ (cmd', fvCmd) ->
350 cmd_names = [arrAName, composeAName, firstAName] ++
351 nameSetToList (methodNamesCmd (unLoc cmd'))
353 -- Generate the rebindable syntax for the monad
354 lookupSyntaxTable cmd_names `thenM` \ (cmd_names', cmd_fvs) ->
356 returnM (HsCmdTop cmd' [] placeHolderType cmd_names',
357 fvCmd `plusFV` cmd_fvs)
359 ---------------------------------------------------
360 -- convert OpApp's in a command context to HsArrForm's
362 convertOpFormsLCmd :: LHsCmd id -> LHsCmd id
363 convertOpFormsLCmd = fmap convertOpFormsCmd
365 convertOpFormsCmd :: HsCmd id -> HsCmd id
367 convertOpFormsCmd (HsApp c e) = HsApp (convertOpFormsLCmd c) e
368 convertOpFormsCmd (HsLam match) = HsLam (convertOpFormsMatch match)
369 convertOpFormsCmd (OpApp c1 op fixity c2)
371 arg1 = L (getLoc c1) $ HsCmdTop (convertOpFormsLCmd c1) [] placeHolderType []
372 arg2 = L (getLoc c2) $ HsCmdTop (convertOpFormsLCmd c2) [] placeHolderType []
374 HsArrForm op (Just fixity) [arg1, arg2]
376 convertOpFormsCmd (HsPar c) = HsPar (convertOpFormsLCmd c)
379 convertOpFormsCmd (HsCase exp matches)
380 = HsCase exp (convertOpFormsMatch matches)
382 convertOpFormsCmd (HsIf exp c1 c2)
383 = HsIf exp (convertOpFormsLCmd c1) (convertOpFormsLCmd c2)
385 convertOpFormsCmd (HsLet binds cmd)
386 = HsLet binds (convertOpFormsLCmd cmd)
388 convertOpFormsCmd (HsDo ctxt stmts body ty)
389 = HsDo ctxt (map (fmap convertOpFormsStmt) stmts)
390 (convertOpFormsLCmd body) ty
392 -- Anything else is unchanged. This includes HsArrForm (already done),
393 -- things with no sub-commands, and illegal commands (which will be
394 -- caught by the type checker)
395 convertOpFormsCmd c = c
397 convertOpFormsStmt (BindStmt pat cmd _ _)
398 = BindStmt pat (convertOpFormsLCmd cmd) noSyntaxExpr noSyntaxExpr
399 convertOpFormsStmt (ExprStmt cmd _ _)
400 = ExprStmt (convertOpFormsLCmd cmd) noSyntaxExpr placeHolderType
401 convertOpFormsStmt (RecStmt stmts lvs rvs es binds)
402 = RecStmt (map (fmap convertOpFormsStmt) stmts) lvs rvs es binds
403 convertOpFormsStmt stmt = stmt
405 convertOpFormsMatch (MatchGroup ms ty)
406 = MatchGroup (map (fmap convert) ms) ty
407 where convert (Match pat mty grhss)
408 = Match pat mty (convertOpFormsGRHSs grhss)
410 convertOpFormsGRHSs (GRHSs grhss binds)
411 = GRHSs (map convertOpFormsGRHS grhss) binds
413 convertOpFormsGRHS = fmap convert
415 convert (GRHS stmts cmd) = GRHS stmts (convertOpFormsLCmd cmd)
417 ---------------------------------------------------
418 type CmdNeeds = FreeVars -- Only inhabitants are
419 -- appAName, choiceAName, loopAName
421 -- find what methods the Cmd needs (loop, choice, apply)
422 methodNamesLCmd :: LHsCmd Name -> CmdNeeds
423 methodNamesLCmd = methodNamesCmd . unLoc
425 methodNamesCmd :: HsCmd Name -> CmdNeeds
427 methodNamesCmd cmd@(HsArrApp _arrow _arg _ HsFirstOrderApp _rtl)
429 methodNamesCmd cmd@(HsArrApp _arrow _arg _ HsHigherOrderApp _rtl)
431 methodNamesCmd cmd@(HsArrForm {}) = emptyFVs
433 methodNamesCmd (HsPar c) = methodNamesLCmd c
435 methodNamesCmd (HsIf p c1 c2)
436 = methodNamesLCmd c1 `plusFV` methodNamesLCmd c2 `addOneFV` choiceAName
438 methodNamesCmd (HsLet b c) = methodNamesLCmd c
440 methodNamesCmd (HsDo sc stmts body ty)
441 = methodNamesStmts stmts `plusFV` methodNamesLCmd body
443 methodNamesCmd (HsApp c e) = methodNamesLCmd c
445 methodNamesCmd (HsLam match) = methodNamesMatch match
447 methodNamesCmd (HsCase scrut matches)
448 = methodNamesMatch matches `addOneFV` choiceAName
450 methodNamesCmd other = emptyFVs
451 -- Other forms can't occur in commands, but it's not convenient
452 -- to error here so we just do what's convenient.
453 -- The type checker will complain later
455 ---------------------------------------------------
456 methodNamesMatch (MatchGroup ms ty)
457 = plusFVs (map do_one ms)
459 do_one (L _ (Match pats sig_ty grhss)) = methodNamesGRHSs grhss
461 -------------------------------------------------
463 methodNamesGRHSs (GRHSs grhss binds) = plusFVs (map methodNamesGRHS grhss)
465 -------------------------------------------------
466 methodNamesGRHS (L _ (GRHS stmts rhs)) = methodNamesLCmd rhs
468 ---------------------------------------------------
469 methodNamesStmts stmts = plusFVs (map methodNamesLStmt stmts)
471 ---------------------------------------------------
472 methodNamesLStmt = methodNamesStmt . unLoc
474 methodNamesStmt (ExprStmt cmd _ _) = methodNamesLCmd cmd
475 methodNamesStmt (BindStmt pat cmd _ _) = methodNamesLCmd cmd
476 methodNamesStmt (RecStmt stmts _ _ _ _)
477 = methodNamesStmts stmts `addOneFV` loopAName
478 methodNamesStmt (LetStmt b) = emptyFVs
479 methodNamesStmt (ParStmt ss) = emptyFVs
480 -- ParStmt can't occur in commands, but it's not convenient to error
481 -- here so we just do what's convenient
485 %************************************************************************
489 %************************************************************************
492 rnArithSeq (From expr)
493 = rnLExpr expr `thenM` \ (expr', fvExpr) ->
494 returnM (From expr', fvExpr)
496 rnArithSeq (FromThen expr1 expr2)
497 = rnLExpr expr1 `thenM` \ (expr1', fvExpr1) ->
498 rnLExpr expr2 `thenM` \ (expr2', fvExpr2) ->
499 returnM (FromThen expr1' expr2', fvExpr1 `plusFV` fvExpr2)
501 rnArithSeq (FromTo expr1 expr2)
502 = rnLExpr expr1 `thenM` \ (expr1', fvExpr1) ->
503 rnLExpr expr2 `thenM` \ (expr2', fvExpr2) ->
504 returnM (FromTo expr1' expr2', fvExpr1 `plusFV` fvExpr2)
506 rnArithSeq (FromThenTo expr1 expr2 expr3)
507 = rnLExpr expr1 `thenM` \ (expr1', fvExpr1) ->
508 rnLExpr expr2 `thenM` \ (expr2', fvExpr2) ->
509 rnLExpr expr3 `thenM` \ (expr3', fvExpr3) ->
510 returnM (FromThenTo expr1' expr2' expr3',
511 plusFVs [fvExpr1, fvExpr2, fvExpr3])
515 %************************************************************************
517 \subsubsection{@Rbinds@s and @Rpats@s: in record expressions}
519 %************************************************************************
523 = mappM_ field_dup_err dup_fields `thenM_`
524 mapFvRn rn_rbind rbinds `thenM` \ (rbinds', fvRbind) ->
525 returnM (rbinds', fvRbind)
527 (_, dup_fields) = removeDups cmpLocated [ f | (f,_) <- rbinds ]
529 field_dup_err dups = mappM_ (\f -> addLocErr f (dupFieldErr str)) dups
531 rn_rbind (field, expr)
532 = lookupLocatedGlobalOccRn field `thenM` \ fieldname ->
533 rnLExpr expr `thenM` \ (expr', fvExpr) ->
534 returnM ((fieldname, expr'), fvExpr `addOneFV` unLoc fieldname)
537 %************************************************************************
539 Template Haskell brackets
541 %************************************************************************
544 rnBracket (VarBr n) = do { name <- lookupOccRn n
545 ; this_mod <- getModule
546 ; checkM (nameIsLocalOrFrom this_mod name) $ -- Reason: deprecation checking asumes the
547 do { loadHomeInterface msg name -- home interface is loaded, and this is the
548 ; return () } -- only way that is going to happen
549 ; returnM (VarBr name, unitFV name) }
551 msg = ptext SLIT("Need interface for Template Haskell quoted Name")
553 rnBracket (ExpBr e) = do { (e', fvs) <- rnLExpr e
554 ; return (ExpBr e', fvs) }
555 rnBracket (PatBr p) = do { (p', fvs) <- rnLPat p
556 ; return (PatBr p', fvs) }
557 rnBracket (TypBr t) = do { (t', fvs) <- rnHsTypeFVs doc t
558 ; return (TypBr t', fvs) }
560 doc = ptext SLIT("In a Template-Haskell quoted type")
561 rnBracket (DecBr group)
562 = do { gbl_env <- getGblEnv
564 ; let gbl_env1 = gbl_env { tcg_mod = thFAKE }
565 -- Note the thFAKE. The top-level names from the bracketed
566 -- declarations will go into the name cache, and we don't want them to
567 -- confuse the Names for the current module.
568 -- By using a pretend module, thFAKE, we keep them safely out of the way.
570 ; names <- getLocalDeclBinders gbl_env1 group
571 ; rdr_env' <- extendRdrEnvRn emptyGlobalRdrEnv names
572 -- Furthermore, the names in the bracket shouldn't conflict with
573 -- existing top-level names E.g.
575 -- bar = [d| foo = 1|]
576 -- But both 'foo's get a LocalDef provenance, so we'd get a complaint unless
577 -- we start with an emptyGlobalRdrEnv
579 ; setGblEnv (gbl_env { tcg_rdr_env = tcg_rdr_env gbl_env1 `plusOccEnv` rdr_env',
580 tcg_dus = emptyDUs }) $ do
581 -- Notice plusOccEnv, not plusGlobalRdrEnv. In this situation we want
582 -- to *shadow* top-level bindings. (See the 'foo' example above.)
583 -- If we don't shadow, we'll get an ambiguity complaint when we do
584 -- a lookupTopBndrRn (which uses lookupGreLocalRn) on the binder of the 'foo'
586 -- Furthermore, arguably if the splice does define foo, that should hide
587 -- any foo's further out
589 -- The emptyDUs is so that we just collect uses for this group alone
591 { (tcg_env, group') <- rnSrcDecls group
592 -- Discard the tcg_env; it contains only extra info about fixity
593 ; return (DecBr group', allUses (tcg_dus tcg_env)) } }
596 %************************************************************************
598 \subsubsection{@Stmt@s: in @do@ expressions}
600 %************************************************************************
603 rnStmts :: HsStmtContext Name -> [LStmt RdrName]
604 -> RnM (thing, FreeVars)
605 -> RnM (([LStmt Name], thing), FreeVars)
607 rnStmts (MDoExpr _) = rnMDoStmts
608 rnStmts ctxt = rnNormalStmts ctxt
610 rnNormalStmts :: HsStmtContext Name -> [LStmt RdrName]
611 -> RnM (thing, FreeVars)
612 -> RnM (([LStmt Name], thing), FreeVars)
613 -- Used for cases *other* than recursive mdo
614 -- Implements nested scopes
616 rnNormalStmts ctxt [] thing_inside
617 = do { (thing, fvs) <- thing_inside
618 ; return (([],thing), fvs) }
620 rnNormalStmts ctxt (L loc stmt : stmts) thing_inside
621 = do { ((stmt', (stmts', thing)), fvs)
622 <- rnStmt ctxt stmt $
623 rnNormalStmts ctxt stmts thing_inside
624 ; return (((L loc stmt' : stmts'), thing), fvs) }
626 rnStmt :: HsStmtContext Name -> Stmt RdrName
627 -> RnM (thing, FreeVars)
628 -> RnM ((Stmt Name, thing), FreeVars)
630 rnStmt ctxt (ExprStmt expr _ _) thing_inside
631 = do { (expr', fv_expr) <- rnLExpr expr
632 ; (then_op, fvs1) <- lookupSyntaxName thenMName
633 ; (thing, fvs2) <- thing_inside
634 ; return ((ExprStmt expr' then_op placeHolderType, thing),
635 fv_expr `plusFV` fvs1 `plusFV` fvs2) }
637 rnStmt ctxt (BindStmt pat expr _ _) thing_inside
638 = do { (expr', fv_expr) <- rnLExpr expr
639 -- The binders do not scope over the expression
640 ; (bind_op, fvs1) <- lookupSyntaxName bindMName
641 ; (fail_op, fvs2) <- lookupSyntaxName failMName
642 ; rnPatsAndThen (StmtCtxt ctxt) [pat] $ \ [pat'] -> do
643 { (thing, fvs3) <- thing_inside
644 ; return ((BindStmt pat' expr' bind_op fail_op, thing),
645 fv_expr `plusFV` fvs1 `plusFV` fvs2 `plusFV` fvs3) }}
646 -- fv_expr shouldn't really be filtered by the rnPatsAndThen
647 -- but it does not matter because the names are unique
649 rnStmt ctxt (LetStmt binds) thing_inside
650 = do { checkErr (ok ctxt binds)
651 (badIpBinds (ptext SLIT("a parallel list comprehension:")) binds)
652 ; rnLocalBindsAndThen binds $ \ binds' -> do
653 { (thing, fvs) <- thing_inside
654 ; return ((LetStmt binds', thing), fvs) }}
656 -- We do not allow implicit-parameter bindings in a parallel
657 -- list comprehension. I'm not sure what it might mean.
658 ok (ParStmtCtxt _) (HsIPBinds _) = False
661 rnStmt ctxt (RecStmt rec_stmts _ _ _ _) thing_inside
662 = bindLocatedLocalsRn doc (collectLStmtsBinders rec_stmts) $ \ bndrs ->
663 rn_rec_stmts bndrs rec_stmts `thenM` \ segs ->
664 thing_inside `thenM` \ (thing, fvs) ->
666 segs_w_fwd_refs = addFwdRefs segs
667 (ds, us, fs, rec_stmts') = unzip4 segs_w_fwd_refs
668 later_vars = nameSetToList (plusFVs ds `intersectNameSet` fvs)
669 fwd_vars = nameSetToList (plusFVs fs)
671 rec_stmt = RecStmt rec_stmts' later_vars fwd_vars [] emptyLHsBinds
673 returnM ((rec_stmt, thing), uses `plusFV` fvs)
675 doc = text "In a recursive do statement"
677 rnStmt ctxt (ParStmt segs) thing_inside
678 = do { opt_GlasgowExts <- doptM Opt_GlasgowExts
679 ; checkM opt_GlasgowExts parStmtErr
680 ; orig_lcl_env <- getLocalRdrEnv
681 ; ((segs',thing), fvs) <- go orig_lcl_env [] segs
682 ; return ((ParStmt segs', thing), fvs) }
684 -- type ParSeg id = [([LStmt id], [id])]
685 -- go :: NameSet -> [ParSeg RdrName]
686 -- -> RnM (([ParSeg Name], thing), FreeVars)
688 go orig_lcl_env bndrs []
689 = do { let { (bndrs', dups) = removeDups cmpByOcc bndrs
690 ; inner_env = extendLocalRdrEnv orig_lcl_env bndrs' }
692 ; (thing, fvs) <- setLocalRdrEnv inner_env thing_inside
693 ; return (([], thing), fvs) }
695 go orig_lcl_env bndrs_so_far ((stmts, _) : segs)
696 = do { ((stmts', (bndrs, segs', thing)), fvs)
697 <- rnNormalStmts par_ctxt stmts $ do
698 { -- Find the Names that are bound by stmts
699 lcl_env <- getLocalRdrEnv
700 ; let { rdr_bndrs = collectLStmtsBinders stmts
701 ; bndrs = map ( expectJust "rnStmt"
702 . lookupLocalRdrEnv lcl_env
704 ; new_bndrs = nub bndrs ++ bndrs_so_far
705 -- The nub is because there might be shadowing
707 -- So we'll look up (Unqual x) twice, getting
708 -- the second binding both times, which is the
711 -- Typecheck the thing inside, passing on all
712 -- the Names bound, but separately; revert the envt
713 ; ((segs', thing), fvs) <- setLocalRdrEnv orig_lcl_env $
714 go orig_lcl_env new_bndrs segs
716 -- Figure out which of the bound names are used
717 ; let used_bndrs = filter (`elemNameSet` fvs) bndrs
718 ; return ((used_bndrs, segs', thing), fvs) }
720 ; let seg' = (stmts', bndrs)
721 ; return (((seg':segs'), thing),
722 delListFromNameSet fvs bndrs) }
724 par_ctxt = ParStmtCtxt ctxt
726 cmpByOcc n1 n2 = nameOccName n1 `compare` nameOccName n2
727 dupErr vs = addErr (ptext SLIT("Duplicate binding in parallel list comprehension for:")
728 <+> quotes (ppr (head vs)))
732 %************************************************************************
734 \subsubsection{mdo expressions}
736 %************************************************************************
739 type FwdRefs = NameSet
740 type Segment stmts = (Defs,
741 Uses, -- May include defs
742 FwdRefs, -- A subset of uses that are
743 -- (a) used before they are bound in this segment, or
744 -- (b) used here, and bound in subsequent segments
745 stmts) -- Either Stmt or [Stmt]
748 ----------------------------------------------------
749 rnMDoStmts :: [LStmt RdrName]
750 -> RnM (thing, FreeVars)
751 -> RnM (([LStmt Name], thing), FreeVars)
752 rnMDoStmts stmts thing_inside
753 = -- Step1: bring all the binders of the mdo into scope
754 -- Remember that this also removes the binders from the
755 -- finally-returned free-vars
756 bindLocatedLocalsRn doc (collectLStmtsBinders stmts) $ \ bndrs ->
758 -- Step 2: Rename each individual stmt, making a
759 -- singleton segment. At this stage the FwdRefs field
760 -- isn't finished: it's empty for all except a BindStmt
761 -- for which it's the fwd refs within the bind itself
762 -- (This set may not be empty, because we're in a recursive
764 segs <- rn_rec_stmts bndrs stmts
766 ; (thing, fvs_later) <- thing_inside
769 -- Step 3: Fill in the fwd refs.
770 -- The segments are all singletons, but their fwd-ref
771 -- field mentions all the things used by the segment
772 -- that are bound after their use
773 segs_w_fwd_refs = addFwdRefs segs
775 -- Step 4: Group together the segments to make bigger segments
776 -- Invariant: in the result, no segment uses a variable
777 -- bound in a later segment
778 grouped_segs = glomSegments segs_w_fwd_refs
780 -- Step 5: Turn the segments into Stmts
781 -- Use RecStmt when and only when there are fwd refs
782 -- Also gather up the uses from the end towards the
783 -- start, so we can tell the RecStmt which things are
784 -- used 'after' the RecStmt
785 (stmts', fvs) = segsToStmts grouped_segs fvs_later
787 ; return ((stmts', thing), fvs) }
789 doc = text "In a recursive mdo-expression"
791 ---------------------------------------------
792 rn_rec_stmts :: [Name] -> [LStmt RdrName] -> RnM [Segment (LStmt Name)]
793 rn_rec_stmts bndrs stmts = mappM (rn_rec_stmt bndrs) stmts `thenM` \ segs_s ->
794 returnM (concat segs_s)
796 ----------------------------------------------------
797 rn_rec_stmt :: [Name] -> LStmt RdrName -> RnM [Segment (LStmt Name)]
798 -- Rename a Stmt that is inside a RecStmt (or mdo)
799 -- Assumes all binders are already in scope
800 -- Turns each stmt into a singleton Stmt
802 rn_rec_stmt all_bndrs (L loc (ExprStmt expr _ _))
803 = rnLExpr expr `thenM` \ (expr', fvs) ->
804 lookupSyntaxName thenMName `thenM` \ (then_op, fvs1) ->
805 returnM [(emptyNameSet, fvs `plusFV` fvs1, emptyNameSet,
806 L loc (ExprStmt expr' then_op placeHolderType))]
808 rn_rec_stmt all_bndrs (L loc (BindStmt pat expr _ _))
809 = rnLExpr expr `thenM` \ (expr', fv_expr) ->
810 rnLPat pat `thenM` \ (pat', fv_pat) ->
811 lookupSyntaxName bindMName `thenM` \ (bind_op, fvs1) ->
812 lookupSyntaxName failMName `thenM` \ (fail_op, fvs2) ->
814 bndrs = mkNameSet (collectPatBinders pat')
815 fvs = fv_expr `plusFV` fv_pat `plusFV` fvs1 `plusFV` fvs2
817 returnM [(bndrs, fvs, bndrs `intersectNameSet` fvs,
818 L loc (BindStmt pat' expr' bind_op fail_op))]
820 rn_rec_stmt all_bndrs (L loc (LetStmt binds@(HsIPBinds _)))
821 = do { addErr (badIpBinds (ptext SLIT("an mdo expression")) binds)
824 rn_rec_stmt all_bndrs (L loc (LetStmt (HsValBinds binds)))
825 = rnValBinds (trimWith all_bndrs) binds `thenM` \ (binds', du_binds) ->
826 returnM [(duDefs du_binds, duUses du_binds,
827 emptyNameSet, L loc (LetStmt (HsValBinds binds')))]
829 rn_rec_stmt all_bndrs (L loc (RecStmt stmts _ _ _ _)) -- Flatten Rec inside Rec
830 = rn_rec_stmts all_bndrs stmts
832 rn_rec_stmt all_bndrs stmt@(L _ (ParStmt _)) -- Syntactically illegal in mdo
833 = pprPanic "rn_rec_stmt" (ppr stmt)
835 ---------------------------------------------
836 addFwdRefs :: [Segment a] -> [Segment a]
837 -- So far the segments only have forward refs *within* the Stmt
838 -- (which happens for bind: x <- ...x...)
839 -- This function adds the cross-seg fwd ref info
842 = fst (foldr mk_seg ([], emptyNameSet) pairs)
844 mk_seg (defs, uses, fwds, stmts) (segs, later_defs)
845 = (new_seg : segs, all_defs)
847 new_seg = (defs, uses, new_fwds, stmts)
848 all_defs = later_defs `unionNameSets` defs
849 new_fwds = fwds `unionNameSets` (uses `intersectNameSet` later_defs)
850 -- Add the downstream fwd refs here
852 ----------------------------------------------------
853 -- Glomming the singleton segments of an mdo into
854 -- minimal recursive groups.
856 -- At first I thought this was just strongly connected components, but
857 -- there's an important constraint: the order of the stmts must not change.
860 -- mdo { x <- ...y...
867 -- Here, the first stmt mention 'y', which is bound in the third.
868 -- But that means that the innocent second stmt (p <- z) gets caught
869 -- up in the recursion. And that in turn means that the binding for
870 -- 'z' has to be included... and so on.
872 -- Start at the tail { r <- x }
873 -- Now add the next one { z <- y ; r <- x }
874 -- Now add one more { q <- x ; z <- y ; r <- x }
875 -- Now one more... but this time we have to group a bunch into rec
876 -- { rec { y <- ...x... ; q <- x ; z <- y } ; r <- x }
877 -- Now one more, which we can add on without a rec
879 -- rec { y <- ...x... ; q <- x ; z <- y } ;
881 -- Finally we add the last one; since it mentions y we have to
882 -- glom it togeher with the first two groups
883 -- { rec { x <- ...y...; p <- z ; y <- ...x... ;
884 -- q <- x ; z <- y } ;
887 glomSegments :: [Segment (LStmt Name)] -> [Segment [LStmt Name]]
890 glomSegments ((defs,uses,fwds,stmt) : segs)
891 -- Actually stmts will always be a singleton
892 = (seg_defs, seg_uses, seg_fwds, seg_stmts) : others
894 segs' = glomSegments segs
895 (extras, others) = grab uses segs'
896 (ds, us, fs, ss) = unzip4 extras
898 seg_defs = plusFVs ds `plusFV` defs
899 seg_uses = plusFVs us `plusFV` uses
900 seg_fwds = plusFVs fs `plusFV` fwds
901 seg_stmts = stmt : concat ss
903 grab :: NameSet -- The client
905 -> ([Segment a], -- Needed by the 'client'
906 [Segment a]) -- Not needed by the client
907 -- The result is simply a split of the input
909 = (reverse yeses, reverse noes)
911 (noes, yeses) = span not_needed (reverse dus)
912 not_needed (defs,_,_,_) = not (intersectsNameSet defs uses)
915 ----------------------------------------------------
916 segsToStmts :: [Segment [LStmt Name]]
917 -> FreeVars -- Free vars used 'later'
918 -> ([LStmt Name], FreeVars)
920 segsToStmts [] fvs_later = ([], fvs_later)
921 segsToStmts ((defs, uses, fwds, ss) : segs) fvs_later
922 = ASSERT( not (null ss) )
923 (new_stmt : later_stmts, later_uses `plusFV` uses)
925 (later_stmts, later_uses) = segsToStmts segs fvs_later
926 new_stmt | non_rec = head ss
927 | otherwise = L (getLoc (head ss)) $
928 RecStmt ss (nameSetToList used_later) (nameSetToList fwds)
931 non_rec = isSingleton ss && isEmptyNameSet fwds
932 used_later = defs `intersectNameSet` later_uses
933 -- The ones needed after the RecStmt
936 %************************************************************************
938 \subsubsection{breakpoint utils}
940 %************************************************************************
943 #if defined(GHCI) && defined(BREAKPOINT)
944 mkBreakPointExpr :: [Name] -> RnM (HsExpr Name, FreeVars)
945 mkBreakPointExpr scope
946 = do sloc <- getSrcSpanM
947 undef <- lookupOccRn undefined_RDR
949 lHsApp x y = inLoc (HsApp x y)
950 mkExpr fnName args = mkExpr' fnName (reverse args)
951 mkExpr' fnName [] = inLoc (HsVar fnName)
952 mkExpr' fnName (arg:args)
953 = lHsApp (mkExpr' fnName args) (inLoc arg)
954 expr = unLoc $ mkExpr breakpointJumpName [mkScopeArg scope, HsVar undef, HsLit msg]
956 = unLoc $ mkExpr undef (map HsVar args)
957 msg = HsString (mkFastString (unpackFS (srcSpanFile sloc) ++ ":" ++ show (srcSpanStartLine sloc)))
958 return (expr, emptyFVs)
962 %************************************************************************
964 \subsubsection{Assertion utils}
966 %************************************************************************
969 mkAssertErrorExpr :: RnM (HsExpr Name, FreeVars)
970 -- Return an expression for (assertError "Foo.hs:27")
972 = getSrcSpanM `thenM` \ sloc ->
974 expr = HsApp (L sloc (HsVar assertErrorName)) (L sloc (HsLit msg))
975 msg = HsStringPrim (mkFastString (showSDoc (ppr sloc)))
977 returnM (expr, emptyFVs)
980 %************************************************************************
982 \subsubsection{Errors}
984 %************************************************************************
987 patSynErr e = do { addErr (sep [ptext SLIT("Pattern syntax in expression context:"),
989 ; return (EWildPat, emptyFVs) }
991 parStmtErr = addErr (ptext SLIT("Illegal parallel list comprehension: use -fglasgow-exts"))
993 badIpBinds what binds
994 = hang (ptext SLIT("Implicit-parameter bindings illegal in") <+> what)