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