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