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)
112 rnExpr (HsLit lit@(HsString s))
114 opt_OverloadedStrings <- doptM Opt_OverloadedStrings
115 ; if opt_OverloadedStrings then
116 rnExpr (HsOverLit (mkHsIsString s))
117 else -- Same as below
119 returnM (HsLit lit, emptyFVs)
124 returnM (HsLit lit, emptyFVs)
126 rnExpr (HsOverLit lit)
127 = rnOverLit lit `thenM` \ (lit', fvs) ->
128 returnM (HsOverLit lit', fvs)
130 rnExpr (HsApp fun arg)
131 = rnLExpr fun `thenM` \ (fun',fvFun) ->
132 rnLExpr arg `thenM` \ (arg',fvArg) ->
133 returnM (HsApp fun' arg', fvFun `plusFV` fvArg)
135 rnExpr (OpApp e1 op _ e2)
136 = rnLExpr e1 `thenM` \ (e1', fv_e1) ->
137 rnLExpr e2 `thenM` \ (e2', fv_e2) ->
138 rnLExpr op `thenM` \ (op'@(L _ (HsVar op_name)), fv_op) ->
141 -- When renaming code synthesised from "deriving" declarations
142 -- we used to avoid fixity stuff, but we can't easily tell any
143 -- more, so I've removed the test. Adding HsPars in TcGenDeriv
144 -- should prevent bad things happening.
145 lookupFixityRn op_name `thenM` \ fixity ->
146 mkOpAppRn e1' op' fixity e2' `thenM` \ final_e ->
149 fv_e1 `plusFV` fv_op `plusFV` fv_e2)
152 = rnLExpr e `thenM` \ (e', fv_e) ->
153 lookupSyntaxName negateName `thenM` \ (neg_name, fv_neg) ->
154 mkNegAppRn e' neg_name `thenM` \ final_e ->
155 returnM (final_e, fv_e `plusFV` fv_neg)
158 = rnLExpr e `thenM` \ (e', fvs_e) ->
159 returnM (HsPar e', fvs_e)
161 -- Template Haskell extensions
162 -- Don't ifdef-GHCI them because we want to fail gracefully
163 -- (not with an rnExpr crash) in a stage-1 compiler.
164 rnExpr e@(HsBracket br_body)
165 = checkTH e "bracket" `thenM_`
166 rnBracket br_body `thenM` \ (body', fvs_e) ->
167 returnM (HsBracket body', fvs_e)
169 rnExpr e@(HsSpliceE splice)
170 = rnSplice splice `thenM` \ (splice', fvs) ->
171 returnM (HsSpliceE splice', fvs)
173 rnExpr section@(SectionL expr op)
174 = rnLExpr expr `thenM` \ (expr', fvs_expr) ->
175 rnLExpr op `thenM` \ (op', fvs_op) ->
176 checkSectionPrec InfixL section op' expr' `thenM_`
177 returnM (SectionL expr' op', fvs_op `plusFV` fvs_expr)
179 rnExpr section@(SectionR op expr)
180 = rnLExpr op `thenM` \ (op', fvs_op) ->
181 rnLExpr expr `thenM` \ (expr', fvs_expr) ->
182 checkSectionPrec InfixR section op' expr' `thenM_`
183 returnM (SectionR op' expr', fvs_op `plusFV` fvs_expr)
185 rnExpr (HsCoreAnn ann expr)
186 = rnLExpr expr `thenM` \ (expr', fvs_expr) ->
187 returnM (HsCoreAnn ann expr', fvs_expr)
189 rnExpr (HsSCC lbl expr)
190 = rnLExpr expr `thenM` \ (expr', fvs_expr) ->
191 returnM (HsSCC lbl expr', fvs_expr)
192 rnExpr (HsTickPragma info expr)
193 = rnLExpr expr `thenM` \ (expr', fvs_expr) ->
194 returnM (HsTickPragma info expr', fvs_expr)
196 rnExpr (HsLam matches)
197 = rnMatchGroup LambdaExpr matches `thenM` \ (matches', fvMatch) ->
198 returnM (HsLam matches', fvMatch)
200 rnExpr (HsCase expr matches)
201 = rnLExpr expr `thenM` \ (new_expr, e_fvs) ->
202 rnMatchGroup CaseAlt matches `thenM` \ (new_matches, ms_fvs) ->
203 returnM (HsCase new_expr new_matches, e_fvs `plusFV` ms_fvs)
205 rnExpr (HsLet binds expr)
206 = rnLocalBindsAndThen binds $ \ binds' ->
207 rnLExpr expr `thenM` \ (expr',fvExpr) ->
208 returnM (HsLet binds' expr', fvExpr)
210 rnExpr e@(HsDo do_or_lc stmts body _)
211 = do { ((stmts', body'), fvs) <- rnStmts do_or_lc stmts $
213 ; return (HsDo do_or_lc stmts' body' placeHolderType, fvs) }
215 rnExpr (ExplicitList _ exps)
216 = rnExprs exps `thenM` \ (exps', fvs) ->
217 returnM (ExplicitList placeHolderType exps', fvs `addOneFV` listTyCon_name)
219 rnExpr (ExplicitPArr _ exps)
220 = rnExprs exps `thenM` \ (exps', fvs) ->
221 returnM (ExplicitPArr placeHolderType exps', fvs)
223 rnExpr e@(ExplicitTuple exps boxity)
224 = checkTupSize tup_size `thenM_`
225 rnExprs exps `thenM` \ (exps', fvs) ->
226 returnM (ExplicitTuple exps' boxity, fvs `addOneFV` tycon_name)
228 tup_size = length exps
229 tycon_name = tupleTyCon_name boxity tup_size
231 rnExpr (RecordCon con_id _ (HsRecordBinds rbinds))
232 = lookupLocatedOccRn con_id `thenM` \ conname ->
233 rnRbinds "construction" rbinds `thenM` \ (rbinds', fvRbinds) ->
234 returnM (RecordCon conname noPostTcExpr (HsRecordBinds rbinds'),
235 fvRbinds `addOneFV` unLoc conname)
237 rnExpr (RecordUpd expr (HsRecordBinds rbinds) _ _)
238 = rnLExpr expr `thenM` \ (expr', fvExpr) ->
239 rnRbinds "update" rbinds `thenM` \ (rbinds', fvRbinds) ->
240 returnM (RecordUpd expr' (HsRecordBinds rbinds') placeHolderType placeHolderType,
241 fvExpr `plusFV` fvRbinds)
243 rnExpr (ExprWithTySig expr pty)
244 = do { (pty', fvTy) <- rnHsTypeFVs doc pty
245 ; (expr', fvExpr) <- bindSigTyVarsFV (hsExplicitTvs pty') $
247 ; return (ExprWithTySig expr' pty', fvExpr `plusFV` fvTy) }
249 doc = text "In an expression type signature"
251 rnExpr (HsIf p b1 b2)
252 = rnLExpr p `thenM` \ (p', fvP) ->
253 rnLExpr b1 `thenM` \ (b1', fvB1) ->
254 rnLExpr b2 `thenM` \ (b2', fvB2) ->
255 returnM (HsIf p' b1' b2', plusFVs [fvP, fvB1, fvB2])
258 = rnHsTypeFVs doc a `thenM` \ (t, fvT) ->
259 returnM (HsType t, fvT)
261 doc = text "In a type argument"
263 rnExpr (ArithSeq _ seq)
264 = rnArithSeq seq `thenM` \ (new_seq, fvs) ->
265 returnM (ArithSeq noPostTcExpr new_seq, fvs)
267 rnExpr (PArrSeq _ seq)
268 = rnArithSeq seq `thenM` \ (new_seq, fvs) ->
269 returnM (PArrSeq noPostTcExpr new_seq, fvs)
272 These three are pattern syntax appearing in expressions.
273 Since all the symbols are reservedops we can simply reject them.
274 We return a (bogus) EWildPat in each case.
277 rnExpr e@EWildPat = patSynErr e
278 rnExpr e@(EAsPat {}) = patSynErr e
279 rnExpr e@(ELazyPat {}) = patSynErr e
282 %************************************************************************
286 %************************************************************************
289 rnExpr (HsProc pat body)
291 rnPatsAndThen ProcExpr [pat] $ \ [pat'] ->
292 rnCmdTop body `thenM` \ (body',fvBody) ->
293 returnM (HsProc pat' body', fvBody)
295 rnExpr (HsArrApp arrow arg _ ho rtl)
296 = select_arrow_scope (rnLExpr arrow) `thenM` \ (arrow',fvArrow) ->
297 rnLExpr arg `thenM` \ (arg',fvArg) ->
298 returnM (HsArrApp arrow' arg' placeHolderType ho rtl,
299 fvArrow `plusFV` fvArg)
301 select_arrow_scope tc = case ho of
302 HsHigherOrderApp -> tc
303 HsFirstOrderApp -> escapeArrowScope tc
306 rnExpr (HsArrForm op (Just _) [arg1, arg2])
307 = escapeArrowScope (rnLExpr op)
308 `thenM` \ (op'@(L _ (HsVar op_name)),fv_op) ->
309 rnCmdTop arg1 `thenM` \ (arg1',fv_arg1) ->
310 rnCmdTop arg2 `thenM` \ (arg2',fv_arg2) ->
314 lookupFixityRn op_name `thenM` \ fixity ->
315 mkOpFormRn arg1' op' fixity arg2' `thenM` \ final_e ->
318 fv_arg1 `plusFV` fv_op `plusFV` fv_arg2)
320 rnExpr (HsArrForm op fixity cmds)
321 = escapeArrowScope (rnLExpr op) `thenM` \ (op',fvOp) ->
322 rnCmdArgs cmds `thenM` \ (cmds',fvCmds) ->
323 returnM (HsArrForm op' fixity cmds', fvOp `plusFV` fvCmds)
325 rnExpr other = pprPanic "rnExpr: unexpected expression" (ppr other)
330 %************************************************************************
334 %************************************************************************
337 rnCmdArgs [] = returnM ([], emptyFVs)
339 = rnCmdTop arg `thenM` \ (arg',fvArg) ->
340 rnCmdArgs args `thenM` \ (args',fvArgs) ->
341 returnM (arg':args', fvArg `plusFV` fvArgs)
344 rnCmdTop = wrapLocFstM rnCmdTop'
346 rnCmdTop' (HsCmdTop cmd _ _ _)
347 = rnLExpr (convertOpFormsLCmd cmd) `thenM` \ (cmd', fvCmd) ->
349 cmd_names = [arrAName, composeAName, firstAName] ++
350 nameSetToList (methodNamesCmd (unLoc cmd'))
352 -- Generate the rebindable syntax for the monad
353 lookupSyntaxTable cmd_names `thenM` \ (cmd_names', cmd_fvs) ->
355 returnM (HsCmdTop cmd' [] placeHolderType cmd_names',
356 fvCmd `plusFV` cmd_fvs)
358 ---------------------------------------------------
359 -- convert OpApp's in a command context to HsArrForm's
361 convertOpFormsLCmd :: LHsCmd id -> LHsCmd id
362 convertOpFormsLCmd = fmap convertOpFormsCmd
364 convertOpFormsCmd :: HsCmd id -> HsCmd id
366 convertOpFormsCmd (HsApp c e) = HsApp (convertOpFormsLCmd c) e
367 convertOpFormsCmd (HsLam match) = HsLam (convertOpFormsMatch match)
368 convertOpFormsCmd (OpApp c1 op fixity c2)
370 arg1 = L (getLoc c1) $ HsCmdTop (convertOpFormsLCmd c1) [] placeHolderType []
371 arg2 = L (getLoc c2) $ HsCmdTop (convertOpFormsLCmd c2) [] placeHolderType []
373 HsArrForm op (Just fixity) [arg1, arg2]
375 convertOpFormsCmd (HsPar c) = HsPar (convertOpFormsLCmd c)
378 convertOpFormsCmd (HsCase exp matches)
379 = HsCase exp (convertOpFormsMatch matches)
381 convertOpFormsCmd (HsIf exp c1 c2)
382 = HsIf exp (convertOpFormsLCmd c1) (convertOpFormsLCmd c2)
384 convertOpFormsCmd (HsLet binds cmd)
385 = HsLet binds (convertOpFormsLCmd cmd)
387 convertOpFormsCmd (HsDo ctxt stmts body ty)
388 = HsDo ctxt (map (fmap convertOpFormsStmt) stmts)
389 (convertOpFormsLCmd body) ty
391 -- Anything else is unchanged. This includes HsArrForm (already done),
392 -- things with no sub-commands, and illegal commands (which will be
393 -- caught by the type checker)
394 convertOpFormsCmd c = c
396 convertOpFormsStmt (BindStmt pat cmd _ _)
397 = BindStmt pat (convertOpFormsLCmd cmd) noSyntaxExpr noSyntaxExpr
398 convertOpFormsStmt (ExprStmt cmd _ _)
399 = ExprStmt (convertOpFormsLCmd cmd) noSyntaxExpr placeHolderType
400 convertOpFormsStmt (RecStmt stmts lvs rvs es binds)
401 = RecStmt (map (fmap convertOpFormsStmt) stmts) lvs rvs es binds
402 convertOpFormsStmt stmt = stmt
404 convertOpFormsMatch (MatchGroup ms ty)
405 = MatchGroup (map (fmap convert) ms) ty
406 where convert (Match pat mty grhss)
407 = Match pat mty (convertOpFormsGRHSs grhss)
409 convertOpFormsGRHSs (GRHSs grhss binds)
410 = GRHSs (map convertOpFormsGRHS grhss) binds
412 convertOpFormsGRHS = fmap convert
414 convert (GRHS stmts cmd) = GRHS stmts (convertOpFormsLCmd cmd)
416 ---------------------------------------------------
417 type CmdNeeds = FreeVars -- Only inhabitants are
418 -- appAName, choiceAName, loopAName
420 -- find what methods the Cmd needs (loop, choice, apply)
421 methodNamesLCmd :: LHsCmd Name -> CmdNeeds
422 methodNamesLCmd = methodNamesCmd . unLoc
424 methodNamesCmd :: HsCmd Name -> CmdNeeds
426 methodNamesCmd cmd@(HsArrApp _arrow _arg _ HsFirstOrderApp _rtl)
428 methodNamesCmd cmd@(HsArrApp _arrow _arg _ HsHigherOrderApp _rtl)
430 methodNamesCmd cmd@(HsArrForm {}) = emptyFVs
432 methodNamesCmd (HsPar c) = methodNamesLCmd c
434 methodNamesCmd (HsIf p c1 c2)
435 = methodNamesLCmd c1 `plusFV` methodNamesLCmd c2 `addOneFV` choiceAName
437 methodNamesCmd (HsLet b c) = methodNamesLCmd c
439 methodNamesCmd (HsDo sc stmts body ty)
440 = methodNamesStmts stmts `plusFV` methodNamesLCmd body
442 methodNamesCmd (HsApp c e) = methodNamesLCmd c
444 methodNamesCmd (HsLam match) = methodNamesMatch match
446 methodNamesCmd (HsCase scrut matches)
447 = methodNamesMatch matches `addOneFV` choiceAName
449 methodNamesCmd other = emptyFVs
450 -- Other forms can't occur in commands, but it's not convenient
451 -- to error here so we just do what's convenient.
452 -- The type checker will complain later
454 ---------------------------------------------------
455 methodNamesMatch (MatchGroup ms _)
456 = plusFVs (map do_one ms)
458 do_one (L _ (Match pats sig_ty grhss)) = methodNamesGRHSs grhss
460 -------------------------------------------------
462 methodNamesGRHSs (GRHSs grhss binds) = plusFVs (map methodNamesGRHS grhss)
464 -------------------------------------------------
465 methodNamesGRHS (L _ (GRHS stmts rhs)) = methodNamesLCmd rhs
467 ---------------------------------------------------
468 methodNamesStmts stmts = plusFVs (map methodNamesLStmt stmts)
470 ---------------------------------------------------
471 methodNamesLStmt = methodNamesStmt . unLoc
473 methodNamesStmt (ExprStmt cmd _ _) = methodNamesLCmd cmd
474 methodNamesStmt (BindStmt pat cmd _ _) = methodNamesLCmd cmd
475 methodNamesStmt (RecStmt stmts _ _ _ _)
476 = methodNamesStmts stmts `addOneFV` loopAName
477 methodNamesStmt (LetStmt b) = emptyFVs
478 methodNamesStmt (ParStmt ss) = emptyFVs
479 -- ParStmt can't occur in commands, but it's not convenient to error
480 -- here so we just do what's convenient
484 %************************************************************************
488 %************************************************************************
491 rnArithSeq (From expr)
492 = rnLExpr expr `thenM` \ (expr', fvExpr) ->
493 returnM (From expr', fvExpr)
495 rnArithSeq (FromThen expr1 expr2)
496 = rnLExpr expr1 `thenM` \ (expr1', fvExpr1) ->
497 rnLExpr expr2 `thenM` \ (expr2', fvExpr2) ->
498 returnM (FromThen expr1' expr2', fvExpr1 `plusFV` fvExpr2)
500 rnArithSeq (FromTo expr1 expr2)
501 = rnLExpr expr1 `thenM` \ (expr1', fvExpr1) ->
502 rnLExpr expr2 `thenM` \ (expr2', fvExpr2) ->
503 returnM (FromTo expr1' expr2', fvExpr1 `plusFV` fvExpr2)
505 rnArithSeq (FromThenTo expr1 expr2 expr3)
506 = rnLExpr expr1 `thenM` \ (expr1', fvExpr1) ->
507 rnLExpr expr2 `thenM` \ (expr2', fvExpr2) ->
508 rnLExpr expr3 `thenM` \ (expr3', fvExpr3) ->
509 returnM (FromThenTo expr1' expr2' expr3',
510 plusFVs [fvExpr1, fvExpr2, fvExpr3])
514 %************************************************************************
516 \subsubsection{@Rbinds@s and @Rpats@s: in record expressions}
518 %************************************************************************
522 = mappM_ field_dup_err dup_fields `thenM_`
523 mapFvRn rn_rbind rbinds `thenM` \ (rbinds', fvRbind) ->
524 returnM (rbinds', fvRbind)
526 (_, dup_fields) = removeDups cmpLocated [ f | (f,_) <- rbinds ]
528 field_dup_err dups = mappM_ (\f -> addLocErr f (dupFieldErr str)) dups
530 rn_rbind (field, expr)
531 = lookupLocatedGlobalOccRn field `thenM` \ fieldname ->
532 rnLExpr expr `thenM` \ (expr', fvExpr) ->
533 returnM ((fieldname, expr'), fvExpr `addOneFV` unLoc fieldname)
536 %************************************************************************
538 Template Haskell brackets
540 %************************************************************************
543 rnBracket (VarBr n) = do { name <- lookupOccRn n
544 ; this_mod <- getModule
545 ; checkM (nameIsLocalOrFrom this_mod name) $ -- Reason: deprecation checking asumes the
546 do { loadInterfaceForName msg name -- home interface is loaded, and this is the
547 ; return () } -- only way that is going to happen
548 ; returnM (VarBr name, unitFV name) }
550 msg = ptext SLIT("Need interface for Template Haskell quoted Name")
552 rnBracket (ExpBr e) = do { (e', fvs) <- rnLExpr e
553 ; return (ExpBr e', fvs) }
554 rnBracket (PatBr p) = do { (p', fvs) <- rnLPat p
555 ; return (PatBr p', fvs) }
556 rnBracket (TypBr t) = do { (t', fvs) <- rnHsTypeFVs doc t
557 ; return (TypBr t', fvs) }
559 doc = ptext SLIT("In a Template-Haskell quoted type")
560 rnBracket (DecBr group)
561 = do { gbl_env <- getGblEnv
563 ; let gbl_env1 = gbl_env { tcg_mod = thFAKE }
564 -- Note the thFAKE. The top-level names from the bracketed
565 -- declarations will go into the name cache, and we don't want them to
566 -- confuse the Names for the current module.
567 -- By using a pretend module, thFAKE, we keep them safely out of the way.
569 ; avails <- getLocalDeclBinders gbl_env1 group
570 ; let names = concatMap availNames avails
572 ; let new_occs = map nameOccName names
573 trimmed_rdr_env = hideSomeUnquals (tcg_rdr_env gbl_env) new_occs
575 ; rdr_env' <- extendRdrEnvRn trimmed_rdr_env avails
576 -- In this situation we want to *shadow* top-level bindings.
578 -- bar = [d| foo = 1|]
579 -- If we don't shadow, we'll get an ambiguity complaint when we do
580 -- a lookupTopBndrRn (which uses lookupGreLocalRn) on the binder of the 'foo'
582 -- Furthermore, arguably if the splice does define foo, that should hide
583 -- any foo's further out
585 -- The shadowing is acheived by the call to hideSomeUnquals, which removes
586 -- the unqualified bindings of things defined by the bracket
588 ; setGblEnv (gbl_env { tcg_rdr_env = rdr_env',
589 tcg_dus = emptyDUs }) $ do
590 -- The emptyDUs is so that we just collect uses for this group alone
592 { (tcg_env, group') <- rnSrcDecls group
593 -- Discard the tcg_env; it contains only extra info about fixity
594 ; return (DecBr group', allUses (tcg_dus tcg_env)) } }
597 %************************************************************************
599 \subsubsection{@Stmt@s: in @do@ expressions}
601 %************************************************************************
604 rnStmts :: HsStmtContext Name -> [LStmt RdrName]
605 -> RnM (thing, FreeVars)
606 -> RnM (([LStmt Name], thing), FreeVars)
608 rnStmts (MDoExpr _) = rnMDoStmts
609 rnStmts ctxt = rnNormalStmts ctxt
611 rnNormalStmts :: HsStmtContext Name -> [LStmt RdrName]
612 -> RnM (thing, FreeVars)
613 -> RnM (([LStmt Name], thing), FreeVars)
614 -- Used for cases *other* than recursive mdo
615 -- Implements nested scopes
617 rnNormalStmts ctxt [] thing_inside
618 = do { (thing, fvs) <- thing_inside
619 ; return (([],thing), fvs) }
621 rnNormalStmts ctxt (L loc stmt : stmts) thing_inside
622 = do { ((stmt', (stmts', thing)), fvs)
623 <- rnStmt ctxt stmt $
624 rnNormalStmts ctxt stmts thing_inside
625 ; return (((L loc stmt' : stmts'), thing), fvs) }
627 rnStmt :: HsStmtContext Name -> Stmt RdrName
628 -> RnM (thing, FreeVars)
629 -> RnM ((Stmt Name, thing), FreeVars)
631 rnStmt ctxt (ExprStmt expr _ _) thing_inside
632 = do { (expr', fv_expr) <- rnLExpr expr
633 ; (then_op, fvs1) <- lookupSyntaxName thenMName
634 ; (thing, fvs2) <- thing_inside
635 ; return ((ExprStmt expr' then_op placeHolderType, thing),
636 fv_expr `plusFV` fvs1 `plusFV` fvs2) }
638 rnStmt ctxt (BindStmt pat expr _ _) thing_inside
639 = do { (expr', fv_expr) <- rnLExpr expr
640 -- The binders do not scope over the expression
641 ; (bind_op, fvs1) <- lookupSyntaxName bindMName
642 ; (fail_op, fvs2) <- lookupSyntaxName failMName
643 ; rnPatsAndThen (StmtCtxt ctxt) [pat] $ \ [pat'] -> do
644 { (thing, fvs3) <- thing_inside
645 ; return ((BindStmt pat' expr' bind_op fail_op, thing),
646 fv_expr `plusFV` fvs1 `plusFV` fvs2 `plusFV` fvs3) }}
647 -- fv_expr shouldn't really be filtered by the rnPatsAndThen
648 -- but it does not matter because the names are unique
650 rnStmt ctxt (LetStmt binds) thing_inside
651 = do { checkErr (ok ctxt binds)
652 (badIpBinds (ptext SLIT("a parallel list comprehension:")) binds)
653 ; rnLocalBindsAndThen binds $ \ binds' -> do
654 { (thing, fvs) <- thing_inside
655 ; return ((LetStmt binds', thing), fvs) }}
657 -- We do not allow implicit-parameter bindings in a parallel
658 -- list comprehension. I'm not sure what it might mean.
659 ok (ParStmtCtxt _) (HsIPBinds _) = False
662 rnStmt ctxt (RecStmt rec_stmts _ _ _ _) thing_inside
663 = bindLocatedLocalsRn doc (collectLStmtsBinders rec_stmts) $ \ bndrs ->
664 rn_rec_stmts bndrs rec_stmts `thenM` \ segs ->
665 thing_inside `thenM` \ (thing, fvs) ->
667 segs_w_fwd_refs = addFwdRefs segs
668 (ds, us, fs, rec_stmts') = unzip4 segs_w_fwd_refs
669 later_vars = nameSetToList (plusFVs ds `intersectNameSet` fvs)
670 fwd_vars = nameSetToList (plusFVs fs)
672 rec_stmt = RecStmt rec_stmts' later_vars fwd_vars [] emptyLHsBinds
674 returnM ((rec_stmt, thing), uses `plusFV` fvs)
676 doc = text "In a recursive do statement"
678 rnStmt ctxt (ParStmt segs) thing_inside
679 = do { opt_GlasgowExts <- doptM Opt_GlasgowExts
680 ; checkM opt_GlasgowExts parStmtErr
681 ; orig_lcl_env <- getLocalRdrEnv
682 ; ((segs',thing), fvs) <- go orig_lcl_env [] segs
683 ; return ((ParStmt segs', thing), fvs) }
685 -- type ParSeg id = [([LStmt id], [id])]
686 -- go :: NameSet -> [ParSeg RdrName]
687 -- -> RnM (([ParSeg Name], thing), FreeVars)
689 go orig_lcl_env bndrs []
690 = do { let { (bndrs', dups) = removeDups cmpByOcc bndrs
691 ; inner_env = extendLocalRdrEnv orig_lcl_env bndrs' }
693 ; (thing, fvs) <- setLocalRdrEnv inner_env thing_inside
694 ; return (([], thing), fvs) }
696 go orig_lcl_env bndrs_so_far ((stmts, _) : segs)
697 = do { ((stmts', (bndrs, segs', thing)), fvs)
698 <- rnNormalStmts par_ctxt stmts $ do
699 { -- Find the Names that are bound by stmts
700 lcl_env <- getLocalRdrEnv
701 ; let { rdr_bndrs = collectLStmtsBinders stmts
702 ; bndrs = map ( expectJust "rnStmt"
703 . lookupLocalRdrEnv lcl_env
705 ; new_bndrs = nub bndrs ++ bndrs_so_far
706 -- The nub is because there might be shadowing
708 -- So we'll look up (Unqual x) twice, getting
709 -- the second binding both times, which is the
712 -- Typecheck the thing inside, passing on all
713 -- the Names bound, but separately; revert the envt
714 ; ((segs', thing), fvs) <- setLocalRdrEnv orig_lcl_env $
715 go orig_lcl_env new_bndrs segs
717 -- Figure out which of the bound names are used
718 ; let used_bndrs = filter (`elemNameSet` fvs) bndrs
719 ; return ((used_bndrs, segs', thing), fvs) }
721 ; let seg' = (stmts', bndrs)
722 ; return (((seg':segs'), thing),
723 delListFromNameSet fvs bndrs) }
725 par_ctxt = ParStmtCtxt ctxt
727 cmpByOcc n1 n2 = nameOccName n1 `compare` nameOccName n2
728 dupErr vs = addErr (ptext SLIT("Duplicate binding in parallel list comprehension for:")
729 <+> quotes (ppr (head vs)))
733 %************************************************************************
735 \subsubsection{mdo expressions}
737 %************************************************************************
740 type FwdRefs = NameSet
741 type Segment stmts = (Defs,
742 Uses, -- May include defs
743 FwdRefs, -- A subset of uses that are
744 -- (a) used before they are bound in this segment, or
745 -- (b) used here, and bound in subsequent segments
746 stmts) -- Either Stmt or [Stmt]
749 ----------------------------------------------------
750 rnMDoStmts :: [LStmt RdrName]
751 -> RnM (thing, FreeVars)
752 -> RnM (([LStmt Name], thing), FreeVars)
753 rnMDoStmts stmts thing_inside
754 = -- Step1: bring all the binders of the mdo into scope
755 -- Remember that this also removes the binders from the
756 -- finally-returned free-vars
757 bindLocatedLocalsRn doc (collectLStmtsBinders stmts) $ \ bndrs ->
759 -- Step 2: Rename each individual stmt, making a
760 -- singleton segment. At this stage the FwdRefs field
761 -- isn't finished: it's empty for all except a BindStmt
762 -- for which it's the fwd refs within the bind itself
763 -- (This set may not be empty, because we're in a recursive
765 segs <- rn_rec_stmts bndrs stmts
767 ; (thing, fvs_later) <- thing_inside
770 -- Step 3: Fill in the fwd refs.
771 -- The segments are all singletons, but their fwd-ref
772 -- field mentions all the things used by the segment
773 -- that are bound after their use
774 segs_w_fwd_refs = addFwdRefs segs
776 -- Step 4: Group together the segments to make bigger segments
777 -- Invariant: in the result, no segment uses a variable
778 -- bound in a later segment
779 grouped_segs = glomSegments segs_w_fwd_refs
781 -- Step 5: Turn the segments into Stmts
782 -- Use RecStmt when and only when there are fwd refs
783 -- Also gather up the uses from the end towards the
784 -- start, so we can tell the RecStmt which things are
785 -- used 'after' the RecStmt
786 (stmts', fvs) = segsToStmts grouped_segs fvs_later
788 ; return ((stmts', thing), fvs) }
790 doc = text "In a recursive mdo-expression"
792 ---------------------------------------------
793 rn_rec_stmts :: [Name] -> [LStmt RdrName] -> RnM [Segment (LStmt Name)]
794 rn_rec_stmts bndrs stmts = mappM (rn_rec_stmt bndrs) stmts `thenM` \ segs_s ->
795 returnM (concat segs_s)
797 ----------------------------------------------------
798 rn_rec_stmt :: [Name] -> LStmt RdrName -> RnM [Segment (LStmt Name)]
799 -- Rename a Stmt that is inside a RecStmt (or mdo)
800 -- Assumes all binders are already in scope
801 -- Turns each stmt into a singleton Stmt
803 rn_rec_stmt all_bndrs (L loc (ExprStmt expr _ _))
804 = rnLExpr expr `thenM` \ (expr', fvs) ->
805 lookupSyntaxName thenMName `thenM` \ (then_op, fvs1) ->
806 returnM [(emptyNameSet, fvs `plusFV` fvs1, emptyNameSet,
807 L loc (ExprStmt expr' then_op placeHolderType))]
809 rn_rec_stmt all_bndrs (L loc (BindStmt pat expr _ _))
810 = rnLExpr expr `thenM` \ (expr', fv_expr) ->
811 rnLPat pat `thenM` \ (pat', fv_pat) ->
812 lookupSyntaxName bindMName `thenM` \ (bind_op, fvs1) ->
813 lookupSyntaxName failMName `thenM` \ (fail_op, fvs2) ->
815 bndrs = mkNameSet (collectPatBinders pat')
816 fvs = fv_expr `plusFV` fv_pat `plusFV` fvs1 `plusFV` fvs2
818 returnM [(bndrs, fvs, bndrs `intersectNameSet` fvs,
819 L loc (BindStmt pat' expr' bind_op fail_op))]
821 rn_rec_stmt all_bndrs (L loc (LetStmt binds@(HsIPBinds _)))
822 = do { addErr (badIpBinds (ptext SLIT("an mdo expression")) binds)
825 rn_rec_stmt all_bndrs (L loc (LetStmt (HsValBinds binds)))
826 = rnValBinds (trimWith all_bndrs) binds `thenM` \ (binds', du_binds) ->
827 returnM [(duDefs du_binds, duUses du_binds,
828 emptyNameSet, L loc (LetStmt (HsValBinds binds')))]
830 rn_rec_stmt all_bndrs (L loc (RecStmt stmts _ _ _ _)) -- Flatten Rec inside Rec
831 = rn_rec_stmts all_bndrs stmts
833 rn_rec_stmt all_bndrs stmt@(L _ (ParStmt _)) -- Syntactically illegal in mdo
834 = pprPanic "rn_rec_stmt" (ppr stmt)
836 ---------------------------------------------
837 addFwdRefs :: [Segment a] -> [Segment a]
838 -- So far the segments only have forward refs *within* the Stmt
839 -- (which happens for bind: x <- ...x...)
840 -- This function adds the cross-seg fwd ref info
843 = fst (foldr mk_seg ([], emptyNameSet) pairs)
845 mk_seg (defs, uses, fwds, stmts) (segs, later_defs)
846 = (new_seg : segs, all_defs)
848 new_seg = (defs, uses, new_fwds, stmts)
849 all_defs = later_defs `unionNameSets` defs
850 new_fwds = fwds `unionNameSets` (uses `intersectNameSet` later_defs)
851 -- Add the downstream fwd refs here
853 ----------------------------------------------------
854 -- Glomming the singleton segments of an mdo into
855 -- minimal recursive groups.
857 -- At first I thought this was just strongly connected components, but
858 -- there's an important constraint: the order of the stmts must not change.
861 -- mdo { x <- ...y...
868 -- Here, the first stmt mention 'y', which is bound in the third.
869 -- But that means that the innocent second stmt (p <- z) gets caught
870 -- up in the recursion. And that in turn means that the binding for
871 -- 'z' has to be included... and so on.
873 -- Start at the tail { r <- x }
874 -- Now add the next one { z <- y ; r <- x }
875 -- Now add one more { q <- x ; z <- y ; r <- x }
876 -- Now one more... but this time we have to group a bunch into rec
877 -- { rec { y <- ...x... ; q <- x ; z <- y } ; r <- x }
878 -- Now one more, which we can add on without a rec
880 -- rec { y <- ...x... ; q <- x ; z <- y } ;
882 -- Finally we add the last one; since it mentions y we have to
883 -- glom it togeher with the first two groups
884 -- { rec { x <- ...y...; p <- z ; y <- ...x... ;
885 -- q <- x ; z <- y } ;
888 glomSegments :: [Segment (LStmt Name)] -> [Segment [LStmt Name]]
891 glomSegments ((defs,uses,fwds,stmt) : segs)
892 -- Actually stmts will always be a singleton
893 = (seg_defs, seg_uses, seg_fwds, seg_stmts) : others
895 segs' = glomSegments segs
896 (extras, others) = grab uses segs'
897 (ds, us, fs, ss) = unzip4 extras
899 seg_defs = plusFVs ds `plusFV` defs
900 seg_uses = plusFVs us `plusFV` uses
901 seg_fwds = plusFVs fs `plusFV` fwds
902 seg_stmts = stmt : concat ss
904 grab :: NameSet -- The client
906 -> ([Segment a], -- Needed by the 'client'
907 [Segment a]) -- Not needed by the client
908 -- The result is simply a split of the input
910 = (reverse yeses, reverse noes)
912 (noes, yeses) = span not_needed (reverse dus)
913 not_needed (defs,_,_,_) = not (intersectsNameSet defs uses)
916 ----------------------------------------------------
917 segsToStmts :: [Segment [LStmt Name]]
918 -> FreeVars -- Free vars used 'later'
919 -> ([LStmt Name], FreeVars)
921 segsToStmts [] fvs_later = ([], fvs_later)
922 segsToStmts ((defs, uses, fwds, ss) : segs) fvs_later
923 = ASSERT( not (null ss) )
924 (new_stmt : later_stmts, later_uses `plusFV` uses)
926 (later_stmts, later_uses) = segsToStmts segs fvs_later
927 new_stmt | non_rec = head ss
928 | otherwise = L (getLoc (head ss)) $
929 RecStmt ss (nameSetToList used_later) (nameSetToList fwds)
932 non_rec = isSingleton ss && isEmptyNameSet fwds
933 used_later = defs `intersectNameSet` later_uses
934 -- The ones needed after the RecStmt
937 %************************************************************************
939 \subsubsection{Assertion utils}
941 %************************************************************************
944 srcSpanPrimLit :: SrcSpan -> HsExpr Name
945 srcSpanPrimLit span = HsLit (HsStringPrim (mkFastString (showSDoc (ppr span))))
947 mkAssertErrorExpr :: RnM (HsExpr Name, FreeVars)
948 -- Return an expression for (assertError "Foo.hs:27")
950 = getSrcSpanM `thenM` \ sloc ->
952 expr = HsApp (L sloc (HsVar assertErrorName))
953 (L sloc (srcSpanPrimLit sloc))
955 returnM (expr, emptyFVs)
958 %************************************************************************
960 \subsubsection{Errors}
962 %************************************************************************
965 patSynErr e = do { addErr (sep [ptext SLIT("Pattern syntax in expression context:"),
967 ; return (EWildPat, emptyFVs) }
969 parStmtErr = addErr (ptext SLIT("Illegal parallel list comprehension: use -fglasgow-exts"))
971 badIpBinds what binds
972 = hang (ptext SLIT("Implicit-parameter bindings illegal in") <+> what)