176fdb4d412b4f4207b50533630546cca1fce5ee
[ghc-hetmet.git] / compiler / rename / RnExpr.lhs
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 \begin{code}
13 {-# OPTIONS -w #-}
14 -- The above warning supression flag is a temporary kludge.
15 -- While working on this module you are encouraged to remove it and fix
16 -- any warnings in the module. See
17 --     http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
18 -- for details
19
20 module RnExpr (
21         rnLExpr, rnExpr, rnStmts
22    ) where
23
24 #include "HsVersions.h"
25
26 #ifdef GHCI
27 import {-# SOURCE #-} TcSplice( runQuasiQuoteExpr )
28 #endif  /* GHCI */
29
30 import RnSource  ( rnSrcDecls, rnSplice, checkTH ) 
31 import RnBinds   ( rnLocalBindsAndThen, rnValBindsLHS, rnValBindsRHS,
32                    rnMatchGroup, makeMiniFixityEnv) 
33 import HsSyn
34 import TcRnMonad
35 import RnEnv
36 import HscTypes         ( availNames )
37 import RnNames          ( getLocalDeclBinders, extendRdrEnvRn )
38 import RnTypes          ( rnHsTypeFVs, 
39                           mkOpFormRn, mkOpAppRn, mkNegAppRn, checkSectionPrec)
40 import RnPat            (rnQuasiQuote, rnOverLit, rnPatsAndThen_LocalRightwards, rnBindPat,
41                          localRecNameMaker, rnLit,
42                          rnHsRecFields_Con, rnHsRecFields_Update, checkTupSize)
43 import RdrName      ( mkRdrUnqual )
44 import DynFlags         ( DynFlag(..) )
45 import BasicTypes       ( FixityDirection(..) )
46 import SrcLoc           ( SrcSpan )
47 import PrelNames        ( thFAKE, hasKey, assertIdKey, assertErrorName,
48                           loopAName, choiceAName, appAName, arrAName, composeAName, firstAName,
49                           negateName, thenMName, bindMName, failMName, groupWithName )
50
51 import Name             ( Name, nameOccName, nameModule, nameIsLocalOrFrom )
52 import NameSet
53 import UniqFM
54 import RdrName          ( RdrName, extendLocalRdrEnv, lookupLocalRdrEnv, hideSomeUnquals )
55 import LoadIface        ( loadInterfaceForName )
56 import UniqFM           ( isNullUFM )
57 import UniqSet          ( emptyUniqSet )
58 import List             ( nub )
59 import Util             ( isSingleton )
60 import ListSetOps       ( removeDups )
61 import Maybes           ( expectJust )
62 import Outputable
63 import SrcLoc           ( Located(..), unLoc, getLoc, noLoc )
64 import FastString
65
66 import List             ( unzip4 )
67 \end{code}
68
69
70 %************************************************************************
71 %*                                                                      *
72 \subsubsection{Expressions}
73 %*                                                                      *
74 %************************************************************************
75
76 \begin{code}
77 rnExprs :: [LHsExpr RdrName] -> RnM ([LHsExpr Name], FreeVars)
78 rnExprs ls = rnExprs' ls emptyUniqSet
79  where
80   rnExprs' [] acc = returnM ([], acc)
81   rnExprs' (expr:exprs) acc
82    = rnLExpr expr               `thenM` \ (expr', fvExpr) ->
83
84         -- Now we do a "seq" on the free vars because typically it's small
85         -- or empty, especially in very long lists of constants
86     let
87         acc' = acc `plusFV` fvExpr
88     in
89     (grubby_seqNameSet acc' rnExprs') exprs acc'        `thenM` \ (exprs', fvExprs) ->
90     returnM (expr':exprs', fvExprs)
91
92 -- Grubby little function to do "seq" on namesets; replace by proper seq when GHC can do seq
93 grubby_seqNameSet ns result | isNullUFM ns = result
94                             | otherwise    = result
95 \end{code}
96
97 Variables. We look up the variable and return the resulting name. 
98
99 \begin{code}
100 rnLExpr :: LHsExpr RdrName -> RnM (LHsExpr Name, FreeVars)
101 rnLExpr = wrapLocFstM rnExpr
102
103 rnExpr :: HsExpr RdrName -> RnM (HsExpr Name, FreeVars)
104
105 rnExpr (HsVar v)
106   = do name           <- lookupOccRn v
107        ignore_asserts <- doptM Opt_IgnoreAsserts
108        finish_var ignore_asserts name
109   where
110     finish_var ignore_asserts name
111         | ignore_asserts || not (name `hasKey` assertIdKey)
112         = return (HsVar name, unitFV name)
113         | otherwise
114         = do { (e, fvs) <- mkAssertErrorExpr
115              ; return (e, fvs `addOneFV` name) }
116
117 rnExpr (HsIPVar v)
118   = newIPNameRn v               `thenM` \ name ->
119     returnM (HsIPVar name, emptyFVs)
120
121 rnExpr (HsLit lit@(HsString s))
122   = do {
123          opt_OverloadedStrings <- doptM Opt_OverloadedStrings
124        ; if opt_OverloadedStrings then
125             rnExpr (HsOverLit (mkHsIsString s placeHolderType))
126          else -- Same as below
127             rnLit lit           `thenM_`
128             returnM (HsLit lit, emptyFVs)
129        }
130
131 rnExpr (HsLit lit) 
132   = rnLit lit           `thenM_`
133     returnM (HsLit lit, emptyFVs)
134
135 rnExpr (HsOverLit lit) 
136   = rnOverLit lit               `thenM` \ (lit', fvs) ->
137     returnM (HsOverLit lit', fvs)
138
139 rnExpr (HsApp fun arg)
140   = rnLExpr fun         `thenM` \ (fun',fvFun) ->
141     rnLExpr arg         `thenM` \ (arg',fvArg) ->
142     returnM (HsApp fun' arg', fvFun `plusFV` fvArg)
143
144 rnExpr (OpApp e1 op _ e2) 
145   = rnLExpr e1                          `thenM` \ (e1', fv_e1) ->
146     rnLExpr e2                          `thenM` \ (e2', fv_e2) ->
147     rnLExpr op                          `thenM` \ (op'@(L _ (HsVar op_name)), fv_op) ->
148
149         -- Deal with fixity
150         -- When renaming code synthesised from "deriving" declarations
151         -- we used to avoid fixity stuff, but we can't easily tell any
152         -- more, so I've removed the test.  Adding HsPars in TcGenDeriv
153         -- should prevent bad things happening.
154     lookupFixityRn op_name              `thenM` \ fixity ->
155     mkOpAppRn e1' op' fixity e2'        `thenM` \ final_e -> 
156
157     returnM (final_e,
158               fv_e1 `plusFV` fv_op `plusFV` fv_e2)
159
160 rnExpr (NegApp e _)
161   = rnLExpr e                   `thenM` \ (e', fv_e) ->
162     lookupSyntaxName negateName `thenM` \ (neg_name, fv_neg) ->
163     mkNegAppRn e' neg_name      `thenM` \ final_e ->
164     returnM (final_e, fv_e `plusFV` fv_neg)
165
166 rnExpr (HsPar e)
167   = rnLExpr e           `thenM` \ (e', fvs_e) ->
168     returnM (HsPar e', fvs_e)
169
170 -- Template Haskell extensions
171 -- Don't ifdef-GHCI them because we want to fail gracefully
172 -- (not with an rnExpr crash) in a stage-1 compiler.
173 rnExpr e@(HsBracket br_body)
174   = checkTH e "bracket"         `thenM_`
175     rnBracket br_body           `thenM` \ (body', fvs_e) ->
176     returnM (HsBracket body', fvs_e)
177
178 rnExpr e@(HsSpliceE splice)
179   = rnSplice splice             `thenM` \ (splice', fvs) ->
180     returnM (HsSpliceE splice', fvs)
181
182 #ifndef GHCI
183 rnExpr e@(HsQuasiQuoteE _) = pprPanic "Cant do quasiquotation without GHCi" (ppr e)
184 #else
185 rnExpr e@(HsQuasiQuoteE qq)
186   = rnQuasiQuote qq             `thenM` \ (qq', fvs_qq) ->
187     runQuasiQuoteExpr qq'       `thenM` \ (L _ expr') ->
188     rnExpr expr'                `thenM` \ (expr'', fvs_expr) ->
189     returnM (expr'', fvs_qq `plusFV` fvs_expr)
190 #endif  /* GHCI */
191
192 rnExpr section@(SectionL expr op)
193   = rnLExpr expr                `thenM` \ (expr', fvs_expr) ->
194     rnLExpr op                  `thenM` \ (op', fvs_op) ->
195     checkSectionPrec InfixL section op' expr' `thenM_`
196     returnM (SectionL expr' op', fvs_op `plusFV` fvs_expr)
197
198 rnExpr section@(SectionR op expr)
199   = rnLExpr op                                  `thenM` \ (op',   fvs_op) ->
200     rnLExpr expr                                        `thenM` \ (expr', fvs_expr) ->
201     checkSectionPrec InfixR section op' expr'   `thenM_`
202     returnM (SectionR op' expr', fvs_op `plusFV` fvs_expr)
203
204 rnExpr (HsCoreAnn ann expr)
205   = rnLExpr expr `thenM` \ (expr', fvs_expr) ->
206     returnM (HsCoreAnn ann expr', fvs_expr)
207
208 rnExpr (HsSCC lbl expr)
209   = rnLExpr expr                `thenM` \ (expr', fvs_expr) ->
210     returnM (HsSCC lbl expr', fvs_expr)
211 rnExpr (HsTickPragma info expr)
212   = rnLExpr expr                `thenM` \ (expr', fvs_expr) ->
213     returnM (HsTickPragma info expr', fvs_expr)
214
215 rnExpr (HsLam matches)
216   = rnMatchGroup LambdaExpr matches     `thenM` \ (matches', fvMatch) ->
217     returnM (HsLam matches', fvMatch)
218
219 rnExpr (HsCase expr matches)
220   = rnLExpr expr                        `thenM` \ (new_expr, e_fvs) ->
221     rnMatchGroup CaseAlt matches        `thenM` \ (new_matches, ms_fvs) ->
222     returnM (HsCase new_expr new_matches, e_fvs `plusFV` ms_fvs)
223
224 rnExpr (HsLet binds expr)
225   = rnLocalBindsAndThen binds           $ \ binds' ->
226     rnLExpr expr                         `thenM` \ (expr',fvExpr) ->
227     returnM (HsLet binds' expr', fvExpr)
228
229 rnExpr e@(HsDo do_or_lc stmts body _)
230   = do  { ((stmts', body'), fvs) <- rnStmts do_or_lc stmts $
231                                     rnLExpr body
232         ; return (HsDo do_or_lc stmts' body' placeHolderType, fvs) }
233
234 rnExpr (ExplicitList _ exps)
235   = rnExprs exps                        `thenM` \ (exps', fvs) ->
236     returnM  (ExplicitList placeHolderType exps', fvs)
237
238 rnExpr (ExplicitPArr _ exps)
239   = rnExprs exps                        `thenM` \ (exps', fvs) ->
240     returnM  (ExplicitPArr placeHolderType exps', fvs)
241
242 rnExpr e@(ExplicitTuple exps boxity)
243   = checkTupSize (length exps)                  `thenM_`
244     rnExprs exps                                `thenM` \ (exps', fvs) ->
245     returnM (ExplicitTuple exps' boxity, fvs)
246
247 rnExpr (RecordCon con_id _ rbinds)
248   = do  { conname <- lookupLocatedOccRn con_id
249         ; (rbinds', fvRbinds) <- rnHsRecFields_Con conname rnLExpr rbinds
250         ; return (RecordCon conname noPostTcExpr rbinds', 
251                   fvRbinds `addOneFV` unLoc conname) }
252
253 rnExpr (RecordUpd expr rbinds _ _ _)
254   = do  { (expr', fvExpr) <- rnLExpr expr
255         ; (rbinds', fvRbinds) <- rnHsRecFields_Update rnLExpr rbinds
256         ; return (RecordUpd expr' rbinds' [] [] [], 
257                   fvExpr `plusFV` fvRbinds) }
258
259 rnExpr (ExprWithTySig expr pty)
260   = do  { (pty', fvTy) <- rnHsTypeFVs doc pty
261         ; (expr', fvExpr) <- bindSigTyVarsFV (hsExplicitTvs pty') $
262                              rnLExpr expr
263         ; return (ExprWithTySig expr' pty', fvExpr `plusFV` fvTy) }
264   where 
265     doc = text "In an expression type signature"
266
267 rnExpr (HsIf p b1 b2)
268   = rnLExpr p           `thenM` \ (p', fvP) ->
269     rnLExpr b1          `thenM` \ (b1', fvB1) ->
270     rnLExpr b2          `thenM` \ (b2', fvB2) ->
271     returnM (HsIf p' b1' b2', plusFVs [fvP, fvB1, fvB2])
272
273 rnExpr (HsType a)
274   = rnHsTypeFVs doc a   `thenM` \ (t, fvT) -> 
275     returnM (HsType t, fvT)
276   where 
277     doc = text "In a type argument"
278
279 rnExpr (ArithSeq _ seq)
280   = rnArithSeq seq       `thenM` \ (new_seq, fvs) ->
281     returnM (ArithSeq noPostTcExpr new_seq, fvs)
282
283 rnExpr (PArrSeq _ seq)
284   = rnArithSeq seq       `thenM` \ (new_seq, fvs) ->
285     returnM (PArrSeq noPostTcExpr new_seq, fvs)
286 \end{code}
287
288 These three are pattern syntax appearing in expressions.
289 Since all the symbols are reservedops we can simply reject them.
290 We return a (bogus) EWildPat in each case.
291
292 \begin{code}
293 rnExpr e@EWildPat      = patSynErr e
294 rnExpr e@(EAsPat {})   = patSynErr e
295 rnExpr e@(EViewPat {}) = patSynErr e
296 rnExpr e@(ELazyPat {}) = patSynErr e
297 \end{code}
298
299 %************************************************************************
300 %*                                                                      *
301         Arrow notation
302 %*                                                                      *
303 %************************************************************************
304
305 \begin{code}
306 rnExpr (HsProc pat body)
307   = newArrowScope $
308     rnPatsAndThen_LocalRightwards ProcExpr [pat] $ \ [pat'] ->
309     rnCmdTop body                `thenM` \ (body',fvBody) ->
310     returnM (HsProc pat' body', fvBody)
311
312 rnExpr (HsArrApp arrow arg _ ho rtl)
313   = select_arrow_scope (rnLExpr arrow)  `thenM` \ (arrow',fvArrow) ->
314     rnLExpr arg                         `thenM` \ (arg',fvArg) ->
315     returnM (HsArrApp arrow' arg' placeHolderType ho rtl,
316              fvArrow `plusFV` fvArg)
317   where
318     select_arrow_scope tc = case ho of
319         HsHigherOrderApp -> tc
320         HsFirstOrderApp  -> escapeArrowScope tc
321
322 -- infix form
323 rnExpr (HsArrForm op (Just _) [arg1, arg2])
324   = escapeArrowScope (rnLExpr op)
325                         `thenM` \ (op'@(L _ (HsVar op_name)),fv_op) ->
326     rnCmdTop arg1       `thenM` \ (arg1',fv_arg1) ->
327     rnCmdTop arg2       `thenM` \ (arg2',fv_arg2) ->
328
329         -- Deal with fixity
330
331     lookupFixityRn op_name              `thenM` \ fixity ->
332     mkOpFormRn arg1' op' fixity arg2'   `thenM` \ final_e -> 
333
334     returnM (final_e,
335               fv_arg1 `plusFV` fv_op `plusFV` fv_arg2)
336
337 rnExpr (HsArrForm op fixity cmds)
338   = escapeArrowScope (rnLExpr op)       `thenM` \ (op',fvOp) ->
339     rnCmdArgs cmds                      `thenM` \ (cmds',fvCmds) ->
340     returnM (HsArrForm op' fixity cmds', fvOp `plusFV` fvCmds)
341
342 rnExpr other = pprPanic "rnExpr: unexpected expression" (ppr other)
343         -- HsWrap
344 \end{code}
345
346
347 %************************************************************************
348 %*                                                                      *
349         Arrow commands
350 %*                                                                      *
351 %************************************************************************
352
353 \begin{code}
354 rnCmdArgs [] = returnM ([], emptyFVs)
355 rnCmdArgs (arg:args)
356   = rnCmdTop arg        `thenM` \ (arg',fvArg) ->
357     rnCmdArgs args      `thenM` \ (args',fvArgs) ->
358     returnM (arg':args', fvArg `plusFV` fvArgs)
359
360
361 rnCmdTop = wrapLocFstM rnCmdTop'
362  where
363   rnCmdTop' (HsCmdTop cmd _ _ _) 
364    = rnLExpr (convertOpFormsLCmd cmd) `thenM` \ (cmd', fvCmd) ->
365      let 
366         cmd_names = [arrAName, composeAName, firstAName] ++
367                     nameSetToList (methodNamesCmd (unLoc cmd'))
368      in
369         -- Generate the rebindable syntax for the monad
370      lookupSyntaxTable cmd_names        `thenM` \ (cmd_names', cmd_fvs) ->
371
372      returnM (HsCmdTop cmd' [] placeHolderType cmd_names', 
373              fvCmd `plusFV` cmd_fvs)
374
375 ---------------------------------------------------
376 -- convert OpApp's in a command context to HsArrForm's
377
378 convertOpFormsLCmd :: LHsCmd id -> LHsCmd id
379 convertOpFormsLCmd = fmap convertOpFormsCmd
380
381 convertOpFormsCmd :: HsCmd id -> HsCmd id
382
383 convertOpFormsCmd (HsApp c e) = HsApp (convertOpFormsLCmd c) e
384 convertOpFormsCmd (HsLam match) = HsLam (convertOpFormsMatch match)
385 convertOpFormsCmd (OpApp c1 op fixity c2)
386   = let
387         arg1 = L (getLoc c1) $ HsCmdTop (convertOpFormsLCmd c1) [] placeHolderType []
388         arg2 = L (getLoc c2) $ HsCmdTop (convertOpFormsLCmd c2) [] placeHolderType []
389     in
390     HsArrForm op (Just fixity) [arg1, arg2]
391
392 convertOpFormsCmd (HsPar c) = HsPar (convertOpFormsLCmd c)
393
394 -- gaw 2004
395 convertOpFormsCmd (HsCase exp matches)
396   = HsCase exp (convertOpFormsMatch matches)
397
398 convertOpFormsCmd (HsIf exp c1 c2)
399   = HsIf exp (convertOpFormsLCmd c1) (convertOpFormsLCmd c2)
400
401 convertOpFormsCmd (HsLet binds cmd)
402   = HsLet binds (convertOpFormsLCmd cmd)
403
404 convertOpFormsCmd (HsDo ctxt stmts body ty)
405   = HsDo ctxt (map (fmap convertOpFormsStmt) stmts)
406               (convertOpFormsLCmd body) ty
407
408 -- Anything else is unchanged.  This includes HsArrForm (already done),
409 -- things with no sub-commands, and illegal commands (which will be
410 -- caught by the type checker)
411 convertOpFormsCmd c = c
412
413 convertOpFormsStmt (BindStmt pat cmd _ _)
414   = BindStmt pat (convertOpFormsLCmd cmd) noSyntaxExpr noSyntaxExpr
415 convertOpFormsStmt (ExprStmt cmd _ _)
416   = ExprStmt (convertOpFormsLCmd cmd) noSyntaxExpr placeHolderType
417 convertOpFormsStmt (RecStmt stmts lvs rvs es binds)
418   = RecStmt (map (fmap convertOpFormsStmt) stmts) lvs rvs es binds
419 convertOpFormsStmt stmt = stmt
420
421 convertOpFormsMatch (MatchGroup ms ty)
422   = MatchGroup (map (fmap convert) ms) ty
423  where convert (Match pat mty grhss)
424           = Match pat mty (convertOpFormsGRHSs grhss)
425
426 convertOpFormsGRHSs (GRHSs grhss binds)
427   = GRHSs (map convertOpFormsGRHS grhss) binds
428
429 convertOpFormsGRHS = fmap convert
430  where 
431    convert (GRHS stmts cmd) = GRHS stmts (convertOpFormsLCmd cmd)
432
433 ---------------------------------------------------
434 type CmdNeeds = FreeVars        -- Only inhabitants are 
435                                 --      appAName, choiceAName, loopAName
436
437 -- find what methods the Cmd needs (loop, choice, apply)
438 methodNamesLCmd :: LHsCmd Name -> CmdNeeds
439 methodNamesLCmd = methodNamesCmd . unLoc
440
441 methodNamesCmd :: HsCmd Name -> CmdNeeds
442
443 methodNamesCmd cmd@(HsArrApp _arrow _arg _ HsFirstOrderApp _rtl)
444   = emptyFVs
445 methodNamesCmd cmd@(HsArrApp _arrow _arg _ HsHigherOrderApp _rtl)
446   = unitFV appAName
447 methodNamesCmd cmd@(HsArrForm {}) = emptyFVs
448
449 methodNamesCmd (HsPar c) = methodNamesLCmd c
450
451 methodNamesCmd (HsIf p c1 c2)
452   = methodNamesLCmd c1 `plusFV` methodNamesLCmd c2 `addOneFV` choiceAName
453
454 methodNamesCmd (HsLet b c) = methodNamesLCmd c
455
456 methodNamesCmd (HsDo sc stmts body ty) 
457   = methodNamesStmts stmts `plusFV` methodNamesLCmd body
458
459 methodNamesCmd (HsApp c e) = methodNamesLCmd c
460
461 methodNamesCmd (HsLam match) = methodNamesMatch match
462
463 methodNamesCmd (HsCase scrut matches)
464   = methodNamesMatch matches `addOneFV` choiceAName
465
466 methodNamesCmd other = emptyFVs
467    -- Other forms can't occur in commands, but it's not convenient 
468    -- to error here so we just do what's convenient.
469    -- The type checker will complain later
470
471 ---------------------------------------------------
472 methodNamesMatch (MatchGroup ms _)
473   = plusFVs (map do_one ms)
474  where 
475     do_one (L _ (Match pats sig_ty grhss)) = methodNamesGRHSs grhss
476
477 -------------------------------------------------
478 -- gaw 2004
479 methodNamesGRHSs (GRHSs grhss binds) = plusFVs (map methodNamesGRHS grhss)
480
481 -------------------------------------------------
482 methodNamesGRHS (L _ (GRHS stmts rhs)) = methodNamesLCmd rhs
483
484 ---------------------------------------------------
485 methodNamesStmts stmts = plusFVs (map methodNamesLStmt stmts)
486
487 ---------------------------------------------------
488 methodNamesLStmt = methodNamesStmt . unLoc
489
490 methodNamesStmt (ExprStmt cmd _ _)     = methodNamesLCmd cmd
491 methodNamesStmt (BindStmt pat cmd _ _) = methodNamesLCmd cmd
492 methodNamesStmt (RecStmt stmts _ _ _ _)
493   = methodNamesStmts stmts `addOneFV` loopAName
494 methodNamesStmt (LetStmt b)  = emptyFVs
495 methodNamesStmt (ParStmt ss) = emptyFVs
496 methodNamesStmt (TransformStmt _ _ _) = emptyFVs
497 methodNamesStmt (GroupStmt _ _) = emptyFVs
498    -- ParStmt, TransformStmt and GroupStmt can't occur in commands, but it's not convenient to error 
499    -- here so we just do what's convenient
500 \end{code}
501
502
503 %************************************************************************
504 %*                                                                      *
505         Arithmetic sequences
506 %*                                                                      *
507 %************************************************************************
508
509 \begin{code}
510 rnArithSeq (From expr)
511  = rnLExpr expr         `thenM` \ (expr', fvExpr) ->
512    returnM (From expr', fvExpr)
513
514 rnArithSeq (FromThen expr1 expr2)
515  = rnLExpr expr1        `thenM` \ (expr1', fvExpr1) ->
516    rnLExpr expr2        `thenM` \ (expr2', fvExpr2) ->
517    returnM (FromThen expr1' expr2', fvExpr1 `plusFV` fvExpr2)
518
519 rnArithSeq (FromTo expr1 expr2)
520  = rnLExpr expr1        `thenM` \ (expr1', fvExpr1) ->
521    rnLExpr expr2        `thenM` \ (expr2', fvExpr2) ->
522    returnM (FromTo expr1' expr2', fvExpr1 `plusFV` fvExpr2)
523
524 rnArithSeq (FromThenTo expr1 expr2 expr3)
525  = rnLExpr expr1        `thenM` \ (expr1', fvExpr1) ->
526    rnLExpr expr2        `thenM` \ (expr2', fvExpr2) ->
527    rnLExpr expr3        `thenM` \ (expr3', fvExpr3) ->
528    returnM (FromThenTo expr1' expr2' expr3',
529             plusFVs [fvExpr1, fvExpr2, fvExpr3])
530 \end{code}
531
532 %************************************************************************
533 %*                                                                      *
534         Template Haskell brackets
535 %*                                                                      *
536 %************************************************************************
537
538 \begin{code}
539 rnBracket (VarBr n) = do { name <- lookupOccRn n
540                          ; this_mod <- getModule
541                          ; checkM (nameIsLocalOrFrom this_mod name) $   -- Reason: deprecation checking asumes the
542                            do { loadInterfaceForName msg name           -- home interface is loaded, and this is the
543                               ; return () }                             -- only way that is going to happen
544                          ; returnM (VarBr name, unitFV name) }
545                     where
546                       msg = ptext SLIT("Need interface for Template Haskell quoted Name")
547
548 rnBracket (ExpBr e) = do { (e', fvs) <- rnLExpr e
549                          ; return (ExpBr e', fvs) }
550
551 rnBracket (PatBr p) = do { addErr (ptext SLIT("Tempate Haskell pattern brackets are not supported yet"));
552                            failM }
553
554 rnBracket (TypBr t) = do { (t', fvs) <- rnHsTypeFVs doc t
555                          ; return (TypBr t', fvs) }
556                     where
557                       doc = ptext SLIT("In a Template-Haskell quoted type")
558 rnBracket (DecBr group) 
559   = do { gbl_env  <- getGblEnv
560
561         ; let new_gbl_env = gbl_env { -- Set the module to thFAKE.  The top-level names from the bracketed 
562                                       -- declarations will go into the name cache, and we don't want them to 
563                                       -- confuse the Names for the current module.  
564                                       -- By using a pretend module, thFAKE, we keep them safely out of the way.
565                                      tcg_mod = thFAKE,
566                         
567                                      -- The emptyDUs is so that we just collect uses for this group alone
568                                      -- in the call to rnSrcDecls below
569                                      tcg_dus = emptyDUs }
570        ; setGblEnv new_gbl_env $ do {
571
572         -- In this situation we want to *shadow* top-level bindings.
573         --      foo = 1
574         --      bar = [d| foo = 1 |]
575         -- If we don't shadow, we'll get an ambiguity complaint when we do 
576         -- a lookupTopBndrRn (which uses lookupGreLocalRn) on the binder of the 'foo'
577         --
578         -- Furthermore, arguably if the splice does define foo, that should hide
579         -- any foo's further out
580         --
581         -- The shadowing is acheived by calling rnSrcDecls with True as the shadowing flag
582        ; (tcg_env, group') <- rnSrcDecls True group       
583
584        -- Discard the tcg_env; it contains only extra info about fixity
585         ; return (DecBr group', allUses (tcg_dus tcg_env)) } }
586 \end{code}
587
588 %************************************************************************
589 %*                                                                      *
590 \subsubsection{@Stmt@s: in @do@ expressions}
591 %*                                                                      *
592 %************************************************************************
593
594 \begin{code}
595 rnStmts :: HsStmtContext Name -> [LStmt RdrName] 
596         -> RnM (thing, FreeVars)
597         -> RnM (([LStmt Name], thing), FreeVars)
598
599 rnStmts (MDoExpr _) = rnMDoStmts
600 rnStmts ctxt        = rnNormalStmts ctxt
601
602 rnNormalStmts :: HsStmtContext Name -> [LStmt RdrName]
603               -> RnM (thing, FreeVars)
604               -> RnM (([LStmt Name], thing), FreeVars)  
605 -- Used for cases *other* than recursive mdo
606 -- Implements nested scopes
607
608 rnNormalStmts ctxt [] thing_inside 
609   = do { (thing, fvs) <- thing_inside
610         ; return (([],thing), fvs) } 
611
612 rnNormalStmts ctxt (L loc stmt : stmts) thing_inside
613   = do { ((stmt', (stmts', thing)), fvs) <- rnStmt ctxt stmt $
614             rnNormalStmts ctxt stmts thing_inside
615         ; return (((L loc stmt' : stmts'), thing), fvs) }
616
617
618 rnStmt :: HsStmtContext Name -> Stmt RdrName
619        -> RnM (thing, FreeVars)
620        -> RnM ((Stmt Name, thing), FreeVars)
621
622 rnStmt ctxt (ExprStmt expr _ _) thing_inside
623   = do  { (expr', fv_expr) <- rnLExpr expr
624         ; (then_op, fvs1)  <- lookupSyntaxName thenMName
625         ; (thing, fvs2)    <- thing_inside
626         ; return ((ExprStmt expr' then_op placeHolderType, thing),
627                   fv_expr `plusFV` fvs1 `plusFV` fvs2) }
628
629 rnStmt ctxt (BindStmt pat expr _ _) thing_inside
630   = do  { (expr', fv_expr) <- rnLExpr expr
631                 -- The binders do not scope over the expression
632         ; (bind_op, fvs1) <- lookupSyntaxName bindMName
633         ; (fail_op, fvs2) <- lookupSyntaxName failMName
634         ; rnPatsAndThen_LocalRightwards (StmtCtxt ctxt) [pat] $ \ [pat'] -> do
635         { (thing, fvs3) <- thing_inside
636         ; return ((BindStmt pat' expr' bind_op fail_op, thing),
637                   fv_expr `plusFV` fvs1 `plusFV` fvs2 `plusFV` fvs3) }}
638        -- fv_expr shouldn't really be filtered by the rnPatsAndThen
639         -- but it does not matter because the names are unique
640
641 rnStmt ctxt (LetStmt binds) thing_inside = do
642     checkErr (ok ctxt binds) (badIpBinds (ptext SLIT("a parallel list comprehension:")) binds)
643     rnLocalBindsAndThen binds $ \binds' -> do
644         (thing, fvs) <- thing_inside
645         return ((LetStmt binds', thing), fvs)
646   where
647         -- We do not allow implicit-parameter bindings in a parallel
648         -- list comprehension.  I'm not sure what it might mean.
649     ok (ParStmtCtxt _) (HsIPBinds _) = False
650     ok _               _             = True
651
652 rnStmt ctxt (RecStmt rec_stmts _ _ _ _) thing_inside
653   = 
654     rn_rec_stmts_and_then rec_stmts     $ \ segs ->
655     thing_inside                        `thenM` \ (thing, fvs) ->
656     let
657         segs_w_fwd_refs          = addFwdRefs segs
658         (ds, us, fs, rec_stmts') = unzip4 segs_w_fwd_refs
659         later_vars = nameSetToList (plusFVs ds `intersectNameSet` fvs)
660         fwd_vars   = nameSetToList (plusFVs fs)
661         uses       = plusFVs us
662         rec_stmt   = RecStmt rec_stmts' later_vars fwd_vars [] emptyLHsBinds
663     in  
664     returnM ((rec_stmt, thing), uses `plusFV` fvs)
665   where
666     doc = text "In a recursive do statement"
667
668 rnStmt ctxt (TransformStmt (stmts, _) usingExpr maybeByExpr) thing_inside = do
669     checkIsTransformableListComp ctxt
670     
671     (usingExpr', fv_usingExpr) <- rnLExpr usingExpr
672     ((stmts', binders, (maybeByExpr', thing)), fvs) <- 
673         rnNormalStmtsAndFindUsedBinders (TransformStmtCtxt ctxt) stmts $ \unshadowed_bndrs -> do
674             (maybeByExpr', fv_maybeByExpr)  <- rnMaybeLExpr maybeByExpr
675             (thing, fv_thing)               <- thing_inside
676             
677             return ((maybeByExpr', thing), fv_maybeByExpr `plusFV` fv_thing)
678     
679     return ((TransformStmt (stmts', binders) usingExpr' maybeByExpr', thing), fv_usingExpr `plusFV` fvs)
680   where
681     rnMaybeLExpr Nothing = return (Nothing, emptyFVs)
682     rnMaybeLExpr (Just expr) = do
683         (expr', fv_expr) <- rnLExpr expr
684         return (Just expr', fv_expr)
685         
686 rnStmt ctxt (GroupStmt (stmts, _) groupByClause) thing_inside = do
687     checkIsTransformableListComp ctxt
688     
689     -- We must rename the using expression in the context before the transform is begun
690     groupByClauseAction <- 
691         case groupByClause of
692             GroupByNothing usingExpr -> do
693                 (usingExpr', fv_usingExpr) <- rnLExpr usingExpr
694                 (return . return) (GroupByNothing usingExpr', fv_usingExpr)
695             GroupBySomething eitherUsingExpr byExpr -> do
696                 (eitherUsingExpr', fv_eitherUsingExpr) <- 
697                     case eitherUsingExpr of
698                         Right _ -> return (Right $ HsVar groupWithName, unitNameSet groupWithName)
699                         Left usingExpr -> do
700                             (usingExpr', fv_usingExpr) <- rnLExpr usingExpr
701                             return (Left usingExpr', fv_usingExpr)
702                             
703                 return $ do
704                     (byExpr', fv_byExpr) <- rnLExpr byExpr
705                     return (GroupBySomething eitherUsingExpr' byExpr', fv_eitherUsingExpr `plusFV` fv_byExpr)
706     
707     -- We only use rnNormalStmtsAndFindUsedBinders to get unshadowed_bndrs, so
708     -- perhaps we could refactor this to use rnNormalStmts directly?
709     ((stmts', _, (groupByClause', usedBinderMap, thing)), fvs) <- 
710         rnNormalStmtsAndFindUsedBinders (TransformStmtCtxt ctxt) stmts $ \unshadowed_bndrs -> do
711             (groupByClause', fv_groupByClause) <- groupByClauseAction
712             
713             unshadowed_bndrs' <- mapM newLocalName unshadowed_bndrs
714             let binderMap = zip unshadowed_bndrs unshadowed_bndrs'
715             
716             -- Bind the "thing" inside a context where we have REBOUND everything
717             -- bound by the statements before the group. This is necessary since after
718             -- the grouping the same identifiers actually have different meanings
719             -- i.e. they refer to lists not singletons!
720             (thing, fv_thing) <- bindLocalNames unshadowed_bndrs' thing_inside
721             
722             -- We remove entries from the binder map that are not used in the thing_inside.
723             -- We can then use that usage information to ensure that the free variables do 
724             -- not contain the things we just bound, but do contain the things we need to
725             -- make those bindings (i.e. the corresponding non-listy variables)
726             
727             -- Note that we also retain those entries which have an old binder in our
728             -- own free variables (the using or by expression). This is because this map
729             -- is reused in the desugarer to create the type to bind from the statements
730             -- that occur before this one. If the binders we need are not in the map, they
731             -- will never get bound into our desugared expression and hence the simplifier
732             -- crashes as we refer to variables that don't exist!
733             let usedBinderMap = filter 
734                     (\(old_binder, new_binder) -> 
735                         (new_binder `elemNameSet` fv_thing) || 
736                         (old_binder `elemNameSet` fv_groupByClause)) binderMap
737                 (usedOldBinders, usedNewBinders) = unzip usedBinderMap
738                 real_fv_thing = (delListFromNameSet fv_thing usedNewBinders) `plusFV` (mkNameSet usedOldBinders)
739             
740             return ((groupByClause', usedBinderMap, thing), fv_groupByClause `plusFV` real_fv_thing)
741     
742     traceRn (text "rnStmt: implicitly rebound these used binders:" <+> ppr usedBinderMap)
743     return ((GroupStmt (stmts', usedBinderMap) groupByClause', thing), fvs)
744   
745 rnStmt ctxt (ParStmt segs) thing_inside
746   = do  { parallel_list_comp <- doptM Opt_ParallelListComp
747         ; checkM parallel_list_comp parStmtErr
748         ; ((segs', thing), fvs) <- rnParallelStmts (ParStmtCtxt ctxt) segs thing_inside
749         ; return ((ParStmt segs', thing), fvs) }
750
751
752 rnNormalStmtsAndFindUsedBinders :: HsStmtContext Name 
753           -> [LStmt RdrName]
754           -> ([Name] -> RnM (thing, FreeVars))
755           -> RnM (([LStmt Name], [Name], thing), FreeVars)      
756 rnNormalStmtsAndFindUsedBinders ctxt stmts thing_inside = do
757     ((stmts', (used_bndrs, inner_thing)), fvs) <- rnNormalStmts ctxt stmts $ do
758         -- Find the Names that are bound by stmts that
759         -- by assumption we have just renamed
760         local_env <- getLocalRdrEnv
761         let 
762             stmts_binders = collectLStmtsBinders stmts
763             bndrs = map (expectJust "rnStmt"
764                         . lookupLocalRdrEnv local_env
765                         . unLoc) stmts_binders
766                         
767             -- If shadow, we'll look up (Unqual x) twice, getting
768             -- the second binding both times, which is the
769             -- one we want
770             unshadowed_bndrs = nub bndrs
771                         
772         -- Typecheck the thing inside, passing on all 
773         -- the Names bound before it for its information
774         (thing, fvs) <- thing_inside unshadowed_bndrs
775
776         -- Figure out which of the bound names are used
777         -- after the statements we renamed
778         let used_bndrs = filter (`elemNameSet` fvs) bndrs
779         return ((used_bndrs, thing), fvs)
780
781     -- Flatten the tuple returned by the above call a bit!
782     return ((stmts', used_bndrs, inner_thing), fvs)
783
784
785 rnParallelStmts ctxt segs thing_inside = do
786         orig_lcl_env <- getLocalRdrEnv
787         go orig_lcl_env [] segs
788     where
789         go orig_lcl_env bndrs [] = do 
790             let (bndrs', dups) = removeDups cmpByOcc bndrs
791                 inner_env = extendLocalRdrEnv orig_lcl_env bndrs'
792             
793             mappM dupErr dups
794             (thing, fvs) <- setLocalRdrEnv inner_env thing_inside
795             return (([], thing), fvs)
796
797         go orig_lcl_env bndrs_so_far ((stmts, _) : segs) = do 
798             ((stmts', bndrs, (segs', thing)), fvs) <- rnNormalStmtsAndFindUsedBinders ctxt stmts $ \new_bndrs -> do
799                 -- Typecheck the thing inside, passing on all
800                 -- the Names bound, but separately; revert the envt
801                 setLocalRdrEnv orig_lcl_env $ do
802                     go orig_lcl_env (new_bndrs ++ bndrs_so_far) segs
803
804             let seg' = (stmts', bndrs)
805             return (((seg':segs'), thing), delListFromNameSet fvs bndrs)
806
807         cmpByOcc n1 n2 = nameOccName n1 `compare` nameOccName n2
808         dupErr vs = addErr (ptext SLIT("Duplicate binding in parallel list comprehension for:")
809                     <+> quotes (ppr (head vs)))
810
811
812 checkIsTransformableListComp :: HsStmtContext Name -> RnM ()
813 checkIsTransformableListComp ctxt = do
814     -- Ensure we are really within a list comprehension because otherwise the
815     -- desugarer will break when we come to operate on a parallel array
816     checkM (notParallelArray ctxt) transformStmtOutsideListCompErr
817     
818     -- Ensure the user has turned the correct flag on
819     transform_list_comp <- doptM Opt_TransformListComp
820     checkM transform_list_comp transformStmtErr
821   where
822     notParallelArray PArrComp = False
823     notParallelArray _        = True
824     
825 \end{code}
826
827
828 %************************************************************************
829 %*                                                                      *
830 \subsubsection{mdo expressions}
831 %*                                                                      *
832 %************************************************************************
833
834 \begin{code}
835 type FwdRefs = NameSet
836 type Segment stmts = (Defs,
837                       Uses,     -- May include defs
838                       FwdRefs,  -- A subset of uses that are 
839                                 --   (a) used before they are bound in this segment, or 
840                                 --   (b) used here, and bound in subsequent segments
841                       stmts)    -- Either Stmt or [Stmt]
842
843
844 ----------------------------------------------------
845
846 rnMDoStmts :: [LStmt RdrName]
847            -> RnM (thing, FreeVars)
848            -> RnM (([LStmt Name], thing), FreeVars)     
849 rnMDoStmts stmts thing_inside
850   =    -- Step1: Bring all the binders of the mdo into scope
851         -- (Remember that this also removes the binders from the
852         -- finally-returned free-vars.)
853         -- And rename each individual stmt, making a
854         -- singleton segment.  At this stage the FwdRefs field
855         -- isn't finished: it's empty for all except a BindStmt
856         -- for which it's the fwd refs within the bind itself
857         -- (This set may not be empty, because we're in a recursive 
858         -- context.)
859      rn_rec_stmts_and_then stmts $ \ segs -> do {
860
861         ; (thing, fvs_later) <- thing_inside
862
863         ; let
864         -- Step 2: Fill in the fwd refs.
865         --         The segments are all singletons, but their fwd-ref
866         --         field mentions all the things used by the segment
867         --         that are bound after their use
868             segs_w_fwd_refs = addFwdRefs segs
869
870         -- Step 3: Group together the segments to make bigger segments
871         --         Invariant: in the result, no segment uses a variable
872         --                    bound in a later segment
873             grouped_segs = glomSegments segs_w_fwd_refs
874
875         -- Step 4: Turn the segments into Stmts
876         --         Use RecStmt when and only when there are fwd refs
877         --         Also gather up the uses from the end towards the
878         --         start, so we can tell the RecStmt which things are
879         --         used 'after' the RecStmt
880             (stmts', fvs) = segsToStmts grouped_segs fvs_later
881
882         ; return ((stmts', thing), fvs) }
883   where
884     doc = text "In a recursive mdo-expression"
885
886 ---------------------------------------------
887
888 -- wrapper that does both the left- and right-hand sides
889 rn_rec_stmts_and_then :: [LStmt RdrName]
890                          -- assumes that the FreeVars returned includes
891                          -- the FreeVars of the Segments
892                       -> ([Segment (LStmt Name)] -> RnM (a, FreeVars))
893                       -> RnM (a, FreeVars)
894 rn_rec_stmts_and_then s cont = do
895   -- (A) make the mini fixity env for all of the stmts
896   fix_env <- makeMiniFixityEnv (collectRecStmtsFixities s)
897
898   -- (B) do the LHSes
899   new_lhs_and_fv <- rn_rec_stmts_lhs fix_env s
900
901   --    bring them and their fixities into scope
902   let bound_names = map unLoc $ collectLStmtsBinders (map fst new_lhs_and_fv)
903   bindLocalNamesFV_WithFixities bound_names fix_env $ 
904     warnUnusedLocalBinds bound_names $ do
905
906   -- (C) do the right-hand-sides and thing-inside
907   segs <- rn_rec_stmts bound_names new_lhs_and_fv
908   cont segs
909
910
911 -- get all the fixity decls in any Let stmt
912 collectRecStmtsFixities l = 
913     foldr (\ s -> \acc -> case s of 
914                             (L loc (LetStmt (HsValBinds (ValBindsIn _ sigs)))) -> 
915                                 foldr (\ sig -> \ acc -> case sig of 
916                                                            (L loc (FixSig s)) -> (L loc s) : acc
917                                                            _ -> acc) acc sigs
918                             _ -> acc) [] l
919                              
920 -- left-hand sides
921
922 rn_rec_stmt_lhs :: UniqFM (Located Fixity) -- mini fixity env for the names we're about to bind
923                                            -- these fixities need to be brought into scope with the names
924                 -> LStmt RdrName
925                    -- rename LHS, and return its FVs
926                    -- Warning: we will only need the FreeVars below in the case of a BindStmt,
927                    -- so we don't bother to compute it accurately in the other cases
928                 -> RnM [(LStmtLR Name RdrName, FreeVars)]
929
930 rn_rec_stmt_lhs fix_env (L loc (ExprStmt expr a b)) = return [(L loc (ExprStmt expr a b), 
931                                                        -- this is actually correct
932                                                        emptyFVs)]
933
934 rn_rec_stmt_lhs fix_env (L loc (BindStmt pat expr a b)) 
935   = do 
936       -- should the ctxt be MDo instead?
937       (pat', fv_pat) <- rnBindPat (localRecNameMaker fix_env) pat 
938       return [(L loc (BindStmt pat' expr a b),
939                fv_pat)]
940
941 rn_rec_stmt_lhs fix_env (L loc (LetStmt binds@(HsIPBinds _)))
942   = do  { addErr (badIpBinds (ptext SLIT("an mdo expression")) binds)
943         ; failM }
944
945 rn_rec_stmt_lhs fix_env (L loc (LetStmt (HsValBinds binds))) 
946     = do binds' <- rnValBindsLHS fix_env binds
947          return [(L loc (LetStmt (HsValBinds binds')),
948                  -- Warning: this is bogus; see function invariant
949                  emptyFVs
950                  )]
951
952 rn_rec_stmt_lhs fix_env (L loc (RecStmt stmts _ _ _ _)) -- Flatten Rec inside Rec
953     = rn_rec_stmts_lhs fix_env stmts
954
955 rn_rec_stmt_lhs _ stmt@(L _ (ParStmt _))        -- Syntactically illegal in mdo
956   = pprPanic "rn_rec_stmt" (ppr stmt)
957   
958 rn_rec_stmt_lhs _ stmt@(L _ (TransformStmt _ _ _))      -- Syntactically illegal in mdo
959   = pprPanic "rn_rec_stmt" (ppr stmt)
960   
961 rn_rec_stmt_lhs _ stmt@(L _ (GroupStmt _ _))    -- Syntactically illegal in mdo
962   = pprPanic "rn_rec_stmt" (ppr stmt)
963   
964 rn_rec_stmts_lhs :: UniqFM (Located Fixity) -- mini fixity env for the names we're about to bind
965                                             -- these fixities need to be brought into scope with the names
966                  -> [LStmt RdrName] 
967                  -> RnM [(LStmtLR Name RdrName, FreeVars)]
968 rn_rec_stmts_lhs fix_env stmts = 
969     let boundNames = collectLStmtsBinders stmts
970         doc = text "In a recursive mdo-expression"
971     in do
972      -- First do error checking: we need to check for dups here because we
973      -- don't bind all of the variables from the Stmt at once
974      -- with bindLocatedLocals.
975      checkDupRdrNames doc boundNames
976      mappM (rn_rec_stmt_lhs fix_env) stmts `thenM` \ ls -> returnM (concat ls)
977
978
979 -- right-hand-sides
980
981 rn_rec_stmt :: [Name] -> LStmtLR Name RdrName -> FreeVars -> RnM [Segment (LStmt Name)]
982         -- Rename a Stmt that is inside a RecStmt (or mdo)
983         -- Assumes all binders are already in scope
984         -- Turns each stmt into a singleton Stmt
985 rn_rec_stmt all_bndrs (L loc (ExprStmt expr _ _)) _
986   = rnLExpr expr `thenM` \ (expr', fvs) ->
987     lookupSyntaxName thenMName  `thenM` \ (then_op, fvs1) ->
988     returnM [(emptyNameSet, fvs `plusFV` fvs1, emptyNameSet,
989               L loc (ExprStmt expr' then_op placeHolderType))]
990
991 rn_rec_stmt all_bndrs (L loc (BindStmt pat' expr _ _)) fv_pat
992   = rnLExpr expr                `thenM` \ (expr', fv_expr) ->
993     lookupSyntaxName bindMName  `thenM` \ (bind_op, fvs1) ->
994     lookupSyntaxName failMName  `thenM` \ (fail_op, fvs2) ->
995     let
996         bndrs = mkNameSet (collectPatBinders pat')
997         fvs   = fv_expr `plusFV` fv_pat `plusFV` fvs1 `plusFV` fvs2
998     in
999     returnM [(bndrs, fvs, bndrs `intersectNameSet` fvs,
1000               L loc (BindStmt pat' expr' bind_op fail_op))]
1001
1002 rn_rec_stmt all_bndrs (L loc (LetStmt binds@(HsIPBinds _))) _
1003   = do  { addErr (badIpBinds (ptext SLIT("an mdo expression")) binds)
1004         ; failM }
1005
1006 rn_rec_stmt all_bndrs (L loc (LetStmt (HsValBinds binds'))) _ = do 
1007   (binds', du_binds) <- 
1008       -- fixities and unused are handled above in rn_rec_stmts_and_then
1009       rnValBindsRHS all_bndrs binds'
1010   returnM [(duDefs du_binds, duUses du_binds, 
1011             emptyNameSet, L loc (LetStmt (HsValBinds binds')))]
1012
1013 -- no RecStmt case becuase they get flattened above when doing the LHSes
1014 rn_rec_stmt all_bndrs stmt@(L loc (RecStmt stmts _ _ _ _)) _    
1015   = pprPanic "rn_rec_stmt: RecStmt" (ppr stmt)
1016
1017 rn_rec_stmt all_bndrs stmt@(L _ (ParStmt _)) _  -- Syntactically illegal in mdo
1018   = pprPanic "rn_rec_stmt: ParStmt" (ppr stmt)
1019
1020 rn_rec_stmt all_bndrs stmt@(L _ (TransformStmt _ _ _)) _        -- Syntactically illegal in mdo
1021   = pprPanic "rn_rec_stmt: TransformStmt" (ppr stmt)
1022
1023 rn_rec_stmt all_bndrs stmt@(L _ (GroupStmt _ _)) _      -- Syntactically illegal in mdo
1024   = pprPanic "rn_rec_stmt: GroupStmt" (ppr stmt)
1025
1026 rn_rec_stmts :: [Name] -> [(LStmtLR Name RdrName, FreeVars)] -> RnM [Segment (LStmt Name)]
1027 rn_rec_stmts bndrs stmts = mappM (uncurry (rn_rec_stmt bndrs)) stmts    `thenM` \ segs_s ->
1028                            returnM (concat segs_s)
1029
1030 ---------------------------------------------
1031 addFwdRefs :: [Segment a] -> [Segment a]
1032 -- So far the segments only have forward refs *within* the Stmt
1033 --      (which happens for bind:  x <- ...x...)
1034 -- This function adds the cross-seg fwd ref info
1035
1036 addFwdRefs pairs 
1037   = fst (foldr mk_seg ([], emptyNameSet) pairs)
1038   where
1039     mk_seg (defs, uses, fwds, stmts) (segs, later_defs)
1040         = (new_seg : segs, all_defs)
1041         where
1042           new_seg = (defs, uses, new_fwds, stmts)
1043           all_defs = later_defs `unionNameSets` defs
1044           new_fwds = fwds `unionNameSets` (uses `intersectNameSet` later_defs)
1045                 -- Add the downstream fwd refs here
1046
1047 ----------------------------------------------------
1048 --      Glomming the singleton segments of an mdo into 
1049 --      minimal recursive groups.
1050 --
1051 -- At first I thought this was just strongly connected components, but
1052 -- there's an important constraint: the order of the stmts must not change.
1053 --
1054 -- Consider
1055 --      mdo { x <- ...y...
1056 --            p <- z
1057 --            y <- ...x...
1058 --            q <- x
1059 --            z <- y
1060 --            r <- x }
1061 --
1062 -- Here, the first stmt mention 'y', which is bound in the third.  
1063 -- But that means that the innocent second stmt (p <- z) gets caught
1064 -- up in the recursion.  And that in turn means that the binding for
1065 -- 'z' has to be included... and so on.
1066 --
1067 -- Start at the tail { r <- x }
1068 -- Now add the next one { z <- y ; r <- x }
1069 -- Now add one more     { q <- x ; z <- y ; r <- x }
1070 -- Now one more... but this time we have to group a bunch into rec
1071 --      { rec { y <- ...x... ; q <- x ; z <- y } ; r <- x }
1072 -- Now one more, which we can add on without a rec
1073 --      { p <- z ; 
1074 --        rec { y <- ...x... ; q <- x ; z <- y } ; 
1075 --        r <- x }
1076 -- Finally we add the last one; since it mentions y we have to
1077 -- glom it togeher with the first two groups
1078 --      { rec { x <- ...y...; p <- z ; y <- ...x... ; 
1079 --              q <- x ; z <- y } ; 
1080 --        r <- x }
1081
1082 glomSegments :: [Segment (LStmt Name)] -> [Segment [LStmt Name]]
1083
1084 glomSegments [] = []
1085 glomSegments ((defs,uses,fwds,stmt) : segs)
1086         -- Actually stmts will always be a singleton
1087   = (seg_defs, seg_uses, seg_fwds, seg_stmts)  : others
1088   where
1089     segs'            = glomSegments segs
1090     (extras, others) = grab uses segs'
1091     (ds, us, fs, ss) = unzip4 extras
1092     
1093     seg_defs  = plusFVs ds `plusFV` defs
1094     seg_uses  = plusFVs us `plusFV` uses
1095     seg_fwds  = plusFVs fs `plusFV` fwds
1096     seg_stmts = stmt : concat ss
1097
1098     grab :: NameSet             -- The client
1099          -> [Segment a]
1100          -> ([Segment a],       -- Needed by the 'client'
1101              [Segment a])       -- Not needed by the client
1102         -- The result is simply a split of the input
1103     grab uses dus 
1104         = (reverse yeses, reverse noes)
1105         where
1106           (noes, yeses)           = span not_needed (reverse dus)
1107           not_needed (defs,_,_,_) = not (intersectsNameSet defs uses)
1108
1109
1110 ----------------------------------------------------
1111 segsToStmts :: [Segment [LStmt Name]] 
1112             -> FreeVars                 -- Free vars used 'later'
1113             -> ([LStmt Name], FreeVars)
1114
1115 segsToStmts [] fvs_later = ([], fvs_later)
1116 segsToStmts ((defs, uses, fwds, ss) : segs) fvs_later
1117   = ASSERT( not (null ss) )
1118     (new_stmt : later_stmts, later_uses `plusFV` uses)
1119   where
1120     (later_stmts, later_uses) = segsToStmts segs fvs_later
1121     new_stmt | non_rec   = head ss
1122              | otherwise = L (getLoc (head ss)) $ 
1123                            RecStmt ss (nameSetToList used_later) (nameSetToList fwds) 
1124                                       [] emptyLHsBinds
1125              where
1126                non_rec    = isSingleton ss && isEmptyNameSet fwds
1127                used_later = defs `intersectNameSet` later_uses
1128                                 -- The ones needed after the RecStmt
1129 \end{code}
1130
1131 %************************************************************************
1132 %*                                                                      *
1133 \subsubsection{Assertion utils}
1134 %*                                                                      *
1135 %************************************************************************
1136
1137 \begin{code}
1138 srcSpanPrimLit :: SrcSpan -> HsExpr Name
1139 srcSpanPrimLit span = HsLit (HsStringPrim (mkFastString (showSDoc (ppr span))))
1140
1141 mkAssertErrorExpr :: RnM (HsExpr Name, FreeVars)
1142 -- Return an expression for (assertError "Foo.hs:27")
1143 mkAssertErrorExpr
1144   = getSrcSpanM                         `thenM` \ sloc ->
1145     let
1146         expr = HsApp (L sloc (HsVar assertErrorName)) 
1147                      (L sloc (srcSpanPrimLit sloc))
1148     in
1149     returnM (expr, emptyFVs)
1150 \end{code}
1151
1152 %************************************************************************
1153 %*                                                                      *
1154 \subsubsection{Errors}
1155 %*                                                                      *
1156 %************************************************************************
1157
1158 \begin{code}
1159 patSynErr e = do { addErr (sep [ptext SLIT("Pattern syntax in expression context:"),
1160                                 nest 4 (ppr e)])
1161                  ; return (EWildPat, emptyFVs) }
1162
1163
1164 parStmtErr = addErr (ptext SLIT("Illegal parallel list comprehension: use -XParallelListComp"))
1165
1166 transformStmtErr = addErr (ptext SLIT("Illegal transform or grouping list comprehension: use -XTransformListComp"))
1167 transformStmtOutsideListCompErr = addErr (ptext SLIT("Currently you may only use transform or grouping comprehensions within list comprehensions, not parallel array comprehensions"))
1168
1169 badIpBinds what binds
1170   = hang (ptext SLIT("Implicit-parameter bindings illegal in") <+> what)
1171          2 (ppr binds)
1172 \end{code}
1173
1174