vectorise: Put it out of its misery
[ghc.git] / compiler / rename / RnExpr.hs
1 {-
2 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3
4 \section[RnExpr]{Renaming of expressions}
5
6 Basically dependency analysis.
7
8 Handles @Match@, @GRHSs@, @HsExpr@, and @Qualifier@ datatypes. In
9 general, all of these functions return a renamed thing, and a set of
10 free variables.
11 -}
12
13 {-# LANGUAGE CPP #-}
14 {-# LANGUAGE ScopedTypeVariables #-}
15 {-# LANGUAGE MultiWayIf #-}
16 {-# LANGUAGE TypeFamilies #-}
17
18 module RnExpr (
19 rnLExpr, rnExpr, rnStmts
20 ) where
21
22 #include "HsVersions.h"
23
24 import GhcPrelude
25
26 import RnBinds ( rnLocalBindsAndThen, rnLocalValBindsLHS, rnLocalValBindsRHS,
27 rnMatchGroup, rnGRHS, makeMiniFixityEnv)
28 import HsSyn
29 import TcRnMonad
30 import Module ( getModule )
31 import RnEnv
32 import RnFixity
33 import RnUtils ( HsDocContext(..), bindLocalNamesFV, checkDupNames
34 , bindLocalNames
35 , mapMaybeFvRn, mapFvRn
36 , warnUnusedLocalBinds )
37 import RnUnbound ( reportUnboundName )
38 import RnSplice ( rnBracket, rnSpliceExpr, checkThLocalName )
39 import RnTypes
40 import RnPat
41 import DynFlags
42 import PrelNames
43
44 import BasicTypes
45 import Name
46 import NameSet
47 import RdrName
48 import UniqSet
49 import Data.List
50 import Util
51 import ListSetOps ( removeDups )
52 import ErrUtils
53 import Outputable
54 import SrcLoc
55 import FastString
56 import Control.Monad
57 import TysWiredIn ( nilDataConName )
58 import qualified GHC.LanguageExtensions as LangExt
59
60 import Data.Ord
61 import Data.Array
62 import qualified Data.List.NonEmpty as NE
63
64 {-
65 ************************************************************************
66 * *
67 \subsubsection{Expressions}
68 * *
69 ************************************************************************
70 -}
71
72 rnExprs :: [LHsExpr GhcPs] -> RnM ([LHsExpr GhcRn], FreeVars)
73 rnExprs ls = rnExprs' ls emptyUniqSet
74 where
75 rnExprs' [] acc = return ([], acc)
76 rnExprs' (expr:exprs) acc =
77 do { (expr', fvExpr) <- rnLExpr expr
78 -- Now we do a "seq" on the free vars because typically it's small
79 -- or empty, especially in very long lists of constants
80 ; let acc' = acc `plusFV` fvExpr
81 ; (exprs', fvExprs) <- acc' `seq` rnExprs' exprs acc'
82 ; return (expr':exprs', fvExprs) }
83
84 -- Variables. We look up the variable and return the resulting name.
85
86 rnLExpr :: LHsExpr GhcPs -> RnM (LHsExpr GhcRn, FreeVars)
87 rnLExpr = wrapLocFstM rnExpr
88
89 rnExpr :: HsExpr GhcPs -> RnM (HsExpr GhcRn, FreeVars)
90
91 finishHsVar :: Located Name -> RnM (HsExpr GhcRn, FreeVars)
92 -- Separated from rnExpr because it's also used
93 -- when renaming infix expressions
94 finishHsVar (L l name)
95 = do { this_mod <- getModule
96 ; when (nameIsLocalOrFrom this_mod name) $
97 checkThLocalName name
98 ; return (HsVar noExt (L l name), unitFV name) }
99
100 rnUnboundVar :: RdrName -> RnM (HsExpr GhcRn, FreeVars)
101 rnUnboundVar v
102 = do { if isUnqual v
103 then -- Treat this as a "hole"
104 -- Do not fail right now; instead, return HsUnboundVar
105 -- and let the type checker report the error
106 do { let occ = rdrNameOcc v
107 ; uv <- if startsWithUnderscore occ
108 then return (TrueExprHole occ)
109 else OutOfScope occ <$> getGlobalRdrEnv
110 ; return (HsUnboundVar noExt uv, emptyFVs) }
111
112 else -- Fail immediately (qualified name)
113 do { n <- reportUnboundName v
114 ; return (HsVar noExt (noLoc n), emptyFVs) } }
115
116 rnExpr (HsVar _ (L l v))
117 = do { opt_DuplicateRecordFields <- xoptM LangExt.DuplicateRecordFields
118 ; mb_name <- lookupOccRn_overloaded opt_DuplicateRecordFields v
119 ; case mb_name of {
120 Nothing -> rnUnboundVar v ;
121 Just (Left name)
122 | name == nilDataConName -- Treat [] as an ExplicitList, so that
123 -- OverloadedLists works correctly
124 -> rnExpr (ExplicitList noExt Nothing [])
125
126 | otherwise
127 -> finishHsVar (L l name) ;
128 Just (Right [s]) ->
129 return ( HsRecFld noExt (Unambiguous s (L l v) ), unitFV s) ;
130 Just (Right fs@(_:_:_)) ->
131 return ( HsRecFld noExt (Ambiguous noExt (L l v))
132 , mkFVs fs);
133 Just (Right []) -> panic "runExpr/HsVar" } }
134
135 rnExpr (HsIPVar x v)
136 = return (HsIPVar x v, emptyFVs)
137
138 rnExpr (HsOverLabel x _ v)
139 = do { rebindable_on <- xoptM LangExt.RebindableSyntax
140 ; if rebindable_on
141 then do { fromLabel <- lookupOccRn (mkVarUnqual (fsLit "fromLabel"))
142 ; return (HsOverLabel x (Just fromLabel) v, unitFV fromLabel) }
143 else return (HsOverLabel x Nothing v, emptyFVs) }
144
145 rnExpr (HsLit x lit@(HsString src s))
146 = do { opt_OverloadedStrings <- xoptM LangExt.OverloadedStrings
147 ; if opt_OverloadedStrings then
148 rnExpr (HsOverLit x (mkHsIsString src s))
149 else do {
150 ; rnLit lit
151 ; return (HsLit x (convertLit lit), emptyFVs) } }
152
153 rnExpr (HsLit x lit)
154 = do { rnLit lit
155 ; return (HsLit x(convertLit lit), emptyFVs) }
156
157 rnExpr (HsOverLit x lit)
158 = do { ((lit', mb_neg), fvs) <- rnOverLit lit -- See Note [Negative zero]
159 ; case mb_neg of
160 Nothing -> return (HsOverLit x lit', fvs)
161 Just neg -> return (HsApp x (noLoc neg) (noLoc (HsOverLit x lit'))
162 , fvs ) }
163
164 rnExpr (HsApp x fun arg)
165 = do { (fun',fvFun) <- rnLExpr fun
166 ; (arg',fvArg) <- rnLExpr arg
167 ; return (HsApp x fun' arg', fvFun `plusFV` fvArg) }
168
169 rnExpr (HsAppType arg fun)
170 = do { (fun',fvFun) <- rnLExpr fun
171 ; (arg',fvArg) <- rnHsWcType HsTypeCtx arg
172 ; return (HsAppType arg' fun', fvFun `plusFV` fvArg) }
173
174 rnExpr (OpApp _ e1 op e2)
175 = do { (e1', fv_e1) <- rnLExpr e1
176 ; (e2', fv_e2) <- rnLExpr e2
177 ; (op', fv_op) <- rnLExpr op
178
179 -- Deal with fixity
180 -- When renaming code synthesised from "deriving" declarations
181 -- we used to avoid fixity stuff, but we can't easily tell any
182 -- more, so I've removed the test. Adding HsPars in TcGenDeriv
183 -- should prevent bad things happening.
184 ; fixity <- case op' of
185 L _ (HsVar _ (L _ n)) -> lookupFixityRn n
186 L _ (HsRecFld _ f) -> lookupFieldFixityRn f
187 _ -> return (Fixity NoSourceText minPrecedence InfixL)
188 -- c.f. lookupFixity for unbound
189
190 ; final_e <- mkOpAppRn e1' op' fixity e2'
191 ; return (final_e, fv_e1 `plusFV` fv_op `plusFV` fv_e2) }
192
193 rnExpr (NegApp _ e _)
194 = do { (e', fv_e) <- rnLExpr e
195 ; (neg_name, fv_neg) <- lookupSyntaxName negateName
196 ; final_e <- mkNegAppRn e' neg_name
197 ; return (final_e, fv_e `plusFV` fv_neg) }
198
199 ------------------------------------------
200 -- Template Haskell extensions
201 -- Don't ifdef-GHCI them because we want to fail gracefully
202 -- (not with an rnExpr crash) in a stage-1 compiler.
203 rnExpr e@(HsBracket _ br_body) = rnBracket e br_body
204
205 rnExpr (HsSpliceE _ splice) = rnSpliceExpr splice
206
207 ---------------------------------------------
208 -- Sections
209 -- See Note [Parsing sections] in Parser.y
210 rnExpr (HsPar x (L loc (section@(SectionL {}))))
211 = do { (section', fvs) <- rnSection section
212 ; return (HsPar x (L loc section'), fvs) }
213
214 rnExpr (HsPar x (L loc (section@(SectionR {}))))
215 = do { (section', fvs) <- rnSection section
216 ; return (HsPar x (L loc section'), fvs) }
217
218 rnExpr (HsPar x e)
219 = do { (e', fvs_e) <- rnLExpr e
220 ; return (HsPar x e', fvs_e) }
221
222 rnExpr expr@(SectionL {})
223 = do { addErr (sectionErr expr); rnSection expr }
224 rnExpr expr@(SectionR {})
225 = do { addErr (sectionErr expr); rnSection expr }
226
227 ---------------------------------------------
228 rnExpr (HsCoreAnn x src ann expr)
229 = do { (expr', fvs_expr) <- rnLExpr expr
230 ; return (HsCoreAnn x src ann expr', fvs_expr) }
231
232 rnExpr (HsSCC x src lbl expr)
233 = do { (expr', fvs_expr) <- rnLExpr expr
234 ; return (HsSCC x src lbl expr', fvs_expr) }
235 rnExpr (HsTickPragma x src info srcInfo expr)
236 = do { (expr', fvs_expr) <- rnLExpr expr
237 ; return (HsTickPragma x src info srcInfo expr', fvs_expr) }
238
239 rnExpr (HsLam x matches)
240 = do { (matches', fvMatch) <- rnMatchGroup LambdaExpr rnLExpr matches
241 ; return (HsLam x matches', fvMatch) }
242
243 rnExpr (HsLamCase x matches)
244 = do { (matches', fvs_ms) <- rnMatchGroup CaseAlt rnLExpr matches
245 ; return (HsLamCase x matches', fvs_ms) }
246
247 rnExpr (HsCase x expr matches)
248 = do { (new_expr, e_fvs) <- rnLExpr expr
249 ; (new_matches, ms_fvs) <- rnMatchGroup CaseAlt rnLExpr matches
250 ; return (HsCase x new_expr new_matches, e_fvs `plusFV` ms_fvs) }
251
252 rnExpr (HsLet x (L l binds) expr)
253 = rnLocalBindsAndThen binds $ \binds' _ -> do
254 { (expr',fvExpr) <- rnLExpr expr
255 ; return (HsLet x (L l binds') expr', fvExpr) }
256
257 rnExpr (HsDo x do_or_lc (L l stmts))
258 = do { ((stmts', _), fvs) <-
259 rnStmtsWithPostProcessing do_or_lc rnLExpr
260 postProcessStmtsForApplicativeDo stmts
261 (\ _ -> return ((), emptyFVs))
262 ; return ( HsDo x do_or_lc (L l stmts'), fvs ) }
263
264 rnExpr (ExplicitList x _ exps)
265 = do { opt_OverloadedLists <- xoptM LangExt.OverloadedLists
266 ; (exps', fvs) <- rnExprs exps
267 ; if opt_OverloadedLists
268 then do {
269 ; (from_list_n_name, fvs') <- lookupSyntaxName fromListNName
270 ; return (ExplicitList x (Just from_list_n_name) exps'
271 , fvs `plusFV` fvs') }
272 else
273 return (ExplicitList x Nothing exps', fvs) }
274
275 rnExpr (ExplicitTuple x tup_args boxity)
276 = do { checkTupleSection tup_args
277 ; checkTupSize (length tup_args)
278 ; (tup_args', fvs) <- mapAndUnzipM rnTupArg tup_args
279 ; return (ExplicitTuple x tup_args' boxity, plusFVs fvs) }
280 where
281 rnTupArg (L l (Present x e)) = do { (e',fvs) <- rnLExpr e
282 ; return (L l (Present x e'), fvs) }
283 rnTupArg (L l (Missing _)) = return (L l (Missing noExt)
284 , emptyFVs)
285 rnTupArg (L _ (XTupArg {})) = panic "rnExpr.XTupArg"
286
287 rnExpr (ExplicitSum x alt arity expr)
288 = do { (expr', fvs) <- rnLExpr expr
289 ; return (ExplicitSum x alt arity expr', fvs) }
290
291 rnExpr (RecordCon { rcon_con_name = con_id
292 , rcon_flds = rec_binds@(HsRecFields { rec_dotdot = dd }) })
293 = do { con_lname@(L _ con_name) <- lookupLocatedOccRn con_id
294 ; (flds, fvs) <- rnHsRecFields (HsRecFieldCon con_name) mk_hs_var rec_binds
295 ; (flds', fvss) <- mapAndUnzipM rn_field flds
296 ; let rec_binds' = HsRecFields { rec_flds = flds', rec_dotdot = dd }
297 ; return (RecordCon { rcon_ext = noExt
298 , rcon_con_name = con_lname, rcon_flds = rec_binds' }
299 , fvs `plusFV` plusFVs fvss `addOneFV` con_name) }
300 where
301 mk_hs_var l n = HsVar noExt (L l n)
302 rn_field (L l fld) = do { (arg', fvs) <- rnLExpr (hsRecFieldArg fld)
303 ; return (L l (fld { hsRecFieldArg = arg' }), fvs) }
304
305 rnExpr (RecordUpd { rupd_expr = expr, rupd_flds = rbinds })
306 = do { (expr', fvExpr) <- rnLExpr expr
307 ; (rbinds', fvRbinds) <- rnHsRecUpdFields rbinds
308 ; return (RecordUpd { rupd_ext = noExt, rupd_expr = expr'
309 , rupd_flds = rbinds' }
310 , fvExpr `plusFV` fvRbinds) }
311
312 rnExpr (ExprWithTySig pty expr)
313 = do { (pty', fvTy) <- rnHsSigWcType ExprWithTySigCtx pty
314 ; (expr', fvExpr) <- bindSigTyVarsFV (hsWcScopedTvs pty') $
315 rnLExpr expr
316 ; return (ExprWithTySig pty' expr', fvExpr `plusFV` fvTy) }
317
318 rnExpr (HsIf x _ p b1 b2)
319 = do { (p', fvP) <- rnLExpr p
320 ; (b1', fvB1) <- rnLExpr b1
321 ; (b2', fvB2) <- rnLExpr b2
322 ; (mb_ite, fvITE) <- lookupIfThenElse
323 ; return (HsIf x mb_ite p' b1' b2', plusFVs [fvITE, fvP, fvB1, fvB2]) }
324
325 rnExpr (HsMultiIf x alts)
326 = do { (alts', fvs) <- mapFvRn (rnGRHS IfAlt rnLExpr) alts
327 -- ; return (HsMultiIf ty alts', fvs) }
328 ; return (HsMultiIf x alts', fvs) }
329
330 rnExpr (ArithSeq x _ seq)
331 = do { opt_OverloadedLists <- xoptM LangExt.OverloadedLists
332 ; (new_seq, fvs) <- rnArithSeq seq
333 ; if opt_OverloadedLists
334 then do {
335 ; (from_list_name, fvs') <- lookupSyntaxName fromListName
336 ; return (ArithSeq x (Just from_list_name) new_seq
337 , fvs `plusFV` fvs') }
338 else
339 return (ArithSeq x Nothing new_seq, fvs) }
340
341 {-
342 These three are pattern syntax appearing in expressions.
343 Since all the symbols are reservedops we can simply reject them.
344 We return a (bogus) EWildPat in each case.
345 -}
346
347 rnExpr (EWildPat _) = return (hsHoleExpr, emptyFVs) -- "_" is just a hole
348 rnExpr e@(EAsPat {})
349 = do { opt_TypeApplications <- xoptM LangExt.TypeApplications
350 ; let msg | opt_TypeApplications
351 = "Type application syntax requires a space before '@'"
352 | otherwise
353 = "Did you mean to enable TypeApplications?"
354 ; patSynErr e (text msg)
355 }
356 rnExpr e@(EViewPat {}) = patSynErr e empty
357 rnExpr e@(ELazyPat {}) = patSynErr e empty
358
359 {-
360 ************************************************************************
361 * *
362 Static values
363 * *
364 ************************************************************************
365
366 For the static form we check that it is not used in splices.
367 We also collect the free variables of the term which come from
368 this module. See Note [Grand plan for static forms] in StaticPtrTable.
369 -}
370
371 rnExpr e@(HsStatic _ expr) = do
372 -- Normally, you wouldn't be able to construct a static expression without
373 -- first enabling -XStaticPointers in the first place, since that extension
374 -- is what makes the parser treat `static` as a keyword. But this is not a
375 -- sufficient safeguard, as one can construct static expressions by another
376 -- mechanism: Template Haskell (see #14204). To ensure that GHC is
377 -- absolutely prepared to cope with static forms, we check for
378 -- -XStaticPointers here as well.
379 unlessXOptM LangExt.StaticPointers $
380 addErr $ hang (text "Illegal static expression:" <+> ppr e)
381 2 (text "Use StaticPointers to enable this extension")
382 (expr',fvExpr) <- rnLExpr expr
383 stage <- getStage
384 case stage of
385 Splice _ -> addErr $ sep
386 [ text "static forms cannot be used in splices:"
387 , nest 2 $ ppr e
388 ]
389 _ -> return ()
390 mod <- getModule
391 let fvExpr' = filterNameSet (nameIsLocalOrFrom mod) fvExpr
392 return (HsStatic fvExpr' expr', fvExpr)
393
394 {-
395 ************************************************************************
396 * *
397 Arrow notation
398 * *
399 ************************************************************************
400 -}
401
402 rnExpr (HsProc x pat body)
403 = newArrowScope $
404 rnPat ProcExpr pat $ \ pat' -> do
405 { (body',fvBody) <- rnCmdTop body
406 ; return (HsProc x pat' body', fvBody) }
407
408 -- Ideally, these would be done in parsing, but to keep parsing simple, we do it here.
409 rnExpr e@(HsArrApp {}) = arrowFail e
410 rnExpr e@(HsArrForm {}) = arrowFail e
411
412 rnExpr other = pprPanic "rnExpr: unexpected expression" (ppr other)
413 -- HsWrap
414
415 hsHoleExpr :: HsExpr (GhcPass id)
416 hsHoleExpr = HsUnboundVar noExt (TrueExprHole (mkVarOcc "_"))
417
418 arrowFail :: HsExpr GhcPs -> RnM (HsExpr GhcRn, FreeVars)
419 arrowFail e
420 = do { addErr (vcat [ text "Arrow command found where an expression was expected:"
421 , nest 2 (ppr e) ])
422 -- Return a place-holder hole, so that we can carry on
423 -- to report other errors
424 ; return (hsHoleExpr, emptyFVs) }
425
426 ----------------------
427 -- See Note [Parsing sections] in Parser.y
428 rnSection :: HsExpr GhcPs -> RnM (HsExpr GhcRn, FreeVars)
429 rnSection section@(SectionR x op expr)
430 = do { (op', fvs_op) <- rnLExpr op
431 ; (expr', fvs_expr) <- rnLExpr expr
432 ; checkSectionPrec InfixR section op' expr'
433 ; return (SectionR x op' expr', fvs_op `plusFV` fvs_expr) }
434
435 rnSection section@(SectionL x expr op)
436 = do { (expr', fvs_expr) <- rnLExpr expr
437 ; (op', fvs_op) <- rnLExpr op
438 ; checkSectionPrec InfixL section op' expr'
439 ; return (SectionL x expr' op', fvs_op `plusFV` fvs_expr) }
440
441 rnSection other = pprPanic "rnSection" (ppr other)
442
443 {-
444 ************************************************************************
445 * *
446 Arrow commands
447 * *
448 ************************************************************************
449 -}
450
451 rnCmdArgs :: [LHsCmdTop GhcPs] -> RnM ([LHsCmdTop GhcRn], FreeVars)
452 rnCmdArgs [] = return ([], emptyFVs)
453 rnCmdArgs (arg:args)
454 = do { (arg',fvArg) <- rnCmdTop arg
455 ; (args',fvArgs) <- rnCmdArgs args
456 ; return (arg':args', fvArg `plusFV` fvArgs) }
457
458 rnCmdTop :: LHsCmdTop GhcPs -> RnM (LHsCmdTop GhcRn, FreeVars)
459 rnCmdTop = wrapLocFstM rnCmdTop'
460 where
461 rnCmdTop' (HsCmdTop _ cmd)
462 = do { (cmd', fvCmd) <- rnLCmd cmd
463 ; let cmd_names = [arrAName, composeAName, firstAName] ++
464 nameSetElemsStable (methodNamesCmd (unLoc cmd'))
465 -- Generate the rebindable syntax for the monad
466 ; (cmd_names', cmd_fvs) <- lookupSyntaxNames cmd_names
467
468 ; return (HsCmdTop (cmd_names `zip` cmd_names') cmd',
469 fvCmd `plusFV` cmd_fvs) }
470 rnCmdTop' (XCmdTop{}) = panic "rnCmdTop"
471
472 rnLCmd :: LHsCmd GhcPs -> RnM (LHsCmd GhcRn, FreeVars)
473 rnLCmd = wrapLocFstM rnCmd
474
475 rnCmd :: HsCmd GhcPs -> RnM (HsCmd GhcRn, FreeVars)
476
477 rnCmd (HsCmdArrApp x arrow arg ho rtl)
478 = do { (arrow',fvArrow) <- select_arrow_scope (rnLExpr arrow)
479 ; (arg',fvArg) <- rnLExpr arg
480 ; return (HsCmdArrApp x arrow' arg' ho rtl,
481 fvArrow `plusFV` fvArg) }
482 where
483 select_arrow_scope tc = case ho of
484 HsHigherOrderApp -> tc
485 HsFirstOrderApp -> escapeArrowScope tc
486 -- See Note [Escaping the arrow scope] in TcRnTypes
487 -- Before renaming 'arrow', use the environment of the enclosing
488 -- proc for the (-<) case.
489 -- Local bindings, inside the enclosing proc, are not in scope
490 -- inside 'arrow'. In the higher-order case (-<<), they are.
491
492 -- infix form
493 rnCmd (HsCmdArrForm _ op _ (Just _) [arg1, arg2])
494 = do { (op',fv_op) <- escapeArrowScope (rnLExpr op)
495 ; let L _ (HsVar _ (L _ op_name)) = op'
496 ; (arg1',fv_arg1) <- rnCmdTop arg1
497 ; (arg2',fv_arg2) <- rnCmdTop arg2
498 -- Deal with fixity
499 ; fixity <- lookupFixityRn op_name
500 ; final_e <- mkOpFormRn arg1' op' fixity arg2'
501 ; return (final_e, fv_arg1 `plusFV` fv_op `plusFV` fv_arg2) }
502
503 rnCmd (HsCmdArrForm x op f fixity cmds)
504 = do { (op',fvOp) <- escapeArrowScope (rnLExpr op)
505 ; (cmds',fvCmds) <- rnCmdArgs cmds
506 ; return (HsCmdArrForm x op' f fixity cmds', fvOp `plusFV` fvCmds) }
507
508 rnCmd (HsCmdApp x fun arg)
509 = do { (fun',fvFun) <- rnLCmd fun
510 ; (arg',fvArg) <- rnLExpr arg
511 ; return (HsCmdApp x fun' arg', fvFun `plusFV` fvArg) }
512
513 rnCmd (HsCmdLam x matches)
514 = do { (matches', fvMatch) <- rnMatchGroup LambdaExpr rnLCmd matches
515 ; return (HsCmdLam x matches', fvMatch) }
516
517 rnCmd (HsCmdPar x e)
518 = do { (e', fvs_e) <- rnLCmd e
519 ; return (HsCmdPar x e', fvs_e) }
520
521 rnCmd (HsCmdCase x expr matches)
522 = do { (new_expr, e_fvs) <- rnLExpr expr
523 ; (new_matches, ms_fvs) <- rnMatchGroup CaseAlt rnLCmd matches
524 ; return (HsCmdCase x new_expr new_matches, e_fvs `plusFV` ms_fvs) }
525
526 rnCmd (HsCmdIf x _ p b1 b2)
527 = do { (p', fvP) <- rnLExpr p
528 ; (b1', fvB1) <- rnLCmd b1
529 ; (b2', fvB2) <- rnLCmd b2
530 ; (mb_ite, fvITE) <- lookupIfThenElse
531 ; return (HsCmdIf x mb_ite p' b1' b2', plusFVs [fvITE, fvP, fvB1, fvB2])}
532
533 rnCmd (HsCmdLet x (L l binds) cmd)
534 = rnLocalBindsAndThen binds $ \ binds' _ -> do
535 { (cmd',fvExpr) <- rnLCmd cmd
536 ; return (HsCmdLet x (L l binds') cmd', fvExpr) }
537
538 rnCmd (HsCmdDo x (L l stmts))
539 = do { ((stmts', _), fvs) <-
540 rnStmts ArrowExpr rnLCmd stmts (\ _ -> return ((), emptyFVs))
541 ; return ( HsCmdDo x (L l stmts'), fvs ) }
542
543 rnCmd cmd@(HsCmdWrap {}) = pprPanic "rnCmd" (ppr cmd)
544 rnCmd cmd@(XCmd {}) = pprPanic "rnCmd" (ppr cmd)
545
546 ---------------------------------------------------
547 type CmdNeeds = FreeVars -- Only inhabitants are
548 -- appAName, choiceAName, loopAName
549
550 -- find what methods the Cmd needs (loop, choice, apply)
551 methodNamesLCmd :: LHsCmd GhcRn -> CmdNeeds
552 methodNamesLCmd = methodNamesCmd . unLoc
553
554 methodNamesCmd :: HsCmd GhcRn -> CmdNeeds
555
556 methodNamesCmd (HsCmdArrApp _ _arrow _arg HsFirstOrderApp _rtl)
557 = emptyFVs
558 methodNamesCmd (HsCmdArrApp _ _arrow _arg HsHigherOrderApp _rtl)
559 = unitFV appAName
560 methodNamesCmd (HsCmdArrForm {}) = emptyFVs
561 methodNamesCmd (HsCmdWrap _ _ cmd) = methodNamesCmd cmd
562
563 methodNamesCmd (HsCmdPar _ c) = methodNamesLCmd c
564
565 methodNamesCmd (HsCmdIf _ _ _ c1 c2)
566 = methodNamesLCmd c1 `plusFV` methodNamesLCmd c2 `addOneFV` choiceAName
567
568 methodNamesCmd (HsCmdLet _ _ c) = methodNamesLCmd c
569 methodNamesCmd (HsCmdDo _ (L _ stmts)) = methodNamesStmts stmts
570 methodNamesCmd (HsCmdApp _ c _) = methodNamesLCmd c
571 methodNamesCmd (HsCmdLam _ match) = methodNamesMatch match
572
573 methodNamesCmd (HsCmdCase _ _ matches)
574 = methodNamesMatch matches `addOneFV` choiceAName
575
576 methodNamesCmd (XCmd {}) = panic "methodNamesCmd"
577
578 --methodNamesCmd _ = emptyFVs
579 -- Other forms can't occur in commands, but it's not convenient
580 -- to error here so we just do what's convenient.
581 -- The type checker will complain later
582
583 ---------------------------------------------------
584 methodNamesMatch :: MatchGroup GhcRn (LHsCmd GhcRn) -> FreeVars
585 methodNamesMatch (MG { mg_alts = L _ ms })
586 = plusFVs (map do_one ms)
587 where
588 do_one (L _ (Match { m_grhss = grhss })) = methodNamesGRHSs grhss
589 do_one (L _ (XMatch _)) = panic "methodNamesMatch.XMatch"
590 methodNamesMatch (XMatchGroup _) = panic "methodNamesMatch"
591
592 -------------------------------------------------
593 -- gaw 2004
594 methodNamesGRHSs :: GRHSs GhcRn (LHsCmd GhcRn) -> FreeVars
595 methodNamesGRHSs (GRHSs _ grhss _) = plusFVs (map methodNamesGRHS grhss)
596 methodNamesGRHSs (XGRHSs _) = panic "methodNamesGRHSs"
597
598 -------------------------------------------------
599
600 methodNamesGRHS :: Located (GRHS GhcRn (LHsCmd GhcRn)) -> CmdNeeds
601 methodNamesGRHS (L _ (GRHS _ _ rhs)) = methodNamesLCmd rhs
602 methodNamesGRHS (L _ (XGRHS _)) = panic "methodNamesGRHS"
603
604 ---------------------------------------------------
605 methodNamesStmts :: [Located (StmtLR GhcRn GhcRn (LHsCmd GhcRn))] -> FreeVars
606 methodNamesStmts stmts = plusFVs (map methodNamesLStmt stmts)
607
608 ---------------------------------------------------
609 methodNamesLStmt :: Located (StmtLR GhcRn GhcRn (LHsCmd GhcRn)) -> FreeVars
610 methodNamesLStmt = methodNamesStmt . unLoc
611
612 methodNamesStmt :: StmtLR GhcRn GhcRn (LHsCmd GhcRn) -> FreeVars
613 methodNamesStmt (LastStmt _ cmd _ _) = methodNamesLCmd cmd
614 methodNamesStmt (BodyStmt _ cmd _ _) = methodNamesLCmd cmd
615 methodNamesStmt (BindStmt _ _ cmd _ _) = methodNamesLCmd cmd
616 methodNamesStmt (RecStmt { recS_stmts = stmts }) =
617 methodNamesStmts stmts `addOneFV` loopAName
618 methodNamesStmt (LetStmt {}) = emptyFVs
619 methodNamesStmt (ParStmt {}) = emptyFVs
620 methodNamesStmt (TransStmt {}) = emptyFVs
621 methodNamesStmt ApplicativeStmt{} = emptyFVs
622 -- ParStmt and TransStmt can't occur in commands, but it's not
623 -- convenient to error here so we just do what's convenient
624 methodNamesStmt (XStmtLR {}) = panic "methodNamesStmt"
625
626 {-
627 ************************************************************************
628 * *
629 Arithmetic sequences
630 * *
631 ************************************************************************
632 -}
633
634 rnArithSeq :: ArithSeqInfo GhcPs -> RnM (ArithSeqInfo GhcRn, FreeVars)
635 rnArithSeq (From expr)
636 = do { (expr', fvExpr) <- rnLExpr expr
637 ; return (From expr', fvExpr) }
638
639 rnArithSeq (FromThen expr1 expr2)
640 = do { (expr1', fvExpr1) <- rnLExpr expr1
641 ; (expr2', fvExpr2) <- rnLExpr expr2
642 ; return (FromThen expr1' expr2', fvExpr1 `plusFV` fvExpr2) }
643
644 rnArithSeq (FromTo expr1 expr2)
645 = do { (expr1', fvExpr1) <- rnLExpr expr1
646 ; (expr2', fvExpr2) <- rnLExpr expr2
647 ; return (FromTo expr1' expr2', fvExpr1 `plusFV` fvExpr2) }
648
649 rnArithSeq (FromThenTo expr1 expr2 expr3)
650 = do { (expr1', fvExpr1) <- rnLExpr expr1
651 ; (expr2', fvExpr2) <- rnLExpr expr2
652 ; (expr3', fvExpr3) <- rnLExpr expr3
653 ; return (FromThenTo expr1' expr2' expr3',
654 plusFVs [fvExpr1, fvExpr2, fvExpr3]) }
655
656 {-
657 ************************************************************************
658 * *
659 \subsubsection{@Stmt@s: in @do@ expressions}
660 * *
661 ************************************************************************
662 -}
663
664 {-
665 Note [Deterministic ApplicativeDo and RecursiveDo desugaring]
666 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
667 Both ApplicativeDo and RecursiveDo need to create tuples not
668 present in the source text.
669
670 For ApplicativeDo we create:
671
672 (a,b,c) <- (\c b a -> (a,b,c)) <$>
673
674 For RecursiveDo we create:
675
676 mfix (\ ~(a,b,c) -> do ...; return (a',b',c'))
677
678 The order of the components in those tuples needs to be stable
679 across recompilations, otherwise they can get optimized differently
680 and we end up with incompatible binaries.
681 To get a stable order we use nameSetElemsStable.
682 See Note [Deterministic UniqFM] to learn more about nondeterminism.
683 -}
684
685 -- | Rename some Stmts
686 rnStmts :: Outputable (body GhcPs)
687 => HsStmtContext Name
688 -> (Located (body GhcPs) -> RnM (Located (body GhcRn), FreeVars))
689 -- ^ How to rename the body of each statement (e.g. rnLExpr)
690 -> [LStmt GhcPs (Located (body GhcPs))]
691 -- ^ Statements
692 -> ([Name] -> RnM (thing, FreeVars))
693 -- ^ if these statements scope over something, this renames it
694 -- and returns the result.
695 -> RnM (([LStmt GhcRn (Located (body GhcRn))], thing), FreeVars)
696 rnStmts ctxt rnBody = rnStmtsWithPostProcessing ctxt rnBody noPostProcessStmts
697
698 -- | like 'rnStmts' but applies a post-processing step to the renamed Stmts
699 rnStmtsWithPostProcessing
700 :: Outputable (body GhcPs)
701 => HsStmtContext Name
702 -> (Located (body GhcPs) -> RnM (Located (body GhcRn), FreeVars))
703 -- ^ How to rename the body of each statement (e.g. rnLExpr)
704 -> (HsStmtContext Name
705 -> [(LStmt GhcRn (Located (body GhcRn)), FreeVars)]
706 -> RnM ([LStmt GhcRn (Located (body GhcRn))], FreeVars))
707 -- ^ postprocess the statements
708 -> [LStmt GhcPs (Located (body GhcPs))]
709 -- ^ Statements
710 -> ([Name] -> RnM (thing, FreeVars))
711 -- ^ if these statements scope over something, this renames it
712 -- and returns the result.
713 -> RnM (([LStmt GhcRn (Located (body GhcRn))], thing), FreeVars)
714 rnStmtsWithPostProcessing ctxt rnBody ppStmts stmts thing_inside
715 = do { ((stmts', thing), fvs) <-
716 rnStmtsWithFreeVars ctxt rnBody stmts thing_inside
717 ; (pp_stmts, fvs') <- ppStmts ctxt stmts'
718 ; return ((pp_stmts, thing), fvs `plusFV` fvs')
719 }
720
721 -- | maybe rearrange statements according to the ApplicativeDo transformation
722 postProcessStmtsForApplicativeDo
723 :: HsStmtContext Name
724 -> [(ExprLStmt GhcRn, FreeVars)]
725 -> RnM ([ExprLStmt GhcRn], FreeVars)
726 postProcessStmtsForApplicativeDo ctxt stmts
727 = do {
728 -- rearrange the statements using ApplicativeStmt if
729 -- -XApplicativeDo is on. Also strip out the FreeVars attached
730 -- to each Stmt body.
731 ado_is_on <- xoptM LangExt.ApplicativeDo
732 ; let is_do_expr | DoExpr <- ctxt = True
733 | otherwise = False
734 ; if ado_is_on && is_do_expr
735 then do { traceRn "ppsfa" (ppr stmts)
736 ; rearrangeForApplicativeDo ctxt stmts }
737 else noPostProcessStmts ctxt stmts }
738
739 -- | strip the FreeVars annotations from statements
740 noPostProcessStmts
741 :: HsStmtContext Name
742 -> [(LStmt GhcRn (Located (body GhcRn)), FreeVars)]
743 -> RnM ([LStmt GhcRn (Located (body GhcRn))], FreeVars)
744 noPostProcessStmts _ stmts = return (map fst stmts, emptyNameSet)
745
746
747 rnStmtsWithFreeVars :: Outputable (body GhcPs)
748 => HsStmtContext Name
749 -> (Located (body GhcPs) -> RnM (Located (body GhcRn), FreeVars))
750 -> [LStmt GhcPs (Located (body GhcPs))]
751 -> ([Name] -> RnM (thing, FreeVars))
752 -> RnM ( ([(LStmt GhcRn (Located (body GhcRn)), FreeVars)], thing)
753 , FreeVars)
754 -- Each Stmt body is annotated with its FreeVars, so that
755 -- we can rearrange statements for ApplicativeDo.
756 --
757 -- Variables bound by the Stmts, and mentioned in thing_inside,
758 -- do not appear in the result FreeVars
759
760 rnStmtsWithFreeVars ctxt _ [] thing_inside
761 = do { checkEmptyStmts ctxt
762 ; (thing, fvs) <- thing_inside []
763 ; return (([], thing), fvs) }
764
765 rnStmtsWithFreeVars MDoExpr rnBody stmts thing_inside -- Deal with mdo
766 = -- Behave like do { rec { ...all but last... }; last }
767 do { ((stmts1, (stmts2, thing)), fvs)
768 <- rnStmt MDoExpr rnBody (noLoc $ mkRecStmt all_but_last) $ \ _ ->
769 do { last_stmt' <- checkLastStmt MDoExpr last_stmt
770 ; rnStmt MDoExpr rnBody last_stmt' thing_inside }
771 ; return (((stmts1 ++ stmts2), thing), fvs) }
772 where
773 Just (all_but_last, last_stmt) = snocView stmts
774
775 rnStmtsWithFreeVars ctxt rnBody (lstmt@(L loc _) : lstmts) thing_inside
776 | null lstmts
777 = setSrcSpan loc $
778 do { lstmt' <- checkLastStmt ctxt lstmt
779 ; rnStmt ctxt rnBody lstmt' thing_inside }
780
781 | otherwise
782 = do { ((stmts1, (stmts2, thing)), fvs)
783 <- setSrcSpan loc $
784 do { checkStmt ctxt lstmt
785 ; rnStmt ctxt rnBody lstmt $ \ bndrs1 ->
786 rnStmtsWithFreeVars ctxt rnBody lstmts $ \ bndrs2 ->
787 thing_inside (bndrs1 ++ bndrs2) }
788 ; return (((stmts1 ++ stmts2), thing), fvs) }
789
790 ----------------------
791
792 {-
793 Note [Failing pattern matches in Stmts]
794 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
795
796 Many things desugar to HsStmts including monadic things like `do` and `mdo`
797 statements, pattern guards, and list comprehensions (see 'HsStmtContext' for an
798 exhaustive list). How we deal with pattern match failure is context-dependent.
799
800 * In the case of list comprehensions and pattern guards we don't need any 'fail'
801 function; the desugarer ignores the fail function field of 'BindStmt' entirely.
802 * In the case of monadic contexts (e.g. monad comprehensions, do, and mdo
803 expressions) we want pattern match failure to be desugared to the appropriate
804 'fail' function (either that of Monad or MonadFail, depending on whether
805 -XMonadFailDesugaring is enabled.)
806
807 At one point we failed to make this distinction, leading to #11216.
808 -}
809
810 rnStmt :: Outputable (body GhcPs)
811 => HsStmtContext Name
812 -> (Located (body GhcPs) -> RnM (Located (body GhcRn), FreeVars))
813 -- ^ How to rename the body of the statement
814 -> LStmt GhcPs (Located (body GhcPs))
815 -- ^ The statement
816 -> ([Name] -> RnM (thing, FreeVars))
817 -- ^ Rename the stuff that this statement scopes over
818 -> RnM ( ([(LStmt GhcRn (Located (body GhcRn)), FreeVars)], thing)
819 , FreeVars)
820 -- Variables bound by the Stmt, and mentioned in thing_inside,
821 -- do not appear in the result FreeVars
822
823 rnStmt ctxt rnBody (L loc (LastStmt _ body noret _)) thing_inside
824 = do { (body', fv_expr) <- rnBody body
825 ; (ret_op, fvs1) <- lookupStmtName ctxt returnMName
826 ; (thing, fvs3) <- thing_inside []
827 ; return (([(L loc (LastStmt noExt body' noret ret_op), fv_expr)]
828 , thing), fv_expr `plusFV` fvs1 `plusFV` fvs3) }
829
830 rnStmt ctxt rnBody (L loc (BodyStmt _ body _ _)) thing_inside
831 = do { (body', fv_expr) <- rnBody body
832 ; (then_op, fvs1) <- lookupStmtName ctxt thenMName
833 ; (guard_op, fvs2) <- if isListCompExpr ctxt
834 then lookupStmtName ctxt guardMName
835 else return (noSyntaxExpr, emptyFVs)
836 -- Only list/monad comprehensions use 'guard'
837 -- Also for sub-stmts of same eg [ e | x<-xs, gd | blah ]
838 -- Here "gd" is a guard
839 ; (thing, fvs3) <- thing_inside []
840 ; return ( ([(L loc (BodyStmt noExt body' then_op guard_op), fv_expr)]
841 , thing), fv_expr `plusFV` fvs1 `plusFV` fvs2 `plusFV` fvs3) }
842
843 rnStmt ctxt rnBody (L loc (BindStmt _ pat body _ _)) thing_inside
844 = do { (body', fv_expr) <- rnBody body
845 -- The binders do not scope over the expression
846 ; (bind_op, fvs1) <- lookupStmtName ctxt bindMName
847
848 ; xMonadFailEnabled <- fmap (xopt LangExt.MonadFailDesugaring) getDynFlags
849 ; let getFailFunction
850 -- If the pattern is irrefutable (e.g.: wildcard, tuple,
851 -- ~pat, etc.) we should not need to fail.
852 | isIrrefutableHsPat pat
853 = return (noSyntaxExpr, emptyFVs)
854 -- For non-monadic contexts (e.g. guard patterns, list
855 -- comprehensions, etc.) we should not need to fail.
856 -- See Note [Failing pattern matches in Stmts]
857 | not (isMonadFailStmtContext ctxt)
858 = return (noSyntaxExpr, emptyFVs)
859 | xMonadFailEnabled = lookupSyntaxName failMName
860 | otherwise = lookupSyntaxName failMName_preMFP
861 ; (fail_op, fvs2) <- getFailFunction
862
863 ; rnPat (StmtCtxt ctxt) pat $ \ pat' -> do
864 { (thing, fvs3) <- thing_inside (collectPatBinders pat')
865 ; return (( [( L loc (BindStmt noExt pat' body' bind_op fail_op)
866 , fv_expr )]
867 , thing),
868 fv_expr `plusFV` fvs1 `plusFV` fvs2 `plusFV` fvs3) }}
869 -- fv_expr shouldn't really be filtered by the rnPatsAndThen
870 -- but it does not matter because the names are unique
871
872 rnStmt _ _ (L loc (LetStmt _ (L l binds))) thing_inside
873 = do { rnLocalBindsAndThen binds $ \binds' bind_fvs -> do
874 { (thing, fvs) <- thing_inside (collectLocalBinders binds')
875 ; return ( ([(L loc (LetStmt noExt (L l binds')), bind_fvs)], thing)
876 , fvs) } }
877
878 rnStmt ctxt rnBody (L loc (RecStmt { recS_stmts = rec_stmts })) thing_inside
879 = do { (return_op, fvs1) <- lookupStmtName ctxt returnMName
880 ; (mfix_op, fvs2) <- lookupStmtName ctxt mfixName
881 ; (bind_op, fvs3) <- lookupStmtName ctxt bindMName
882 ; let empty_rec_stmt = emptyRecStmtName { recS_ret_fn = return_op
883 , recS_mfix_fn = mfix_op
884 , recS_bind_fn = bind_op }
885
886 -- Step1: Bring all the binders of the mdo into scope
887 -- (Remember that this also removes the binders from the
888 -- finally-returned free-vars.)
889 -- And rename each individual stmt, making a
890 -- singleton segment. At this stage the FwdRefs field
891 -- isn't finished: it's empty for all except a BindStmt
892 -- for which it's the fwd refs within the bind itself
893 -- (This set may not be empty, because we're in a recursive
894 -- context.)
895 ; rnRecStmtsAndThen rnBody rec_stmts $ \ segs -> do
896 { let bndrs = nameSetElemsStable $
897 foldr (unionNameSet . (\(ds,_,_,_) -> ds))
898 emptyNameSet
899 segs
900 -- See Note [Deterministic ApplicativeDo and RecursiveDo desugaring]
901 ; (thing, fvs_later) <- thing_inside bndrs
902 ; let (rec_stmts', fvs) = segmentRecStmts loc ctxt empty_rec_stmt segs fvs_later
903 -- We aren't going to try to group RecStmts with
904 -- ApplicativeDo, so attaching empty FVs is fine.
905 ; return ( ((zip rec_stmts' (repeat emptyNameSet)), thing)
906 , fvs `plusFV` fvs1 `plusFV` fvs2 `plusFV` fvs3) } }
907
908 rnStmt ctxt _ (L loc (ParStmt _ segs _ _)) thing_inside
909 = do { (mzip_op, fvs1) <- lookupStmtNamePoly ctxt mzipName
910 ; (bind_op, fvs2) <- lookupStmtName ctxt bindMName
911 ; (return_op, fvs3) <- lookupStmtName ctxt returnMName
912 ; ((segs', thing), fvs4) <- rnParallelStmts (ParStmtCtxt ctxt) return_op segs thing_inside
913 ; return (([(L loc (ParStmt noExt segs' mzip_op bind_op), fvs4)], thing)
914 , fvs1 `plusFV` fvs2 `plusFV` fvs3 `plusFV` fvs4) }
915
916 rnStmt ctxt _ (L loc (TransStmt { trS_stmts = stmts, trS_by = by, trS_form = form
917 , trS_using = using })) thing_inside
918 = do { -- Rename the 'using' expression in the context before the transform is begun
919 (using', fvs1) <- rnLExpr using
920
921 -- Rename the stmts and the 'by' expression
922 -- Keep track of the variables mentioned in the 'by' expression
923 ; ((stmts', (by', used_bndrs, thing)), fvs2)
924 <- rnStmts (TransStmtCtxt ctxt) rnLExpr stmts $ \ bndrs ->
925 do { (by', fvs_by) <- mapMaybeFvRn rnLExpr by
926 ; (thing, fvs_thing) <- thing_inside bndrs
927 ; let fvs = fvs_by `plusFV` fvs_thing
928 used_bndrs = filter (`elemNameSet` fvs) bndrs
929 -- The paper (Fig 5) has a bug here; we must treat any free variable
930 -- of the "thing inside", **or of the by-expression**, as used
931 ; return ((by', used_bndrs, thing), fvs) }
932
933 -- Lookup `return`, `(>>=)` and `liftM` for monad comprehensions
934 ; (return_op, fvs3) <- lookupStmtName ctxt returnMName
935 ; (bind_op, fvs4) <- lookupStmtName ctxt bindMName
936 ; (fmap_op, fvs5) <- case form of
937 ThenForm -> return (noExpr, emptyFVs)
938 _ -> lookupStmtNamePoly ctxt fmapName
939
940 ; let all_fvs = fvs1 `plusFV` fvs2 `plusFV` fvs3
941 `plusFV` fvs4 `plusFV` fvs5
942 bndr_map = used_bndrs `zip` used_bndrs
943 -- See Note [TransStmt binder map] in HsExpr
944
945 ; traceRn "rnStmt: implicitly rebound these used binders:" (ppr bndr_map)
946 ; return (([(L loc (TransStmt { trS_ext = noExt
947 , trS_stmts = stmts', trS_bndrs = bndr_map
948 , trS_by = by', trS_using = using', trS_form = form
949 , trS_ret = return_op, trS_bind = bind_op
950 , trS_fmap = fmap_op }), fvs2)], thing), all_fvs) }
951
952 rnStmt _ _ (L _ ApplicativeStmt{}) _ =
953 panic "rnStmt: ApplicativeStmt"
954
955 rnStmt _ _ (L _ XStmtLR{}) _ =
956 panic "rnStmt: XStmtLR"
957
958 rnParallelStmts :: forall thing. HsStmtContext Name
959 -> SyntaxExpr GhcRn
960 -> [ParStmtBlock GhcPs GhcPs]
961 -> ([Name] -> RnM (thing, FreeVars))
962 -> RnM (([ParStmtBlock GhcRn GhcRn], thing), FreeVars)
963 -- Note [Renaming parallel Stmts]
964 rnParallelStmts ctxt return_op segs thing_inside
965 = do { orig_lcl_env <- getLocalRdrEnv
966 ; rn_segs orig_lcl_env [] segs }
967 where
968 rn_segs :: LocalRdrEnv
969 -> [Name] -> [ParStmtBlock GhcPs GhcPs]
970 -> RnM (([ParStmtBlock GhcRn GhcRn], thing), FreeVars)
971 rn_segs _ bndrs_so_far []
972 = do { let (bndrs', dups) = removeDups cmpByOcc bndrs_so_far
973 ; mapM_ dupErr dups
974 ; (thing, fvs) <- bindLocalNames bndrs' (thing_inside bndrs')
975 ; return (([], thing), fvs) }
976
977 rn_segs env bndrs_so_far (ParStmtBlock x stmts _ _ : segs)
978 = do { ((stmts', (used_bndrs, segs', thing)), fvs)
979 <- rnStmts ctxt rnLExpr stmts $ \ bndrs ->
980 setLocalRdrEnv env $ do
981 { ((segs', thing), fvs) <- rn_segs env (bndrs ++ bndrs_so_far) segs
982 ; let used_bndrs = filter (`elemNameSet` fvs) bndrs
983 ; return ((used_bndrs, segs', thing), fvs) }
984
985 ; let seg' = ParStmtBlock x stmts' used_bndrs return_op
986 ; return ((seg':segs', thing), fvs) }
987 rn_segs _ _ (XParStmtBlock{}:_) = panic "rnParallelStmts"
988
989 cmpByOcc n1 n2 = nameOccName n1 `compare` nameOccName n2
990 dupErr vs = addErr (text "Duplicate binding in parallel list comprehension for:"
991 <+> quotes (ppr (NE.head vs)))
992
993 lookupStmtName :: HsStmtContext Name -> Name -> RnM (SyntaxExpr GhcRn, FreeVars)
994 -- Like lookupSyntaxName, but respects contexts
995 lookupStmtName ctxt n
996 | rebindableContext ctxt
997 = lookupSyntaxName n
998 | otherwise
999 = return (mkRnSyntaxExpr n, emptyFVs)
1000
1001 lookupStmtNamePoly :: HsStmtContext Name -> Name -> RnM (HsExpr GhcRn, FreeVars)
1002 lookupStmtNamePoly ctxt name
1003 | rebindableContext ctxt
1004 = do { rebindable_on <- xoptM LangExt.RebindableSyntax
1005 ; if rebindable_on
1006 then do { fm <- lookupOccRn (nameRdrName name)
1007 ; return (HsVar noExt (noLoc fm), unitFV fm) }
1008 else not_rebindable }
1009 | otherwise
1010 = not_rebindable
1011 where
1012 not_rebindable = return (HsVar noExt (noLoc name), emptyFVs)
1013
1014 -- | Is this a context where we respect RebindableSyntax?
1015 -- but ListComp are never rebindable
1016 -- Neither is ArrowExpr, which has its own desugarer in DsArrows
1017 rebindableContext :: HsStmtContext Name -> Bool
1018 rebindableContext ctxt = case ctxt of
1019 ListComp -> False
1020 ArrowExpr -> False
1021 PatGuard {} -> False
1022
1023 DoExpr -> True
1024 MDoExpr -> True
1025 MonadComp -> True
1026 GhciStmtCtxt -> True -- I suppose?
1027
1028 ParStmtCtxt c -> rebindableContext c -- Look inside to
1029 TransStmtCtxt c -> rebindableContext c -- the parent context
1030
1031 {-
1032 Note [Renaming parallel Stmts]
1033 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1034 Renaming parallel statements is painful. Given, say
1035 [ a+c | a <- as, bs <- bss
1036 | c <- bs, a <- ds ]
1037 Note that
1038 (a) In order to report "Defined but not used" about 'bs', we must
1039 rename each group of Stmts with a thing_inside whose FreeVars
1040 include at least {a,c}
1041
1042 (b) We want to report that 'a' is illegally bound in both branches
1043
1044 (c) The 'bs' in the second group must obviously not be captured by
1045 the binding in the first group
1046
1047 To satisfy (a) we nest the segements.
1048 To satisfy (b) we check for duplicates just before thing_inside.
1049 To satisfy (c) we reset the LocalRdrEnv each time.
1050
1051 ************************************************************************
1052 * *
1053 \subsubsection{mdo expressions}
1054 * *
1055 ************************************************************************
1056 -}
1057
1058 type FwdRefs = NameSet
1059 type Segment stmts = (Defs,
1060 Uses, -- May include defs
1061 FwdRefs, -- A subset of uses that are
1062 -- (a) used before they are bound in this segment, or
1063 -- (b) used here, and bound in subsequent segments
1064 stmts) -- Either Stmt or [Stmt]
1065
1066
1067 -- wrapper that does both the left- and right-hand sides
1068 rnRecStmtsAndThen :: Outputable (body GhcPs) =>
1069 (Located (body GhcPs)
1070 -> RnM (Located (body GhcRn), FreeVars))
1071 -> [LStmt GhcPs (Located (body GhcPs))]
1072 -- assumes that the FreeVars returned includes
1073 -- the FreeVars of the Segments
1074 -> ([Segment (LStmt GhcRn (Located (body GhcRn)))]
1075 -> RnM (a, FreeVars))
1076 -> RnM (a, FreeVars)
1077 rnRecStmtsAndThen rnBody s cont
1078 = do { -- (A) Make the mini fixity env for all of the stmts
1079 fix_env <- makeMiniFixityEnv (collectRecStmtsFixities s)
1080
1081 -- (B) Do the LHSes
1082 ; new_lhs_and_fv <- rn_rec_stmts_lhs fix_env s
1083
1084 -- ...bring them and their fixities into scope
1085 ; let bound_names = collectLStmtsBinders (map fst new_lhs_and_fv)
1086 -- Fake uses of variables introduced implicitly (warning suppression, see #4404)
1087 implicit_uses = lStmtsImplicits (map fst new_lhs_and_fv)
1088 ; bindLocalNamesFV bound_names $
1089 addLocalFixities fix_env bound_names $ do
1090
1091 -- (C) do the right-hand-sides and thing-inside
1092 { segs <- rn_rec_stmts rnBody bound_names new_lhs_and_fv
1093 ; (res, fvs) <- cont segs
1094 ; warnUnusedLocalBinds bound_names (fvs `unionNameSet` implicit_uses)
1095 ; return (res, fvs) }}
1096
1097 -- get all the fixity decls in any Let stmt
1098 collectRecStmtsFixities :: [LStmtLR GhcPs GhcPs body] -> [LFixitySig GhcPs]
1099 collectRecStmtsFixities l =
1100 foldr (\ s -> \acc -> case s of
1101 (L _ (LetStmt _ (L _ (HsValBinds _ (ValBinds _ _ sigs))))) ->
1102 foldr (\ sig -> \ acc -> case sig of
1103 (L loc (FixSig _ s)) -> (L loc s) : acc
1104 _ -> acc) acc sigs
1105 _ -> acc) [] l
1106
1107 -- left-hand sides
1108
1109 rn_rec_stmt_lhs :: Outputable body => MiniFixityEnv
1110 -> LStmt GhcPs body
1111 -- rename LHS, and return its FVs
1112 -- Warning: we will only need the FreeVars below in the case of a BindStmt,
1113 -- so we don't bother to compute it accurately in the other cases
1114 -> RnM [(LStmtLR GhcRn GhcPs body, FreeVars)]
1115
1116 rn_rec_stmt_lhs _ (L loc (BodyStmt _ body a b))
1117 = return [(L loc (BodyStmt noExt body a b), emptyFVs)]
1118
1119 rn_rec_stmt_lhs _ (L loc (LastStmt _ body noret a))
1120 = return [(L loc (LastStmt noExt body noret a), emptyFVs)]
1121
1122 rn_rec_stmt_lhs fix_env (L loc (BindStmt _ pat body a b))
1123 = do
1124 -- should the ctxt be MDo instead?
1125 (pat', fv_pat) <- rnBindPat (localRecNameMaker fix_env) pat
1126 return [(L loc (BindStmt noExt pat' body a b), fv_pat)]
1127
1128 rn_rec_stmt_lhs _ (L _ (LetStmt _ (L _ binds@(HsIPBinds {}))))
1129 = failWith (badIpBinds (text "an mdo expression") binds)
1130
1131 rn_rec_stmt_lhs fix_env (L loc (LetStmt _ (L l (HsValBinds x binds))))
1132 = do (_bound_names, binds') <- rnLocalValBindsLHS fix_env binds
1133 return [(L loc (LetStmt noExt (L l (HsValBinds x binds'))),
1134 -- Warning: this is bogus; see function invariant
1135 emptyFVs
1136 )]
1137
1138 -- XXX Do we need to do something with the return and mfix names?
1139 rn_rec_stmt_lhs fix_env (L _ (RecStmt { recS_stmts = stmts })) -- Flatten Rec inside Rec
1140 = rn_rec_stmts_lhs fix_env stmts
1141
1142 rn_rec_stmt_lhs _ stmt@(L _ (ParStmt {})) -- Syntactically illegal in mdo
1143 = pprPanic "rn_rec_stmt" (ppr stmt)
1144
1145 rn_rec_stmt_lhs _ stmt@(L _ (TransStmt {})) -- Syntactically illegal in mdo
1146 = pprPanic "rn_rec_stmt" (ppr stmt)
1147
1148 rn_rec_stmt_lhs _ stmt@(L _ (ApplicativeStmt {})) -- Shouldn't appear yet
1149 = pprPanic "rn_rec_stmt" (ppr stmt)
1150
1151 rn_rec_stmt_lhs _ (L _ (LetStmt _ (L _ (EmptyLocalBinds _))))
1152 = panic "rn_rec_stmt LetStmt EmptyLocalBinds"
1153 rn_rec_stmt_lhs _ (L _ (LetStmt _ (L _ (XHsLocalBindsLR _))))
1154 = panic "rn_rec_stmt LetStmt XHsLocalBindsLR"
1155 rn_rec_stmt_lhs _ (L _ (XStmtLR _))
1156 = panic "rn_rec_stmt XStmtLR"
1157
1158 rn_rec_stmts_lhs :: Outputable body => MiniFixityEnv
1159 -> [LStmt GhcPs body]
1160 -> RnM [(LStmtLR GhcRn GhcPs body, FreeVars)]
1161 rn_rec_stmts_lhs fix_env stmts
1162 = do { ls <- concatMapM (rn_rec_stmt_lhs fix_env) stmts
1163 ; let boundNames = collectLStmtsBinders (map fst ls)
1164 -- First do error checking: we need to check for dups here because we
1165 -- don't bind all of the variables from the Stmt at once
1166 -- with bindLocatedLocals.
1167 ; checkDupNames boundNames
1168 ; return ls }
1169
1170
1171 -- right-hand-sides
1172
1173 rn_rec_stmt :: (Outputable (body GhcPs)) =>
1174 (Located (body GhcPs) -> RnM (Located (body GhcRn), FreeVars))
1175 -> [Name]
1176 -> (LStmtLR GhcRn GhcPs (Located (body GhcPs)), FreeVars)
1177 -> RnM [Segment (LStmt GhcRn (Located (body GhcRn)))]
1178 -- Rename a Stmt that is inside a RecStmt (or mdo)
1179 -- Assumes all binders are already in scope
1180 -- Turns each stmt into a singleton Stmt
1181 rn_rec_stmt rnBody _ (L loc (LastStmt _ body noret _), _)
1182 = do { (body', fv_expr) <- rnBody body
1183 ; (ret_op, fvs1) <- lookupSyntaxName returnMName
1184 ; return [(emptyNameSet, fv_expr `plusFV` fvs1, emptyNameSet,
1185 L loc (LastStmt noExt body' noret ret_op))] }
1186
1187 rn_rec_stmt rnBody _ (L loc (BodyStmt _ body _ _), _)
1188 = do { (body', fvs) <- rnBody body
1189 ; (then_op, fvs1) <- lookupSyntaxName thenMName
1190 ; return [(emptyNameSet, fvs `plusFV` fvs1, emptyNameSet,
1191 L loc (BodyStmt noExt body' then_op noSyntaxExpr))] }
1192
1193 rn_rec_stmt rnBody _ (L loc (BindStmt _ pat' body _ _), fv_pat)
1194 = do { (body', fv_expr) <- rnBody body
1195 ; (bind_op, fvs1) <- lookupSyntaxName bindMName
1196
1197 ; xMonadFailEnabled <- fmap (xopt LangExt.MonadFailDesugaring) getDynFlags
1198 ; let failFunction | xMonadFailEnabled = failMName
1199 | otherwise = failMName_preMFP
1200 ; (fail_op, fvs2) <- lookupSyntaxName failFunction
1201
1202 ; let bndrs = mkNameSet (collectPatBinders pat')
1203 fvs = fv_expr `plusFV` fv_pat `plusFV` fvs1 `plusFV` fvs2
1204 ; return [(bndrs, fvs, bndrs `intersectNameSet` fvs,
1205 L loc (BindStmt noExt pat' body' bind_op fail_op))] }
1206
1207 rn_rec_stmt _ _ (L _ (LetStmt _ (L _ binds@(HsIPBinds {}))), _)
1208 = failWith (badIpBinds (text "an mdo expression") binds)
1209
1210 rn_rec_stmt _ all_bndrs (L loc (LetStmt _ (L l (HsValBinds x binds'))), _)
1211 = do { (binds', du_binds) <- rnLocalValBindsRHS (mkNameSet all_bndrs) binds'
1212 -- fixities and unused are handled above in rnRecStmtsAndThen
1213 ; let fvs = allUses du_binds
1214 ; return [(duDefs du_binds, fvs, emptyNameSet,
1215 L loc (LetStmt noExt (L l (HsValBinds x binds'))))] }
1216
1217 -- no RecStmt case because they get flattened above when doing the LHSes
1218 rn_rec_stmt _ _ stmt@(L _ (RecStmt {}), _)
1219 = pprPanic "rn_rec_stmt: RecStmt" (ppr stmt)
1220
1221 rn_rec_stmt _ _ stmt@(L _ (ParStmt {}), _) -- Syntactically illegal in mdo
1222 = pprPanic "rn_rec_stmt: ParStmt" (ppr stmt)
1223
1224 rn_rec_stmt _ _ stmt@(L _ (TransStmt {}), _) -- Syntactically illegal in mdo
1225 = pprPanic "rn_rec_stmt: TransStmt" (ppr stmt)
1226
1227 rn_rec_stmt _ _ (L _ (LetStmt _ (L _ (XHsLocalBindsLR _))), _)
1228 = panic "rn_rec_stmt: LetStmt XHsLocalBindsLR"
1229
1230 rn_rec_stmt _ _ (L _ (LetStmt _ (L _ (EmptyLocalBinds _))), _)
1231 = panic "rn_rec_stmt: LetStmt EmptyLocalBinds"
1232
1233 rn_rec_stmt _ _ stmt@(L _ (ApplicativeStmt {}), _)
1234 = pprPanic "rn_rec_stmt: ApplicativeStmt" (ppr stmt)
1235
1236 rn_rec_stmt _ _ stmt@(L _ (XStmtLR {}), _)
1237 = pprPanic "rn_rec_stmt: XStmtLR" (ppr stmt)
1238
1239 rn_rec_stmts :: Outputable (body GhcPs) =>
1240 (Located (body GhcPs) -> RnM (Located (body GhcRn), FreeVars))
1241 -> [Name]
1242 -> [(LStmtLR GhcRn GhcPs (Located (body GhcPs)), FreeVars)]
1243 -> RnM [Segment (LStmt GhcRn (Located (body GhcRn)))]
1244 rn_rec_stmts rnBody bndrs stmts
1245 = do { segs_s <- mapM (rn_rec_stmt rnBody bndrs) stmts
1246 ; return (concat segs_s) }
1247
1248 ---------------------------------------------
1249 segmentRecStmts :: SrcSpan -> HsStmtContext Name
1250 -> Stmt GhcRn body
1251 -> [Segment (LStmt GhcRn body)] -> FreeVars
1252 -> ([LStmt GhcRn body], FreeVars)
1253
1254 segmentRecStmts loc ctxt empty_rec_stmt segs fvs_later
1255 | null segs
1256 = ([], fvs_later)
1257
1258 | MDoExpr <- ctxt
1259 = segsToStmts empty_rec_stmt grouped_segs fvs_later
1260 -- Step 4: Turn the segments into Stmts
1261 -- Use RecStmt when and only when there are fwd refs
1262 -- Also gather up the uses from the end towards the
1263 -- start, so we can tell the RecStmt which things are
1264 -- used 'after' the RecStmt
1265
1266 | otherwise
1267 = ([ L loc $
1268 empty_rec_stmt { recS_stmts = ss
1269 , recS_later_ids = nameSetElemsStable
1270 (defs `intersectNameSet` fvs_later)
1271 , recS_rec_ids = nameSetElemsStable
1272 (defs `intersectNameSet` uses) }]
1273 -- See Note [Deterministic ApplicativeDo and RecursiveDo desugaring]
1274 , uses `plusFV` fvs_later)
1275
1276 where
1277 (defs_s, uses_s, _, ss) = unzip4 segs
1278 defs = plusFVs defs_s
1279 uses = plusFVs uses_s
1280
1281 -- Step 2: Fill in the fwd refs.
1282 -- The segments are all singletons, but their fwd-ref
1283 -- field mentions all the things used by the segment
1284 -- that are bound after their use
1285 segs_w_fwd_refs = addFwdRefs segs
1286
1287 -- Step 3: Group together the segments to make bigger segments
1288 -- Invariant: in the result, no segment uses a variable
1289 -- bound in a later segment
1290 grouped_segs = glomSegments ctxt segs_w_fwd_refs
1291
1292 ----------------------------
1293 addFwdRefs :: [Segment a] -> [Segment a]
1294 -- So far the segments only have forward refs *within* the Stmt
1295 -- (which happens for bind: x <- ...x...)
1296 -- This function adds the cross-seg fwd ref info
1297
1298 addFwdRefs segs
1299 = fst (foldr mk_seg ([], emptyNameSet) segs)
1300 where
1301 mk_seg (defs, uses, fwds, stmts) (segs, later_defs)
1302 = (new_seg : segs, all_defs)
1303 where
1304 new_seg = (defs, uses, new_fwds, stmts)
1305 all_defs = later_defs `unionNameSet` defs
1306 new_fwds = fwds `unionNameSet` (uses `intersectNameSet` later_defs)
1307 -- Add the downstream fwd refs here
1308
1309 {-
1310 Note [Segmenting mdo]
1311 ~~~~~~~~~~~~~~~~~~~~~
1312 NB. June 7 2012: We only glom segments that appear in an explicit mdo;
1313 and leave those found in "do rec"'s intact. See
1314 http://ghc.haskell.org/trac/ghc/ticket/4148 for the discussion
1315 leading to this design choice. Hence the test in segmentRecStmts.
1316
1317 Note [Glomming segments]
1318 ~~~~~~~~~~~~~~~~~~~~~~~~
1319 Glomming the singleton segments of an mdo into minimal recursive groups.
1320
1321 At first I thought this was just strongly connected components, but
1322 there's an important constraint: the order of the stmts must not change.
1323
1324 Consider
1325 mdo { x <- ...y...
1326 p <- z
1327 y <- ...x...
1328 q <- x
1329 z <- y
1330 r <- x }
1331
1332 Here, the first stmt mention 'y', which is bound in the third.
1333 But that means that the innocent second stmt (p <- z) gets caught
1334 up in the recursion. And that in turn means that the binding for
1335 'z' has to be included... and so on.
1336
1337 Start at the tail { r <- x }
1338 Now add the next one { z <- y ; r <- x }
1339 Now add one more { q <- x ; z <- y ; r <- x }
1340 Now one more... but this time we have to group a bunch into rec
1341 { rec { y <- ...x... ; q <- x ; z <- y } ; r <- x }
1342 Now one more, which we can add on without a rec
1343 { p <- z ;
1344 rec { y <- ...x... ; q <- x ; z <- y } ;
1345 r <- x }
1346 Finally we add the last one; since it mentions y we have to
1347 glom it together with the first two groups
1348 { rec { x <- ...y...; p <- z ; y <- ...x... ;
1349 q <- x ; z <- y } ;
1350 r <- x }
1351 -}
1352
1353 glomSegments :: HsStmtContext Name
1354 -> [Segment (LStmt GhcRn body)]
1355 -> [Segment [LStmt GhcRn body]]
1356 -- Each segment has a non-empty list of Stmts
1357 -- See Note [Glomming segments]
1358
1359 glomSegments _ [] = []
1360 glomSegments ctxt ((defs,uses,fwds,stmt) : segs)
1361 -- Actually stmts will always be a singleton
1362 = (seg_defs, seg_uses, seg_fwds, seg_stmts) : others
1363 where
1364 segs' = glomSegments ctxt segs
1365 (extras, others) = grab uses segs'
1366 (ds, us, fs, ss) = unzip4 extras
1367
1368 seg_defs = plusFVs ds `plusFV` defs
1369 seg_uses = plusFVs us `plusFV` uses
1370 seg_fwds = plusFVs fs `plusFV` fwds
1371 seg_stmts = stmt : concat ss
1372
1373 grab :: NameSet -- The client
1374 -> [Segment a]
1375 -> ([Segment a], -- Needed by the 'client'
1376 [Segment a]) -- Not needed by the client
1377 -- The result is simply a split of the input
1378 grab uses dus
1379 = (reverse yeses, reverse noes)
1380 where
1381 (noes, yeses) = span not_needed (reverse dus)
1382 not_needed (defs,_,_,_) = not (intersectsNameSet defs uses)
1383
1384 ----------------------------------------------------
1385 segsToStmts :: Stmt GhcRn body
1386 -- A RecStmt with the SyntaxOps filled in
1387 -> [Segment [LStmt GhcRn body]]
1388 -- Each Segment has a non-empty list of Stmts
1389 -> FreeVars -- Free vars used 'later'
1390 -> ([LStmt GhcRn body], FreeVars)
1391
1392 segsToStmts _ [] fvs_later = ([], fvs_later)
1393 segsToStmts empty_rec_stmt ((defs, uses, fwds, ss) : segs) fvs_later
1394 = ASSERT( not (null ss) )
1395 (new_stmt : later_stmts, later_uses `plusFV` uses)
1396 where
1397 (later_stmts, later_uses) = segsToStmts empty_rec_stmt segs fvs_later
1398 new_stmt | non_rec = head ss
1399 | otherwise = L (getLoc (head ss)) rec_stmt
1400 rec_stmt = empty_rec_stmt { recS_stmts = ss
1401 , recS_later_ids = nameSetElemsStable used_later
1402 , recS_rec_ids = nameSetElemsStable fwds }
1403 -- See Note [Deterministic ApplicativeDo and RecursiveDo desugaring]
1404 non_rec = isSingleton ss && isEmptyNameSet fwds
1405 used_later = defs `intersectNameSet` later_uses
1406 -- The ones needed after the RecStmt
1407
1408 {-
1409 ************************************************************************
1410 * *
1411 ApplicativeDo
1412 * *
1413 ************************************************************************
1414
1415 Note [ApplicativeDo]
1416
1417 = Example =
1418
1419 For a sequence of statements
1420
1421 do
1422 x <- A
1423 y <- B x
1424 z <- C
1425 return (f x y z)
1426
1427 We want to transform this to
1428
1429 (\(x,y) z -> f x y z) <$> (do x <- A; y <- B x; return (x,y)) <*> C
1430
1431 It would be easy to notice that "y <- B x" and "z <- C" are
1432 independent and do something like this:
1433
1434 do
1435 x <- A
1436 (y,z) <- (,) <$> B x <*> C
1437 return (f x y z)
1438
1439 But this isn't enough! A and C were also independent, and this
1440 transformation loses the ability to do A and C in parallel.
1441
1442 The algorithm works by first splitting the sequence of statements into
1443 independent "segments", and a separate "tail" (the final statement). In
1444 our example above, the segements would be
1445
1446 [ x <- A
1447 , y <- B x ]
1448
1449 [ z <- C ]
1450
1451 and the tail is:
1452
1453 return (f x y z)
1454
1455 Then we take these segments and make an Applicative expression from them:
1456
1457 (\(x,y) z -> return (f x y z))
1458 <$> do { x <- A; y <- B x; return (x,y) }
1459 <*> C
1460
1461 Finally, we recursively apply the transformation to each segment, to
1462 discover any nested parallelism.
1463
1464 = Syntax & spec =
1465
1466 expr ::= ... | do {stmt_1; ..; stmt_n} expr | ...
1467
1468 stmt ::= pat <- expr
1469 | (arg_1 | ... | arg_n) -- applicative composition, n>=1
1470 | ... -- other kinds of statement (e.g. let)
1471
1472 arg ::= pat <- expr
1473 | {stmt_1; ..; stmt_n} {var_1..var_n}
1474
1475 (note that in the actual implementation,the expr in a do statement is
1476 represented by a LastStmt as the final stmt, this is just a
1477 representational issue and may change later.)
1478
1479 == Transformation to introduce applicative stmts ==
1480
1481 ado {} tail = tail
1482 ado {pat <- expr} {return expr'} = (mkArg(pat <- expr)); return expr'
1483 ado {one} tail = one : tail
1484 ado stmts tail
1485 | n == 1 = ado before (ado after tail)
1486 where (before,after) = split(stmts_1)
1487 | n > 1 = (mkArg(stmts_1) | ... | mkArg(stmts_n)); tail
1488 where
1489 {stmts_1 .. stmts_n} = segments(stmts)
1490
1491 segments(stmts) =
1492 -- divide stmts into segments with no interdependencies
1493
1494 mkArg({pat <- expr}) = (pat <- expr)
1495 mkArg({stmt_1; ...; stmt_n}) =
1496 {stmt_1; ...; stmt_n} {vars(stmt_1) u .. u vars(stmt_n)}
1497
1498 split({stmt_1; ..; stmt_n) =
1499 ({stmt_1; ..; stmt_i}, {stmt_i+1; ..; stmt_n})
1500 -- 1 <= i <= n
1501 -- i is a good place to insert a bind
1502
1503 == Desugaring for do ==
1504
1505 dsDo {} expr = expr
1506
1507 dsDo {pat <- rhs; stmts} expr =
1508 rhs >>= \pat -> dsDo stmts expr
1509
1510 dsDo {(arg_1 | ... | arg_n)} (return expr) =
1511 (\argpat (arg_1) .. argpat(arg_n) -> expr)
1512 <$> argexpr(arg_1)
1513 <*> ...
1514 <*> argexpr(arg_n)
1515
1516 dsDo {(arg_1 | ... | arg_n); stmts} expr =
1517 join (\argpat (arg_1) .. argpat(arg_n) -> dsDo stmts expr)
1518 <$> argexpr(arg_1)
1519 <*> ...
1520 <*> argexpr(arg_n)
1521
1522 -}
1523
1524 -- | The 'Name's of @return@ and @pure@. These may not be 'returnName' and
1525 -- 'pureName' due to @RebindableSyntax@.
1526 data MonadNames = MonadNames { return_name, pure_name :: Name }
1527
1528 -- | rearrange a list of statements using ApplicativeDoStmt. See
1529 -- Note [ApplicativeDo].
1530 rearrangeForApplicativeDo
1531 :: HsStmtContext Name
1532 -> [(ExprLStmt GhcRn, FreeVars)]
1533 -> RnM ([ExprLStmt GhcRn], FreeVars)
1534
1535 rearrangeForApplicativeDo _ [] = return ([], emptyNameSet)
1536 rearrangeForApplicativeDo _ [(one,_)] = return ([one], emptyNameSet)
1537 rearrangeForApplicativeDo ctxt stmts0 = do
1538 optimal_ado <- goptM Opt_OptimalApplicativeDo
1539 let stmt_tree | optimal_ado = mkStmtTreeOptimal stmts
1540 | otherwise = mkStmtTreeHeuristic stmts
1541 traceRn "rearrangeForADo" (ppr stmt_tree)
1542 return_name <- lookupSyntaxName' returnMName
1543 pure_name <- lookupSyntaxName' pureAName
1544 let monad_names = MonadNames { return_name = return_name
1545 , pure_name = pure_name }
1546 stmtTreeToStmts monad_names ctxt stmt_tree [last] last_fvs
1547 where
1548 (stmts,(last,last_fvs)) = findLast stmts0
1549 findLast [] = error "findLast"
1550 findLast [last] = ([],last)
1551 findLast (x:xs) = (x:rest,last) where (rest,last) = findLast xs
1552
1553 -- | A tree of statements using a mixture of applicative and bind constructs.
1554 data StmtTree a
1555 = StmtTreeOne a
1556 | StmtTreeBind (StmtTree a) (StmtTree a)
1557 | StmtTreeApplicative [StmtTree a]
1558
1559 instance Outputable a => Outputable (StmtTree a) where
1560 ppr (StmtTreeOne x) = parens (text "StmtTreeOne" <+> ppr x)
1561 ppr (StmtTreeBind x y) = parens (hang (text "StmtTreeBind")
1562 2 (sep [ppr x, ppr y]))
1563 ppr (StmtTreeApplicative xs) = parens (hang (text "StmtTreeApplicative")
1564 2 (vcat (map ppr xs)))
1565
1566 flattenStmtTree :: StmtTree a -> [a]
1567 flattenStmtTree t = go t []
1568 where
1569 go (StmtTreeOne a) as = a : as
1570 go (StmtTreeBind l r) as = go l (go r as)
1571 go (StmtTreeApplicative ts) as = foldr go as ts
1572
1573 type ExprStmtTree = StmtTree (ExprLStmt GhcRn, FreeVars)
1574 type Cost = Int
1575
1576 -- | Turn a sequence of statements into an ExprStmtTree using a
1577 -- heuristic algorithm. /O(n^2)/
1578 mkStmtTreeHeuristic :: [(ExprLStmt GhcRn, FreeVars)] -> ExprStmtTree
1579 mkStmtTreeHeuristic [one] = StmtTreeOne one
1580 mkStmtTreeHeuristic stmts =
1581 case segments stmts of
1582 [one] -> split one
1583 segs -> StmtTreeApplicative (map split segs)
1584 where
1585 split [one] = StmtTreeOne one
1586 split stmts =
1587 StmtTreeBind (mkStmtTreeHeuristic before) (mkStmtTreeHeuristic after)
1588 where (before, after) = splitSegment stmts
1589
1590 -- | Turn a sequence of statements into an ExprStmtTree optimally,
1591 -- using dynamic programming. /O(n^3)/
1592 mkStmtTreeOptimal :: [(ExprLStmt GhcRn, FreeVars)] -> ExprStmtTree
1593 mkStmtTreeOptimal stmts =
1594 ASSERT(not (null stmts)) -- the empty case is handled by the caller;
1595 -- we don't support empty StmtTrees.
1596 fst (arr ! (0,n))
1597 where
1598 n = length stmts - 1
1599 stmt_arr = listArray (0,n) stmts
1600
1601 -- lazy cache of optimal trees for subsequences of the input
1602 arr :: Array (Int,Int) (ExprStmtTree, Cost)
1603 arr = array ((0,0),(n,n))
1604 [ ((lo,hi), tree lo hi)
1605 | lo <- [0..n]
1606 , hi <- [lo..n] ]
1607
1608 -- compute the optimal tree for the sequence [lo..hi]
1609 tree lo hi
1610 | hi == lo = (StmtTreeOne (stmt_arr ! lo), 1)
1611 | otherwise =
1612 case segments [ stmt_arr ! i | i <- [lo..hi] ] of
1613 [] -> panic "mkStmtTree"
1614 [_one] -> split lo hi
1615 segs -> (StmtTreeApplicative trees, maximum costs)
1616 where
1617 bounds = scanl (\(_,hi) a -> (hi+1, hi + length a)) (0,lo-1) segs
1618 (trees,costs) = unzip (map (uncurry split) (tail bounds))
1619
1620 -- find the best place to split the segment [lo..hi]
1621 split :: Int -> Int -> (ExprStmtTree, Cost)
1622 split lo hi
1623 | hi == lo = (StmtTreeOne (stmt_arr ! lo), 1)
1624 | otherwise = (StmtTreeBind before after, c1+c2)
1625 where
1626 -- As per the paper, for a sequence s1...sn, we want to find
1627 -- the split with the minimum cost, where the cost is the
1628 -- sum of the cost of the left and right subsequences.
1629 --
1630 -- As an optimisation (also in the paper) if the cost of
1631 -- s1..s(n-1) is different from the cost of s2..sn, we know
1632 -- that the optimal solution is the lower of the two. Only
1633 -- in the case that these two have the same cost do we need
1634 -- to do the exhaustive search.
1635 --
1636 ((before,c1),(after,c2))
1637 | hi - lo == 1
1638 = ((StmtTreeOne (stmt_arr ! lo), 1),
1639 (StmtTreeOne (stmt_arr ! hi), 1))
1640 | left_cost < right_cost
1641 = ((left,left_cost), (StmtTreeOne (stmt_arr ! hi), 1))
1642 | left_cost > right_cost
1643 = ((StmtTreeOne (stmt_arr ! lo), 1), (right,right_cost))
1644 | otherwise = minimumBy (comparing cost) alternatives
1645 where
1646 (left, left_cost) = arr ! (lo,hi-1)
1647 (right, right_cost) = arr ! (lo+1,hi)
1648 cost ((_,c1),(_,c2)) = c1 + c2
1649 alternatives = [ (arr ! (lo,k), arr ! (k+1,hi))
1650 | k <- [lo .. hi-1] ]
1651
1652
1653 -- | Turn the ExprStmtTree back into a sequence of statements, using
1654 -- ApplicativeStmt where necessary.
1655 stmtTreeToStmts
1656 :: MonadNames
1657 -> HsStmtContext Name
1658 -> ExprStmtTree
1659 -> [ExprLStmt GhcRn] -- ^ the "tail"
1660 -> FreeVars -- ^ free variables of the tail
1661 -> RnM ( [ExprLStmt GhcRn] -- ( output statements,
1662 , FreeVars ) -- , things we needed
1663
1664 -- If we have a single bind, and we can do it without a join, transform
1665 -- to an ApplicativeStmt. This corresponds to the rule
1666 -- dsBlock [pat <- rhs] (return expr) = expr <$> rhs
1667 -- In the spec, but we do it here rather than in the desugarer,
1668 -- because we need the typechecker to typecheck the <$> form rather than
1669 -- the bind form, which would give rise to a Monad constraint.
1670 stmtTreeToStmts monad_names ctxt (StmtTreeOne (L _ (BindStmt _ pat rhs _ _), _))
1671 tail _tail_fvs
1672 | not (isStrictPattern pat), (False,tail') <- needJoin monad_names tail
1673 -- See Note [ApplicativeDo and strict patterns]
1674 = mkApplicativeStmt ctxt [ApplicativeArgOne noExt pat rhs False] False tail'
1675 stmtTreeToStmts monad_names ctxt (StmtTreeOne (L _ (BodyStmt _ rhs _ _),_))
1676 tail _tail_fvs
1677 | (False,tail') <- needJoin monad_names tail
1678 = mkApplicativeStmt ctxt
1679 [ApplicativeArgOne noExt nlWildPatName rhs True] False tail'
1680
1681 stmtTreeToStmts _monad_names _ctxt (StmtTreeOne (s,_)) tail _tail_fvs =
1682 return (s : tail, emptyNameSet)
1683
1684 stmtTreeToStmts monad_names ctxt (StmtTreeBind before after) tail tail_fvs = do
1685 (stmts1, fvs1) <- stmtTreeToStmts monad_names ctxt after tail tail_fvs
1686 let tail1_fvs = unionNameSets (tail_fvs : map snd (flattenStmtTree after))
1687 (stmts2, fvs2) <- stmtTreeToStmts monad_names ctxt before stmts1 tail1_fvs
1688 return (stmts2, fvs1 `plusFV` fvs2)
1689
1690 stmtTreeToStmts monad_names ctxt (StmtTreeApplicative trees) tail tail_fvs = do
1691 pairs <- mapM (stmtTreeArg ctxt tail_fvs) trees
1692 let (stmts', fvss) = unzip pairs
1693 let (need_join, tail') = needJoin monad_names tail
1694 (stmts, fvs) <- mkApplicativeStmt ctxt stmts' need_join tail'
1695 return (stmts, unionNameSets (fvs:fvss))
1696 where
1697 stmtTreeArg _ctxt _tail_fvs (StmtTreeOne (L _ (BindStmt _ pat exp _ _), _))
1698 = return (ApplicativeArgOne noExt pat exp False, emptyFVs)
1699 stmtTreeArg _ctxt _tail_fvs (StmtTreeOne (L _ (BodyStmt _ exp _ _), _)) =
1700 return (ApplicativeArgOne noExt nlWildPatName exp True, emptyFVs)
1701 stmtTreeArg ctxt tail_fvs tree = do
1702 let stmts = flattenStmtTree tree
1703 pvarset = mkNameSet (concatMap (collectStmtBinders.unLoc.fst) stmts)
1704 `intersectNameSet` tail_fvs
1705 pvars = nameSetElemsStable pvarset
1706 -- See Note [Deterministic ApplicativeDo and RecursiveDo desugaring]
1707 pat = mkBigLHsVarPatTup pvars
1708 tup = mkBigLHsVarTup pvars
1709 (stmts',fvs2) <- stmtTreeToStmts monad_names ctxt tree [] pvarset
1710 (mb_ret, fvs1) <-
1711 if | L _ ApplicativeStmt{} <- last stmts' ->
1712 return (unLoc tup, emptyNameSet)
1713 | otherwise -> do
1714 (ret,fvs) <- lookupStmtNamePoly ctxt returnMName
1715 return (HsApp noExt (noLoc ret) tup, fvs)
1716 return ( ApplicativeArgMany noExt stmts' mb_ret pat
1717 , fvs1 `plusFV` fvs2)
1718
1719
1720 -- | Divide a sequence of statements into segments, where no segment
1721 -- depends on any variables defined by a statement in another segment.
1722 segments
1723 :: [(ExprLStmt GhcRn, FreeVars)]
1724 -> [[(ExprLStmt GhcRn, FreeVars)]]
1725 segments stmts = map fst $ merge $ reverse $ map reverse $ walk (reverse stmts)
1726 where
1727 allvars = mkNameSet (concatMap (collectStmtBinders.unLoc.fst) stmts)
1728
1729 -- We would rather not have a segment that just has LetStmts in
1730 -- it, so combine those with an adjacent segment where possible.
1731 merge [] = []
1732 merge (seg : segs)
1733 = case rest of
1734 [] -> [(seg,all_lets)]
1735 ((s,s_lets):ss) | all_lets || s_lets
1736 -> (seg ++ s, all_lets && s_lets) : ss
1737 _otherwise -> (seg,all_lets) : rest
1738 where
1739 rest = merge segs
1740 all_lets = all (isLetStmt . fst) seg
1741
1742 -- walk splits the statement sequence into segments, traversing
1743 -- the sequence from the back to the front, and keeping track of
1744 -- the set of free variables of the current segment. Whenever
1745 -- this set of free variables is empty, we have a complete segment.
1746 walk :: [(ExprLStmt GhcRn, FreeVars)] -> [[(ExprLStmt GhcRn, FreeVars)]]
1747 walk [] = []
1748 walk ((stmt,fvs) : stmts) = ((stmt,fvs) : seg) : walk rest
1749 where (seg,rest) = chunter fvs' stmts
1750 (_, fvs') = stmtRefs stmt fvs
1751
1752 chunter _ [] = ([], [])
1753 chunter vars ((stmt,fvs) : rest)
1754 | not (isEmptyNameSet vars)
1755 || isStrictPatternBind stmt
1756 -- See Note [ApplicativeDo and strict patterns]
1757 = ((stmt,fvs) : chunk, rest')
1758 where (chunk,rest') = chunter vars' rest
1759 (pvars, evars) = stmtRefs stmt fvs
1760 vars' = (vars `minusNameSet` pvars) `unionNameSet` evars
1761 chunter _ rest = ([], rest)
1762
1763 stmtRefs stmt fvs
1764 | isLetStmt stmt = (pvars, fvs' `minusNameSet` pvars)
1765 | otherwise = (pvars, fvs')
1766 where fvs' = fvs `intersectNameSet` allvars
1767 pvars = mkNameSet (collectStmtBinders (unLoc stmt))
1768
1769 isStrictPatternBind :: ExprLStmt GhcRn -> Bool
1770 isStrictPatternBind (L _ (BindStmt _ pat _ _ _)) = isStrictPattern pat
1771 isStrictPatternBind _ = False
1772
1773 {-
1774 Note [ApplicativeDo and strict patterns]
1775
1776 A strict pattern match is really a dependency. For example,
1777
1778 do
1779 (x,y) <- A
1780 z <- B
1781 return C
1782
1783 The pattern (_,_) must be matched strictly before we do B. If we
1784 allowed this to be transformed into
1785
1786 (\(x,y) -> \z -> C) <$> A <*> B
1787
1788 then it could be lazier than the standard desuraging using >>=. See #13875
1789 for more examples.
1790
1791 Thus, whenever we have a strict pattern match, we treat it as a
1792 dependency between that statement and the following one. The
1793 dependency prevents those two statements from being performed "in
1794 parallel" in an ApplicativeStmt, but doesn't otherwise affect what we
1795 can do with the rest of the statements in the same "do" expression.
1796 -}
1797
1798 isStrictPattern :: LPat id -> Bool
1799 isStrictPattern (L _ pat) =
1800 case pat of
1801 WildPat{} -> False
1802 VarPat{} -> False
1803 LazyPat{} -> False
1804 AsPat _ _ p -> isStrictPattern p
1805 ParPat _ p -> isStrictPattern p
1806 ViewPat _ _ p -> isStrictPattern p
1807 SigPat _ p -> isStrictPattern p
1808 BangPat{} -> True
1809 ListPat{} -> True
1810 TuplePat{} -> True
1811 SumPat{} -> True
1812 ConPatIn{} -> True
1813 ConPatOut{} -> True
1814 LitPat{} -> True
1815 NPat{} -> True
1816 NPlusKPat{} -> True
1817 SplicePat{} -> True
1818 _otherwise -> panic "isStrictPattern"
1819
1820 isLetStmt :: LStmt a b -> Bool
1821 isLetStmt (L _ LetStmt{}) = True
1822 isLetStmt _ = False
1823
1824 -- | Find a "good" place to insert a bind in an indivisible segment.
1825 -- This is the only place where we use heuristics. The current
1826 -- heuristic is to peel off the first group of independent statements
1827 -- and put the bind after those.
1828 splitSegment
1829 :: [(ExprLStmt GhcRn, FreeVars)]
1830 -> ( [(ExprLStmt GhcRn, FreeVars)]
1831 , [(ExprLStmt GhcRn, FreeVars)] )
1832 splitSegment [one,two] = ([one],[two])
1833 -- there is no choice when there are only two statements; this just saves
1834 -- some work in a common case.
1835 splitSegment stmts
1836 | Just (lets,binds,rest) <- slurpIndependentStmts stmts
1837 = if not (null lets)
1838 then (lets, binds++rest)
1839 else (lets++binds, rest)
1840 | otherwise
1841 = case stmts of
1842 (x:xs) -> ([x],xs)
1843 _other -> (stmts,[])
1844
1845 slurpIndependentStmts
1846 :: [(LStmt GhcRn (Located (body GhcRn)), FreeVars)]
1847 -> Maybe ( [(LStmt GhcRn (Located (body GhcRn)), FreeVars)] -- LetStmts
1848 , [(LStmt GhcRn (Located (body GhcRn)), FreeVars)] -- BindStmts
1849 , [(LStmt GhcRn (Located (body GhcRn)), FreeVars)] )
1850 slurpIndependentStmts stmts = go [] [] emptyNameSet stmts
1851 where
1852 -- If we encounter a BindStmt that doesn't depend on a previous BindStmt
1853 -- in this group, then add it to the group. We have to be careful about
1854 -- strict patterns though; splitSegments expects that if we return Just
1855 -- then we have actually done some splitting. Otherwise it will go into
1856 -- an infinite loop (#14163).
1857 go lets indep bndrs ((L loc (BindStmt _ pat body bind_op fail_op), fvs): rest)
1858 | isEmptyNameSet (bndrs `intersectNameSet` fvs) && not (isStrictPattern pat)
1859 = go lets ((L loc (BindStmt noExt pat body bind_op fail_op), fvs) : indep)
1860 bndrs' rest
1861 where bndrs' = bndrs `unionNameSet` mkNameSet (collectPatBinders pat)
1862 -- If we encounter a LetStmt that doesn't depend on a BindStmt in this
1863 -- group, then move it to the beginning, so that it doesn't interfere with
1864 -- grouping more BindStmts.
1865 -- TODO: perhaps we shouldn't do this if there are any strict bindings,
1866 -- because we might be moving evaluation earlier.
1867 go lets indep bndrs ((L loc (LetStmt noExt binds), fvs) : rest)
1868 | isEmptyNameSet (bndrs `intersectNameSet` fvs)
1869 = go ((L loc (LetStmt noExt binds), fvs) : lets) indep bndrs rest
1870 go _ [] _ _ = Nothing
1871 go _ [_] _ _ = Nothing
1872 go lets indep _ stmts = Just (reverse lets, reverse indep, stmts)
1873
1874 -- | Build an ApplicativeStmt, and strip the "return" from the tail
1875 -- if necessary.
1876 --
1877 -- For example, if we start with
1878 -- do x <- E1; y <- E2; return (f x y)
1879 -- then we get
1880 -- do (E1[x] | E2[y]); f x y
1881 --
1882 -- the LastStmt in this case has the return removed, but we set the
1883 -- flag on the LastStmt to indicate this, so that we can print out the
1884 -- original statement correctly in error messages. It is easier to do
1885 -- it this way rather than try to ignore the return later in both the
1886 -- typechecker and the desugarer (I tried it that way first!).
1887 mkApplicativeStmt
1888 :: HsStmtContext Name
1889 -> [ApplicativeArg GhcRn] -- ^ The args
1890 -> Bool -- ^ True <=> need a join
1891 -> [ExprLStmt GhcRn] -- ^ The body statements
1892 -> RnM ([ExprLStmt GhcRn], FreeVars)
1893 mkApplicativeStmt ctxt args need_join body_stmts
1894 = do { (fmap_op, fvs1) <- lookupStmtName ctxt fmapName
1895 ; (ap_op, fvs2) <- lookupStmtName ctxt apAName
1896 ; (mb_join, fvs3) <-
1897 if need_join then
1898 do { (join_op, fvs) <- lookupStmtName ctxt joinMName
1899 ; return (Just join_op, fvs) }
1900 else
1901 return (Nothing, emptyNameSet)
1902 ; let applicative_stmt = noLoc $ ApplicativeStmt noExt
1903 (zip (fmap_op : repeat ap_op) args)
1904 mb_join
1905 ; return ( applicative_stmt : body_stmts
1906 , fvs1 `plusFV` fvs2 `plusFV` fvs3) }
1907
1908 -- | Given the statements following an ApplicativeStmt, determine whether
1909 -- we need a @join@ or not, and remove the @return@ if necessary.
1910 needJoin :: MonadNames
1911 -> [ExprLStmt GhcRn]
1912 -> (Bool, [ExprLStmt GhcRn])
1913 needJoin _monad_names [] = (False, []) -- we're in an ApplicativeArg
1914 needJoin monad_names [L loc (LastStmt _ e _ t)]
1915 | Just arg <- isReturnApp monad_names e =
1916 (False, [L loc (LastStmt noExt arg True t)])
1917 needJoin _monad_names stmts = (True, stmts)
1918
1919 -- | @Just e@, if the expression is @return e@ or @return $ e@,
1920 -- otherwise @Nothing@
1921 isReturnApp :: MonadNames
1922 -> LHsExpr GhcRn
1923 -> Maybe (LHsExpr GhcRn)
1924 isReturnApp monad_names (L _ (HsPar _ expr)) = isReturnApp monad_names expr
1925 isReturnApp monad_names (L _ e) = case e of
1926 OpApp _ l op r | is_return l, is_dollar op -> Just r
1927 HsApp _ f arg | is_return f -> Just arg
1928 _otherwise -> Nothing
1929 where
1930 is_var f (L _ (HsPar _ e)) = is_var f e
1931 is_var f (L _ (HsAppType _ e)) = is_var f e
1932 is_var f (L _ (HsVar _ (L _ r))) = f r
1933 -- TODO: I don't know how to get this right for rebindable syntax
1934 is_var _ _ = False
1935
1936 is_return = is_var (\n -> n == return_name monad_names
1937 || n == pure_name monad_names)
1938 is_dollar = is_var (`hasKey` dollarIdKey)
1939
1940 {-
1941 ************************************************************************
1942 * *
1943 \subsubsection{Errors}
1944 * *
1945 ************************************************************************
1946 -}
1947
1948 checkEmptyStmts :: HsStmtContext Name -> RnM ()
1949 -- We've seen an empty sequence of Stmts... is that ok?
1950 checkEmptyStmts ctxt
1951 = unless (okEmpty ctxt) (addErr (emptyErr ctxt))
1952
1953 okEmpty :: HsStmtContext a -> Bool
1954 okEmpty (PatGuard {}) = True
1955 okEmpty _ = False
1956
1957 emptyErr :: HsStmtContext Name -> SDoc
1958 emptyErr (ParStmtCtxt {}) = text "Empty statement group in parallel comprehension"
1959 emptyErr (TransStmtCtxt {}) = text "Empty statement group preceding 'group' or 'then'"
1960 emptyErr ctxt = text "Empty" <+> pprStmtContext ctxt
1961
1962 ----------------------
1963 checkLastStmt :: Outputable (body GhcPs) => HsStmtContext Name
1964 -> LStmt GhcPs (Located (body GhcPs))
1965 -> RnM (LStmt GhcPs (Located (body GhcPs)))
1966 checkLastStmt ctxt lstmt@(L loc stmt)
1967 = case ctxt of
1968 ListComp -> check_comp
1969 MonadComp -> check_comp
1970 ArrowExpr -> check_do
1971 DoExpr -> check_do
1972 MDoExpr -> check_do
1973 _ -> check_other
1974 where
1975 check_do -- Expect BodyStmt, and change it to LastStmt
1976 = case stmt of
1977 BodyStmt _ e _ _ -> return (L loc (mkLastStmt e))
1978 LastStmt {} -> return lstmt -- "Deriving" clauses may generate a
1979 -- LastStmt directly (unlike the parser)
1980 _ -> do { addErr (hang last_error 2 (ppr stmt)); return lstmt }
1981 last_error = (text "The last statement in" <+> pprAStmtContext ctxt
1982 <+> text "must be an expression")
1983
1984 check_comp -- Expect LastStmt; this should be enforced by the parser!
1985 = case stmt of
1986 LastStmt {} -> return lstmt
1987 _ -> pprPanic "checkLastStmt" (ppr lstmt)
1988
1989 check_other -- Behave just as if this wasn't the last stmt
1990 = do { checkStmt ctxt lstmt; return lstmt }
1991
1992 -- Checking when a particular Stmt is ok
1993 checkStmt :: HsStmtContext Name
1994 -> LStmt GhcPs (Located (body GhcPs))
1995 -> RnM ()
1996 checkStmt ctxt (L _ stmt)
1997 = do { dflags <- getDynFlags
1998 ; case okStmt dflags ctxt stmt of
1999 IsValid -> return ()
2000 NotValid extra -> addErr (msg $$ extra) }
2001 where
2002 msg = sep [ text "Unexpected" <+> pprStmtCat stmt <+> ptext (sLit "statement")
2003 , text "in" <+> pprAStmtContext ctxt ]
2004
2005 pprStmtCat :: Stmt a body -> SDoc
2006 pprStmtCat (TransStmt {}) = text "transform"
2007 pprStmtCat (LastStmt {}) = text "return expression"
2008 pprStmtCat (BodyStmt {}) = text "body"
2009 pprStmtCat (BindStmt {}) = text "binding"
2010 pprStmtCat (LetStmt {}) = text "let"
2011 pprStmtCat (RecStmt {}) = text "rec"
2012 pprStmtCat (ParStmt {}) = text "parallel"
2013 pprStmtCat (ApplicativeStmt {}) = panic "pprStmtCat: ApplicativeStmt"
2014 pprStmtCat (XStmtLR {}) = panic "pprStmtCat: XStmtLR"
2015
2016 ------------
2017 emptyInvalid :: Validity -- Payload is the empty document
2018 emptyInvalid = NotValid Outputable.empty
2019
2020 okStmt, okDoStmt, okCompStmt, okParStmt
2021 :: DynFlags -> HsStmtContext Name
2022 -> Stmt GhcPs (Located (body GhcPs)) -> Validity
2023 -- Return Nothing if OK, (Just extra) if not ok
2024 -- The "extra" is an SDoc that is appended to a generic error message
2025
2026 okStmt dflags ctxt stmt
2027 = case ctxt of
2028 PatGuard {} -> okPatGuardStmt stmt
2029 ParStmtCtxt ctxt -> okParStmt dflags ctxt stmt
2030 DoExpr -> okDoStmt dflags ctxt stmt
2031 MDoExpr -> okDoStmt dflags ctxt stmt
2032 ArrowExpr -> okDoStmt dflags ctxt stmt
2033 GhciStmtCtxt -> okDoStmt dflags ctxt stmt
2034 ListComp -> okCompStmt dflags ctxt stmt
2035 MonadComp -> okCompStmt dflags ctxt stmt
2036 TransStmtCtxt ctxt -> okStmt dflags ctxt stmt
2037
2038 -------------
2039 okPatGuardStmt :: Stmt GhcPs (Located (body GhcPs)) -> Validity
2040 okPatGuardStmt stmt
2041 = case stmt of
2042 BodyStmt {} -> IsValid
2043 BindStmt {} -> IsValid
2044 LetStmt {} -> IsValid
2045 _ -> emptyInvalid
2046
2047 -------------
2048 okParStmt dflags ctxt stmt
2049 = case stmt of
2050 LetStmt _ (L _ (HsIPBinds {})) -> emptyInvalid
2051 _ -> okStmt dflags ctxt stmt
2052
2053 ----------------
2054 okDoStmt dflags ctxt stmt
2055 = case stmt of
2056 RecStmt {}
2057 | LangExt.RecursiveDo `xopt` dflags -> IsValid
2058 | ArrowExpr <- ctxt -> IsValid -- Arrows allows 'rec'
2059 | otherwise -> NotValid (text "Use RecursiveDo")
2060 BindStmt {} -> IsValid
2061 LetStmt {} -> IsValid
2062 BodyStmt {} -> IsValid
2063 _ -> emptyInvalid
2064
2065 ----------------
2066 okCompStmt dflags _ stmt
2067 = case stmt of
2068 BindStmt {} -> IsValid
2069 LetStmt {} -> IsValid
2070 BodyStmt {} -> IsValid
2071 ParStmt {}
2072 | LangExt.ParallelListComp `xopt` dflags -> IsValid
2073 | otherwise -> NotValid (text "Use ParallelListComp")
2074 TransStmt {}
2075 | LangExt.TransformListComp `xopt` dflags -> IsValid
2076 | otherwise -> NotValid (text "Use TransformListComp")
2077 RecStmt {} -> emptyInvalid
2078 LastStmt {} -> emptyInvalid -- Should not happen (dealt with by checkLastStmt)
2079 ApplicativeStmt {} -> emptyInvalid
2080 XStmtLR{} -> panic "okCompStmt"
2081
2082 ---------
2083 checkTupleSection :: [LHsTupArg GhcPs] -> RnM ()
2084 checkTupleSection args
2085 = do { tuple_section <- xoptM LangExt.TupleSections
2086 ; checkErr (all tupArgPresent args || tuple_section) msg }
2087 where
2088 msg = text "Illegal tuple section: use TupleSections"
2089
2090 ---------
2091 sectionErr :: HsExpr GhcPs -> SDoc
2092 sectionErr expr
2093 = hang (text "A section must be enclosed in parentheses")
2094 2 (text "thus:" <+> (parens (ppr expr)))
2095
2096 patSynErr :: HsExpr GhcPs -> SDoc -> RnM (HsExpr GhcRn, FreeVars)
2097 patSynErr e explanation = do { addErr (sep [text "Pattern syntax in expression context:",
2098 nest 4 (ppr e)] $$
2099 explanation)
2100 ; return (EWildPat noExt, emptyFVs) }
2101
2102 badIpBinds :: Outputable a => SDoc -> a -> SDoc
2103 badIpBinds what binds
2104 = hang (text "Implicit-parameter bindings illegal in" <+> what)
2105 2 (ppr binds)