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 HscTypes ( availNames )
27 import OccName ( plusOccEnv )
28 import RnNames ( getLocalDeclBinders, extendRdrEnvRn )
29 import RnTypes ( rnHsTypeFVs, rnLPat, rnOverLit, rnPatsAndThen, rnLit,
30 mkOpFormRn, mkOpAppRn, mkNegAppRn, checkSectionPrec,
31 dupFieldErr, checkTupSize )
32 import DynFlags ( DynFlag(..) )
33 import BasicTypes ( FixityDirection(..) )
34 import SrcLoc ( SrcSpan )
35 import PrelNames ( thFAKE, hasKey, assertIdKey, assertErrorName,
36 loopAName, choiceAName, appAName, arrAName, composeAName, firstAName,
37 negateName, thenMName, bindMName, failMName )
39 import Name ( Name, nameOccName, nameIsLocalOrFrom )
41 import RdrName ( RdrName, extendLocalRdrEnv, lookupLocalRdrEnv, hideSomeUnquals )
42 import LoadIface ( loadInterfaceForName )
43 import UniqFM ( isNullUFM )
44 import UniqSet ( emptyUniqSet )
46 import Util ( isSingleton )
47 import ListSetOps ( removeDups )
48 import Maybes ( expectJust )
50 import SrcLoc ( Located(..), unLoc, getLoc, cmpLocated )
53 import List ( unzip4 )
57 %************************************************************************
59 \subsubsection{Expressions}
61 %************************************************************************
64 rnExprs :: [LHsExpr RdrName] -> RnM ([LHsExpr Name], FreeVars)
65 rnExprs ls = rnExprs' ls emptyUniqSet
67 rnExprs' [] acc = returnM ([], acc)
68 rnExprs' (expr:exprs) acc
69 = rnLExpr expr `thenM` \ (expr', fvExpr) ->
71 -- Now we do a "seq" on the free vars because typically it's small
72 -- or empty, especially in very long lists of constants
74 acc' = acc `plusFV` fvExpr
76 (grubby_seqNameSet acc' rnExprs') exprs acc' `thenM` \ (exprs', fvExprs) ->
77 returnM (expr':exprs', fvExprs)
79 -- Grubby little function to do "seq" on namesets; replace by proper seq when GHC can do seq
80 grubby_seqNameSet ns result | isNullUFM ns = result
84 Variables. We look up the variable and return the resulting name.
87 rnLExpr :: LHsExpr RdrName -> RnM (LHsExpr Name, FreeVars)
88 rnLExpr = wrapLocFstM rnExpr
90 rnExpr :: HsExpr RdrName -> RnM (HsExpr Name, FreeVars)
93 = do name <- lookupOccRn v
94 localRdrEnv <- getLocalRdrEnv
96 ignore_asserts <- doptM Opt_IgnoreAsserts
97 ignore_breakpoints <- doptM Opt_IgnoreBreakpoints
99 let conds = [ (name `hasKey` assertIdKey
100 && not ignore_asserts,
101 do (e, fvs) <- mkAssertErrorExpr
102 return (e, fvs `addOneFV` name))
104 case lookup True conds of
105 Just action -> action
106 Nothing -> return (HsVar name, unitFV name)
109 = newIPNameRn v `thenM` \ name ->
110 returnM (HsIPVar name, emptyFVs)
114 returnM (HsLit lit, emptyFVs)
116 rnExpr (HsOverLit lit)
117 = rnOverLit lit `thenM` \ (lit', fvs) ->
118 returnM (HsOverLit lit', fvs)
120 rnExpr (HsApp fun arg)
121 = rnLExpr fun `thenM` \ (fun',fvFun) ->
122 rnLExpr arg `thenM` \ (arg',fvArg) ->
123 returnM (HsApp fun' arg', fvFun `plusFV` fvArg)
125 rnExpr (OpApp e1 op _ e2)
126 = rnLExpr e1 `thenM` \ (e1', fv_e1) ->
127 rnLExpr e2 `thenM` \ (e2', fv_e2) ->
128 rnLExpr op `thenM` \ (op'@(L _ (HsVar op_name)), fv_op) ->
131 -- When renaming code synthesised from "deriving" declarations
132 -- we used to avoid fixity stuff, but we can't easily tell any
133 -- more, so I've removed the test. Adding HsPars in TcGenDeriv
134 -- should prevent bad things happening.
135 lookupFixityRn op_name `thenM` \ fixity ->
136 mkOpAppRn e1' op' fixity e2' `thenM` \ final_e ->
139 fv_e1 `plusFV` fv_op `plusFV` fv_e2)
142 = rnLExpr e `thenM` \ (e', fv_e) ->
143 lookupSyntaxName negateName `thenM` \ (neg_name, fv_neg) ->
144 mkNegAppRn e' neg_name `thenM` \ final_e ->
145 returnM (final_e, fv_e `plusFV` fv_neg)
148 = rnLExpr e `thenM` \ (e', fvs_e) ->
149 returnM (HsPar e', fvs_e)
151 -- Template Haskell extensions
152 -- Don't ifdef-GHCI them because we want to fail gracefully
153 -- (not with an rnExpr crash) in a stage-1 compiler.
154 rnExpr e@(HsBracket br_body)
155 = checkTH e "bracket" `thenM_`
156 rnBracket br_body `thenM` \ (body', fvs_e) ->
157 returnM (HsBracket body', fvs_e)
159 rnExpr e@(HsSpliceE splice)
160 = rnSplice splice `thenM` \ (splice', fvs) ->
161 returnM (HsSpliceE splice', fvs)
163 rnExpr section@(SectionL expr op)
164 = rnLExpr expr `thenM` \ (expr', fvs_expr) ->
165 rnLExpr op `thenM` \ (op', fvs_op) ->
166 checkSectionPrec InfixL section op' expr' `thenM_`
167 returnM (SectionL expr' op', fvs_op `plusFV` fvs_expr)
169 rnExpr section@(SectionR op expr)
170 = rnLExpr op `thenM` \ (op', fvs_op) ->
171 rnLExpr expr `thenM` \ (expr', fvs_expr) ->
172 checkSectionPrec InfixR section op' expr' `thenM_`
173 returnM (SectionR op' expr', fvs_op `plusFV` fvs_expr)
175 rnExpr (HsCoreAnn ann expr)
176 = rnLExpr expr `thenM` \ (expr', fvs_expr) ->
177 returnM (HsCoreAnn ann expr', fvs_expr)
179 rnExpr (HsSCC lbl expr)
180 = rnLExpr expr `thenM` \ (expr', fvs_expr) ->
181 returnM (HsSCC lbl expr', fvs_expr)
182 rnExpr (HsTickPragma info expr)
183 = rnLExpr expr `thenM` \ (expr', fvs_expr) ->
184 returnM (HsTickPragma info expr', fvs_expr)
186 rnExpr (HsLam matches)
187 = rnMatchGroup LambdaExpr matches `thenM` \ (matches', fvMatch) ->
188 returnM (HsLam matches', fvMatch)
190 rnExpr (HsCase expr matches)
191 = rnLExpr expr `thenM` \ (new_expr, e_fvs) ->
192 rnMatchGroup CaseAlt matches `thenM` \ (new_matches, ms_fvs) ->
193 returnM (HsCase new_expr new_matches, e_fvs `plusFV` ms_fvs)
195 rnExpr (HsLet binds expr)
196 = rnLocalBindsAndThen binds $ \ binds' ->
197 rnLExpr expr `thenM` \ (expr',fvExpr) ->
198 returnM (HsLet binds' expr', fvExpr)
200 rnExpr e@(HsDo do_or_lc stmts body _)
201 = do { ((stmts', body'), fvs) <- rnStmts do_or_lc stmts $
203 ; return (HsDo do_or_lc stmts' body' placeHolderType, fvs) }
205 rnExpr (ExplicitList _ exps)
206 = rnExprs exps `thenM` \ (exps', fvs) ->
207 returnM (ExplicitList placeHolderType exps', fvs `addOneFV` listTyCon_name)
209 rnExpr (ExplicitPArr _ exps)
210 = rnExprs exps `thenM` \ (exps', fvs) ->
211 returnM (ExplicitPArr placeHolderType exps', fvs)
213 rnExpr e@(ExplicitTuple exps boxity)
214 = checkTupSize tup_size `thenM_`
215 rnExprs exps `thenM` \ (exps', fvs) ->
216 returnM (ExplicitTuple exps' boxity, fvs `addOneFV` tycon_name)
218 tup_size = length exps
219 tycon_name = tupleTyCon_name boxity tup_size
221 rnExpr (RecordCon con_id _ rbinds)
222 = lookupLocatedOccRn con_id `thenM` \ conname ->
223 rnRbinds "construction" rbinds `thenM` \ (rbinds', fvRbinds) ->
224 returnM (RecordCon conname noPostTcExpr rbinds',
225 fvRbinds `addOneFV` unLoc conname)
227 rnExpr (RecordUpd expr rbinds _ _)
228 = rnLExpr expr `thenM` \ (expr', fvExpr) ->
229 rnRbinds "update" rbinds `thenM` \ (rbinds', fvRbinds) ->
230 returnM (RecordUpd expr' rbinds' placeHolderType placeHolderType,
231 fvExpr `plusFV` fvRbinds)
233 rnExpr (ExprWithTySig expr pty)
234 = do { (pty', fvTy) <- rnHsTypeFVs doc pty
235 ; (expr', fvExpr) <- bindSigTyVarsFV (hsExplicitTvs pty') $
237 ; return (ExprWithTySig expr' pty', fvExpr `plusFV` fvTy) }
239 doc = text "In an expression type signature"
241 rnExpr (HsIf p b1 b2)
242 = rnLExpr p `thenM` \ (p', fvP) ->
243 rnLExpr b1 `thenM` \ (b1', fvB1) ->
244 rnLExpr b2 `thenM` \ (b2', fvB2) ->
245 returnM (HsIf p' b1' b2', plusFVs [fvP, fvB1, fvB2])
248 = rnHsTypeFVs doc a `thenM` \ (t, fvT) ->
249 returnM (HsType t, fvT)
251 doc = text "In a type argument"
253 rnExpr (ArithSeq _ seq)
254 = rnArithSeq seq `thenM` \ (new_seq, fvs) ->
255 returnM (ArithSeq noPostTcExpr new_seq, fvs)
257 rnExpr (PArrSeq _ seq)
258 = rnArithSeq seq `thenM` \ (new_seq, fvs) ->
259 returnM (PArrSeq noPostTcExpr new_seq, fvs)
262 These three are pattern syntax appearing in expressions.
263 Since all the symbols are reservedops we can simply reject them.
264 We return a (bogus) EWildPat in each case.
267 rnExpr e@EWildPat = patSynErr e
268 rnExpr e@(EAsPat {}) = patSynErr e
269 rnExpr e@(ELazyPat {}) = patSynErr e
272 %************************************************************************
276 %************************************************************************
279 rnExpr (HsProc pat body)
281 rnPatsAndThen ProcExpr [pat] $ \ [pat'] ->
282 rnCmdTop body `thenM` \ (body',fvBody) ->
283 returnM (HsProc pat' body', fvBody)
285 rnExpr (HsArrApp arrow arg _ ho rtl)
286 = select_arrow_scope (rnLExpr arrow) `thenM` \ (arrow',fvArrow) ->
287 rnLExpr arg `thenM` \ (arg',fvArg) ->
288 returnM (HsArrApp arrow' arg' placeHolderType ho rtl,
289 fvArrow `plusFV` fvArg)
291 select_arrow_scope tc = case ho of
292 HsHigherOrderApp -> tc
293 HsFirstOrderApp -> escapeArrowScope tc
296 rnExpr (HsArrForm op (Just _) [arg1, arg2])
297 = escapeArrowScope (rnLExpr op)
298 `thenM` \ (op'@(L _ (HsVar op_name)),fv_op) ->
299 rnCmdTop arg1 `thenM` \ (arg1',fv_arg1) ->
300 rnCmdTop arg2 `thenM` \ (arg2',fv_arg2) ->
304 lookupFixityRn op_name `thenM` \ fixity ->
305 mkOpFormRn arg1' op' fixity arg2' `thenM` \ final_e ->
308 fv_arg1 `plusFV` fv_op `plusFV` fv_arg2)
310 rnExpr (HsArrForm op fixity cmds)
311 = escapeArrowScope (rnLExpr op) `thenM` \ (op',fvOp) ->
312 rnCmdArgs cmds `thenM` \ (cmds',fvCmds) ->
313 returnM (HsArrForm op' fixity cmds', fvOp `plusFV` fvCmds)
315 rnExpr other = pprPanic "rnExpr: unexpected expression" (ppr other)
320 %************************************************************************
324 %************************************************************************
327 rnCmdArgs [] = returnM ([], emptyFVs)
329 = rnCmdTop arg `thenM` \ (arg',fvArg) ->
330 rnCmdArgs args `thenM` \ (args',fvArgs) ->
331 returnM (arg':args', fvArg `plusFV` fvArgs)
334 rnCmdTop = wrapLocFstM rnCmdTop'
336 rnCmdTop' (HsCmdTop cmd _ _ _)
337 = rnLExpr (convertOpFormsLCmd cmd) `thenM` \ (cmd', fvCmd) ->
339 cmd_names = [arrAName, composeAName, firstAName] ++
340 nameSetToList (methodNamesCmd (unLoc cmd'))
342 -- Generate the rebindable syntax for the monad
343 lookupSyntaxTable cmd_names `thenM` \ (cmd_names', cmd_fvs) ->
345 returnM (HsCmdTop cmd' [] placeHolderType cmd_names',
346 fvCmd `plusFV` cmd_fvs)
348 ---------------------------------------------------
349 -- convert OpApp's in a command context to HsArrForm's
351 convertOpFormsLCmd :: LHsCmd id -> LHsCmd id
352 convertOpFormsLCmd = fmap convertOpFormsCmd
354 convertOpFormsCmd :: HsCmd id -> HsCmd id
356 convertOpFormsCmd (HsApp c e) = HsApp (convertOpFormsLCmd c) e
357 convertOpFormsCmd (HsLam match) = HsLam (convertOpFormsMatch match)
358 convertOpFormsCmd (OpApp c1 op fixity c2)
360 arg1 = L (getLoc c1) $ HsCmdTop (convertOpFormsLCmd c1) [] placeHolderType []
361 arg2 = L (getLoc c2) $ HsCmdTop (convertOpFormsLCmd c2) [] placeHolderType []
363 HsArrForm op (Just fixity) [arg1, arg2]
365 convertOpFormsCmd (HsPar c) = HsPar (convertOpFormsLCmd c)
368 convertOpFormsCmd (HsCase exp matches)
369 = HsCase exp (convertOpFormsMatch matches)
371 convertOpFormsCmd (HsIf exp c1 c2)
372 = HsIf exp (convertOpFormsLCmd c1) (convertOpFormsLCmd c2)
374 convertOpFormsCmd (HsLet binds cmd)
375 = HsLet binds (convertOpFormsLCmd cmd)
377 convertOpFormsCmd (HsDo ctxt stmts body ty)
378 = HsDo ctxt (map (fmap convertOpFormsStmt) stmts)
379 (convertOpFormsLCmd body) ty
381 -- Anything else is unchanged. This includes HsArrForm (already done),
382 -- things with no sub-commands, and illegal commands (which will be
383 -- caught by the type checker)
384 convertOpFormsCmd c = c
386 convertOpFormsStmt (BindStmt pat cmd _ _)
387 = BindStmt pat (convertOpFormsLCmd cmd) noSyntaxExpr noSyntaxExpr
388 convertOpFormsStmt (ExprStmt cmd _ _)
389 = ExprStmt (convertOpFormsLCmd cmd) noSyntaxExpr placeHolderType
390 convertOpFormsStmt (RecStmt stmts lvs rvs es binds)
391 = RecStmt (map (fmap convertOpFormsStmt) stmts) lvs rvs es binds
392 convertOpFormsStmt stmt = stmt
394 convertOpFormsMatch (MatchGroup ms ty)
395 = MatchGroup (map (fmap convert) ms) ty
396 where convert (Match pat mty grhss)
397 = Match pat mty (convertOpFormsGRHSs grhss)
399 convertOpFormsGRHSs (GRHSs grhss binds)
400 = GRHSs (map convertOpFormsGRHS grhss) binds
402 convertOpFormsGRHS = fmap convert
404 convert (GRHS stmts cmd) = GRHS stmts (convertOpFormsLCmd cmd)
406 ---------------------------------------------------
407 type CmdNeeds = FreeVars -- Only inhabitants are
408 -- appAName, choiceAName, loopAName
410 -- find what methods the Cmd needs (loop, choice, apply)
411 methodNamesLCmd :: LHsCmd Name -> CmdNeeds
412 methodNamesLCmd = methodNamesCmd . unLoc
414 methodNamesCmd :: HsCmd Name -> CmdNeeds
416 methodNamesCmd cmd@(HsArrApp _arrow _arg _ HsFirstOrderApp _rtl)
418 methodNamesCmd cmd@(HsArrApp _arrow _arg _ HsHigherOrderApp _rtl)
420 methodNamesCmd cmd@(HsArrForm {}) = emptyFVs
422 methodNamesCmd (HsPar c) = methodNamesLCmd c
424 methodNamesCmd (HsIf p c1 c2)
425 = methodNamesLCmd c1 `plusFV` methodNamesLCmd c2 `addOneFV` choiceAName
427 methodNamesCmd (HsLet b c) = methodNamesLCmd c
429 methodNamesCmd (HsDo sc stmts body ty)
430 = methodNamesStmts stmts `plusFV` methodNamesLCmd body
432 methodNamesCmd (HsApp c e) = methodNamesLCmd c
434 methodNamesCmd (HsLam match) = methodNamesMatch match
436 methodNamesCmd (HsCase scrut matches)
437 = methodNamesMatch matches `addOneFV` choiceAName
439 methodNamesCmd other = emptyFVs
440 -- Other forms can't occur in commands, but it's not convenient
441 -- to error here so we just do what's convenient.
442 -- The type checker will complain later
444 ---------------------------------------------------
445 methodNamesMatch (MatchGroup ms _)
446 = plusFVs (map do_one ms)
448 do_one (L _ (Match pats sig_ty grhss)) = methodNamesGRHSs grhss
450 -------------------------------------------------
452 methodNamesGRHSs (GRHSs grhss binds) = plusFVs (map methodNamesGRHS grhss)
454 -------------------------------------------------
455 methodNamesGRHS (L _ (GRHS stmts rhs)) = methodNamesLCmd rhs
457 ---------------------------------------------------
458 methodNamesStmts stmts = plusFVs (map methodNamesLStmt stmts)
460 ---------------------------------------------------
461 methodNamesLStmt = methodNamesStmt . unLoc
463 methodNamesStmt (ExprStmt cmd _ _) = methodNamesLCmd cmd
464 methodNamesStmt (BindStmt pat cmd _ _) = methodNamesLCmd cmd
465 methodNamesStmt (RecStmt stmts _ _ _ _)
466 = methodNamesStmts stmts `addOneFV` loopAName
467 methodNamesStmt (LetStmt b) = emptyFVs
468 methodNamesStmt (ParStmt ss) = emptyFVs
469 -- ParStmt can't occur in commands, but it's not convenient to error
470 -- here so we just do what's convenient
474 %************************************************************************
478 %************************************************************************
481 rnArithSeq (From expr)
482 = rnLExpr expr `thenM` \ (expr', fvExpr) ->
483 returnM (From expr', fvExpr)
485 rnArithSeq (FromThen expr1 expr2)
486 = rnLExpr expr1 `thenM` \ (expr1', fvExpr1) ->
487 rnLExpr expr2 `thenM` \ (expr2', fvExpr2) ->
488 returnM (FromThen expr1' expr2', fvExpr1 `plusFV` fvExpr2)
490 rnArithSeq (FromTo expr1 expr2)
491 = rnLExpr expr1 `thenM` \ (expr1', fvExpr1) ->
492 rnLExpr expr2 `thenM` \ (expr2', fvExpr2) ->
493 returnM (FromTo expr1' expr2', fvExpr1 `plusFV` fvExpr2)
495 rnArithSeq (FromThenTo expr1 expr2 expr3)
496 = rnLExpr expr1 `thenM` \ (expr1', fvExpr1) ->
497 rnLExpr expr2 `thenM` \ (expr2', fvExpr2) ->
498 rnLExpr expr3 `thenM` \ (expr3', fvExpr3) ->
499 returnM (FromThenTo expr1' expr2' expr3',
500 plusFVs [fvExpr1, fvExpr2, fvExpr3])
504 %************************************************************************
506 \subsubsection{@Rbinds@s and @Rpats@s: in record expressions}
508 %************************************************************************
512 = mappM_ field_dup_err dup_fields `thenM_`
513 mapFvRn rn_rbind rbinds `thenM` \ (rbinds', fvRbind) ->
514 returnM (rbinds', fvRbind)
516 (_, dup_fields) = removeDups cmpLocated [ f | (f,_) <- rbinds ]
518 field_dup_err dups = mappM_ (\f -> addLocErr f (dupFieldErr str)) dups
520 rn_rbind (field, expr)
521 = lookupLocatedGlobalOccRn field `thenM` \ fieldname ->
522 rnLExpr expr `thenM` \ (expr', fvExpr) ->
523 returnM ((fieldname, expr'), fvExpr `addOneFV` unLoc fieldname)
526 %************************************************************************
528 Template Haskell brackets
530 %************************************************************************
533 rnBracket (VarBr n) = do { name <- lookupOccRn n
534 ; this_mod <- getModule
535 ; checkM (nameIsLocalOrFrom this_mod name) $ -- Reason: deprecation checking asumes the
536 do { loadInterfaceForName msg name -- home interface is loaded, and this is the
537 ; return () } -- only way that is going to happen
538 ; returnM (VarBr name, unitFV name) }
540 msg = ptext SLIT("Need interface for Template Haskell quoted Name")
542 rnBracket (ExpBr e) = do { (e', fvs) <- rnLExpr e
543 ; return (ExpBr e', fvs) }
544 rnBracket (PatBr p) = do { (p', fvs) <- rnLPat p
545 ; return (PatBr p', fvs) }
546 rnBracket (TypBr t) = do { (t', fvs) <- rnHsTypeFVs doc t
547 ; return (TypBr t', fvs) }
549 doc = ptext SLIT("In a Template-Haskell quoted type")
550 rnBracket (DecBr group)
551 = do { gbl_env <- getGblEnv
553 ; let gbl_env1 = gbl_env { tcg_mod = thFAKE }
554 -- Note the thFAKE. The top-level names from the bracketed
555 -- declarations will go into the name cache, and we don't want them to
556 -- confuse the Names for the current module.
557 -- By using a pretend module, thFAKE, we keep them safely out of the way.
559 ; avails <- getLocalDeclBinders gbl_env1 group
560 ; let names = concatMap availNames avails
562 ; let new_occs = map nameOccName names
563 trimmed_rdr_env = hideSomeUnquals (tcg_rdr_env gbl_env) new_occs
565 ; rdr_env' <- extendRdrEnvRn trimmed_rdr_env avails
566 -- In this situation we want to *shadow* top-level bindings.
568 -- bar = [d| foo = 1|]
569 -- If we don't shadow, we'll get an ambiguity complaint when we do
570 -- a lookupTopBndrRn (which uses lookupGreLocalRn) on the binder of the 'foo'
572 -- Furthermore, arguably if the splice does define foo, that should hide
573 -- any foo's further out
575 -- The shadowing is acheived by the call to hideSomeUnquals, which removes
576 -- the unqualified bindings of things defined by the bracket
578 ; setGblEnv (gbl_env { tcg_rdr_env = rdr_env',
579 tcg_dus = emptyDUs }) $ do
580 -- The emptyDUs is so that we just collect uses for this group alone
582 { (tcg_env, group') <- rnSrcDecls group
583 -- Discard the tcg_env; it contains only extra info about fixity
584 ; return (DecBr group', allUses (tcg_dus tcg_env)) } }
587 %************************************************************************
589 \subsubsection{@Stmt@s: in @do@ expressions}
591 %************************************************************************
594 rnStmts :: HsStmtContext Name -> [LStmt RdrName]
595 -> RnM (thing, FreeVars)
596 -> RnM (([LStmt Name], thing), FreeVars)
598 rnStmts (MDoExpr _) = rnMDoStmts
599 rnStmts ctxt = rnNormalStmts ctxt
601 rnNormalStmts :: HsStmtContext Name -> [LStmt RdrName]
602 -> RnM (thing, FreeVars)
603 -> RnM (([LStmt Name], thing), FreeVars)
604 -- Used for cases *other* than recursive mdo
605 -- Implements nested scopes
607 rnNormalStmts ctxt [] thing_inside
608 = do { (thing, fvs) <- thing_inside
609 ; return (([],thing), fvs) }
611 rnNormalStmts ctxt (L loc stmt : stmts) thing_inside
612 = do { ((stmt', (stmts', thing)), fvs)
613 <- rnStmt ctxt stmt $
614 rnNormalStmts ctxt stmts thing_inside
615 ; return (((L loc stmt' : stmts'), thing), fvs) }
617 rnStmt :: HsStmtContext Name -> Stmt RdrName
618 -> RnM (thing, FreeVars)
619 -> RnM ((Stmt Name, thing), FreeVars)
621 rnStmt ctxt (ExprStmt expr _ _) thing_inside
622 = do { (expr', fv_expr) <- rnLExpr expr
623 ; (then_op, fvs1) <- lookupSyntaxName thenMName
624 ; (thing, fvs2) <- thing_inside
625 ; return ((ExprStmt expr' then_op placeHolderType, thing),
626 fv_expr `plusFV` fvs1 `plusFV` fvs2) }
628 rnStmt ctxt (BindStmt pat expr _ _) thing_inside
629 = do { (expr', fv_expr) <- rnLExpr expr
630 -- The binders do not scope over the expression
631 ; (bind_op, fvs1) <- lookupSyntaxName bindMName
632 ; (fail_op, fvs2) <- lookupSyntaxName failMName
633 ; rnPatsAndThen (StmtCtxt ctxt) [pat] $ \ [pat'] -> do
634 { (thing, fvs3) <- thing_inside
635 ; return ((BindStmt pat' expr' bind_op fail_op, thing),
636 fv_expr `plusFV` fvs1 `plusFV` fvs2 `plusFV` fvs3) }}
637 -- fv_expr shouldn't really be filtered by the rnPatsAndThen
638 -- but it does not matter because the names are unique
640 rnStmt ctxt (LetStmt binds) thing_inside
641 = do { checkErr (ok ctxt binds)
642 (badIpBinds (ptext SLIT("a parallel list comprehension:")) binds)
643 ; rnLocalBindsAndThen binds $ \ binds' -> do
644 { (thing, fvs) <- thing_inside
645 ; return ((LetStmt binds', thing), fvs) }}
647 -- We do not allow implicit-parameter bindings in a parallel
648 -- list comprehension. I'm not sure what it might mean.
649 ok (ParStmtCtxt _) (HsIPBinds _) = False
652 rnStmt ctxt (RecStmt rec_stmts _ _ _ _) thing_inside
653 = bindLocatedLocalsRn doc (collectLStmtsBinders rec_stmts) $ \ bndrs ->
654 rn_rec_stmts bndrs rec_stmts `thenM` \ segs ->
655 thing_inside `thenM` \ (thing, fvs) ->
657 segs_w_fwd_refs = addFwdRefs segs
658 (ds, us, fs, rec_stmts') = unzip4 segs_w_fwd_refs
659 later_vars = nameSetToList (plusFVs ds `intersectNameSet` fvs)
660 fwd_vars = nameSetToList (plusFVs fs)
662 rec_stmt = RecStmt rec_stmts' later_vars fwd_vars [] emptyLHsBinds
664 returnM ((rec_stmt, thing), uses `plusFV` fvs)
666 doc = text "In a recursive do statement"
668 rnStmt ctxt (ParStmt segs) thing_inside
669 = do { opt_GlasgowExts <- doptM Opt_GlasgowExts
670 ; checkM opt_GlasgowExts parStmtErr
671 ; orig_lcl_env <- getLocalRdrEnv
672 ; ((segs',thing), fvs) <- go orig_lcl_env [] segs
673 ; return ((ParStmt segs', thing), fvs) }
675 -- type ParSeg id = [([LStmt id], [id])]
676 -- go :: NameSet -> [ParSeg RdrName]
677 -- -> RnM (([ParSeg Name], thing), FreeVars)
679 go orig_lcl_env bndrs []
680 = do { let { (bndrs', dups) = removeDups cmpByOcc bndrs
681 ; inner_env = extendLocalRdrEnv orig_lcl_env bndrs' }
683 ; (thing, fvs) <- setLocalRdrEnv inner_env thing_inside
684 ; return (([], thing), fvs) }
686 go orig_lcl_env bndrs_so_far ((stmts, _) : segs)
687 = do { ((stmts', (bndrs, segs', thing)), fvs)
688 <- rnNormalStmts par_ctxt stmts $ do
689 { -- Find the Names that are bound by stmts
690 lcl_env <- getLocalRdrEnv
691 ; let { rdr_bndrs = collectLStmtsBinders stmts
692 ; bndrs = map ( expectJust "rnStmt"
693 . lookupLocalRdrEnv lcl_env
695 ; new_bndrs = nub bndrs ++ bndrs_so_far
696 -- The nub is because there might be shadowing
698 -- So we'll look up (Unqual x) twice, getting
699 -- the second binding both times, which is the
702 -- Typecheck the thing inside, passing on all
703 -- the Names bound, but separately; revert the envt
704 ; ((segs', thing), fvs) <- setLocalRdrEnv orig_lcl_env $
705 go orig_lcl_env new_bndrs segs
707 -- Figure out which of the bound names are used
708 ; let used_bndrs = filter (`elemNameSet` fvs) bndrs
709 ; return ((used_bndrs, segs', thing), fvs) }
711 ; let seg' = (stmts', bndrs)
712 ; return (((seg':segs'), thing),
713 delListFromNameSet fvs bndrs) }
715 par_ctxt = ParStmtCtxt ctxt
717 cmpByOcc n1 n2 = nameOccName n1 `compare` nameOccName n2
718 dupErr vs = addErr (ptext SLIT("Duplicate binding in parallel list comprehension for:")
719 <+> quotes (ppr (head vs)))
723 %************************************************************************
725 \subsubsection{mdo expressions}
727 %************************************************************************
730 type FwdRefs = NameSet
731 type Segment stmts = (Defs,
732 Uses, -- May include defs
733 FwdRefs, -- A subset of uses that are
734 -- (a) used before they are bound in this segment, or
735 -- (b) used here, and bound in subsequent segments
736 stmts) -- Either Stmt or [Stmt]
739 ----------------------------------------------------
740 rnMDoStmts :: [LStmt RdrName]
741 -> RnM (thing, FreeVars)
742 -> RnM (([LStmt Name], thing), FreeVars)
743 rnMDoStmts stmts thing_inside
744 = -- Step1: bring all the binders of the mdo into scope
745 -- Remember that this also removes the binders from the
746 -- finally-returned free-vars
747 bindLocatedLocalsRn doc (collectLStmtsBinders stmts) $ \ bndrs ->
749 -- Step 2: Rename each individual stmt, making a
750 -- singleton segment. At this stage the FwdRefs field
751 -- isn't finished: it's empty for all except a BindStmt
752 -- for which it's the fwd refs within the bind itself
753 -- (This set may not be empty, because we're in a recursive
755 segs <- rn_rec_stmts bndrs stmts
757 ; (thing, fvs_later) <- thing_inside
760 -- Step 3: Fill in the fwd refs.
761 -- The segments are all singletons, but their fwd-ref
762 -- field mentions all the things used by the segment
763 -- that are bound after their use
764 segs_w_fwd_refs = addFwdRefs segs
766 -- Step 4: Group together the segments to make bigger segments
767 -- Invariant: in the result, no segment uses a variable
768 -- bound in a later segment
769 grouped_segs = glomSegments segs_w_fwd_refs
771 -- Step 5: Turn the segments into Stmts
772 -- Use RecStmt when and only when there are fwd refs
773 -- Also gather up the uses from the end towards the
774 -- start, so we can tell the RecStmt which things are
775 -- used 'after' the RecStmt
776 (stmts', fvs) = segsToStmts grouped_segs fvs_later
778 ; return ((stmts', thing), fvs) }
780 doc = text "In a recursive mdo-expression"
782 ---------------------------------------------
783 rn_rec_stmts :: [Name] -> [LStmt RdrName] -> RnM [Segment (LStmt Name)]
784 rn_rec_stmts bndrs stmts = mappM (rn_rec_stmt bndrs) stmts `thenM` \ segs_s ->
785 returnM (concat segs_s)
787 ----------------------------------------------------
788 rn_rec_stmt :: [Name] -> LStmt RdrName -> RnM [Segment (LStmt Name)]
789 -- Rename a Stmt that is inside a RecStmt (or mdo)
790 -- Assumes all binders are already in scope
791 -- Turns each stmt into a singleton Stmt
793 rn_rec_stmt all_bndrs (L loc (ExprStmt expr _ _))
794 = rnLExpr expr `thenM` \ (expr', fvs) ->
795 lookupSyntaxName thenMName `thenM` \ (then_op, fvs1) ->
796 returnM [(emptyNameSet, fvs `plusFV` fvs1, emptyNameSet,
797 L loc (ExprStmt expr' then_op placeHolderType))]
799 rn_rec_stmt all_bndrs (L loc (BindStmt pat expr _ _))
800 = rnLExpr expr `thenM` \ (expr', fv_expr) ->
801 rnLPat pat `thenM` \ (pat', fv_pat) ->
802 lookupSyntaxName bindMName `thenM` \ (bind_op, fvs1) ->
803 lookupSyntaxName failMName `thenM` \ (fail_op, fvs2) ->
805 bndrs = mkNameSet (collectPatBinders pat')
806 fvs = fv_expr `plusFV` fv_pat `plusFV` fvs1 `plusFV` fvs2
808 returnM [(bndrs, fvs, bndrs `intersectNameSet` fvs,
809 L loc (BindStmt pat' expr' bind_op fail_op))]
811 rn_rec_stmt all_bndrs (L loc (LetStmt binds@(HsIPBinds _)))
812 = do { addErr (badIpBinds (ptext SLIT("an mdo expression")) binds)
815 rn_rec_stmt all_bndrs (L loc (LetStmt (HsValBinds binds)))
816 = rnValBinds (trimWith all_bndrs) binds `thenM` \ (binds', du_binds) ->
817 returnM [(duDefs du_binds, duUses du_binds,
818 emptyNameSet, L loc (LetStmt (HsValBinds binds')))]
820 rn_rec_stmt all_bndrs (L loc (RecStmt stmts _ _ _ _)) -- Flatten Rec inside Rec
821 = rn_rec_stmts all_bndrs stmts
823 rn_rec_stmt all_bndrs stmt@(L _ (ParStmt _)) -- Syntactically illegal in mdo
824 = pprPanic "rn_rec_stmt" (ppr stmt)
826 ---------------------------------------------
827 addFwdRefs :: [Segment a] -> [Segment a]
828 -- So far the segments only have forward refs *within* the Stmt
829 -- (which happens for bind: x <- ...x...)
830 -- This function adds the cross-seg fwd ref info
833 = fst (foldr mk_seg ([], emptyNameSet) pairs)
835 mk_seg (defs, uses, fwds, stmts) (segs, later_defs)
836 = (new_seg : segs, all_defs)
838 new_seg = (defs, uses, new_fwds, stmts)
839 all_defs = later_defs `unionNameSets` defs
840 new_fwds = fwds `unionNameSets` (uses `intersectNameSet` later_defs)
841 -- Add the downstream fwd refs here
843 ----------------------------------------------------
844 -- Glomming the singleton segments of an mdo into
845 -- minimal recursive groups.
847 -- At first I thought this was just strongly connected components, but
848 -- there's an important constraint: the order of the stmts must not change.
851 -- mdo { x <- ...y...
858 -- Here, the first stmt mention 'y', which is bound in the third.
859 -- But that means that the innocent second stmt (p <- z) gets caught
860 -- up in the recursion. And that in turn means that the binding for
861 -- 'z' has to be included... and so on.
863 -- Start at the tail { r <- x }
864 -- Now add the next one { z <- y ; r <- x }
865 -- Now add one more { q <- x ; z <- y ; r <- x }
866 -- Now one more... but this time we have to group a bunch into rec
867 -- { rec { y <- ...x... ; q <- x ; z <- y } ; r <- x }
868 -- Now one more, which we can add on without a rec
870 -- rec { y <- ...x... ; q <- x ; z <- y } ;
872 -- Finally we add the last one; since it mentions y we have to
873 -- glom it togeher with the first two groups
874 -- { rec { x <- ...y...; p <- z ; y <- ...x... ;
875 -- q <- x ; z <- y } ;
878 glomSegments :: [Segment (LStmt Name)] -> [Segment [LStmt Name]]
881 glomSegments ((defs,uses,fwds,stmt) : segs)
882 -- Actually stmts will always be a singleton
883 = (seg_defs, seg_uses, seg_fwds, seg_stmts) : others
885 segs' = glomSegments segs
886 (extras, others) = grab uses segs'
887 (ds, us, fs, ss) = unzip4 extras
889 seg_defs = plusFVs ds `plusFV` defs
890 seg_uses = plusFVs us `plusFV` uses
891 seg_fwds = plusFVs fs `plusFV` fwds
892 seg_stmts = stmt : concat ss
894 grab :: NameSet -- The client
896 -> ([Segment a], -- Needed by the 'client'
897 [Segment a]) -- Not needed by the client
898 -- The result is simply a split of the input
900 = (reverse yeses, reverse noes)
902 (noes, yeses) = span not_needed (reverse dus)
903 not_needed (defs,_,_,_) = not (intersectsNameSet defs uses)
906 ----------------------------------------------------
907 segsToStmts :: [Segment [LStmt Name]]
908 -> FreeVars -- Free vars used 'later'
909 -> ([LStmt Name], FreeVars)
911 segsToStmts [] fvs_later = ([], fvs_later)
912 segsToStmts ((defs, uses, fwds, ss) : segs) fvs_later
913 = ASSERT( not (null ss) )
914 (new_stmt : later_stmts, later_uses `plusFV` uses)
916 (later_stmts, later_uses) = segsToStmts segs fvs_later
917 new_stmt | non_rec = head ss
918 | otherwise = L (getLoc (head ss)) $
919 RecStmt ss (nameSetToList used_later) (nameSetToList fwds)
922 non_rec = isSingleton ss && isEmptyNameSet fwds
923 used_later = defs `intersectNameSet` later_uses
924 -- The ones needed after the RecStmt
927 %************************************************************************
929 \subsubsection{Assertion utils}
931 %************************************************************************
934 srcSpanPrimLit :: SrcSpan -> HsExpr Name
935 srcSpanPrimLit span = HsLit (HsStringPrim (mkFastString (showSDoc (ppr span))))
937 mkAssertErrorExpr :: RnM (HsExpr Name, FreeVars)
938 -- Return an expression for (assertError "Foo.hs:27")
940 = getSrcSpanM `thenM` \ sloc ->
942 expr = HsApp (L sloc (HsVar assertErrorName))
943 (L sloc (srcSpanPrimLit sloc))
945 returnM (expr, emptyFVs)
948 %************************************************************************
950 \subsubsection{Errors}
952 %************************************************************************
955 patSynErr e = do { addErr (sep [ptext SLIT("Pattern syntax in expression context:"),
957 ; return (EWildPat, emptyFVs) }
959 parStmtErr = addErr (ptext SLIT("Illegal parallel list comprehension: use -fglasgow-exts"))
961 badIpBinds what binds
962 = hang (ptext SLIT("Implicit-parameter bindings illegal in") <+> what)