bccd2e22af3abbde579b66b018af73b4165ee7ca
[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_GHC -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/WorkingConventions#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, rnValBinds,
28                    rnMatchGroup, trimWith ) 
29 import HsSyn
30 import TcRnMonad
31 import RnEnv
32 import HscTypes         ( availNames )
33 import RnNames          ( getLocalDeclBinders, extendRdrEnvRn )
34 import RnTypes          ( rnHsTypeFVs, rnLPat, rnOverLit, rnPatsAndThen, rnLit,
35                           mkOpFormRn, mkOpAppRn, mkNegAppRn, checkSectionPrec, 
36                           rnHsRecFields, checkTupSize )
37 import DynFlags         ( DynFlag(..) )
38 import BasicTypes       ( FixityDirection(..) )
39 import SrcLoc           ( SrcSpan )
40 import PrelNames        ( thFAKE, hasKey, assertIdKey, assertErrorName,
41                           loopAName, choiceAName, appAName, arrAName, composeAName, firstAName,
42                           negateName, thenMName, bindMName, failMName )
43
44 import Name             ( Name, nameOccName, nameIsLocalOrFrom )
45 import NameSet
46 import RdrName          ( RdrName, extendLocalRdrEnv, lookupLocalRdrEnv, hideSomeUnquals )
47 import LoadIface        ( loadInterfaceForName )
48 import UniqFM           ( isNullUFM )
49 import UniqSet          ( emptyUniqSet )
50 import List             ( nub )
51 import Util             ( isSingleton )
52 import ListSetOps       ( removeDups )
53 import Maybes           ( expectJust )
54 import Outputable
55 import SrcLoc           ( Located(..), unLoc, getLoc )
56 import FastString
57
58 import List             ( unzip4 )
59 \end{code}
60
61
62 %************************************************************************
63 %*                                                                      *
64 \subsubsection{Expressions}
65 %*                                                                      *
66 %************************************************************************
67
68 \begin{code}
69 rnExprs :: [LHsExpr RdrName] -> RnM ([LHsExpr Name], FreeVars)
70 rnExprs ls = rnExprs' ls emptyUniqSet
71  where
72   rnExprs' [] acc = returnM ([], acc)
73   rnExprs' (expr:exprs) acc
74    = rnLExpr expr               `thenM` \ (expr', fvExpr) ->
75
76         -- Now we do a "seq" on the free vars because typically it's small
77         -- or empty, especially in very long lists of constants
78     let
79         acc' = acc `plusFV` fvExpr
80     in
81     (grubby_seqNameSet acc' rnExprs') exprs acc'        `thenM` \ (exprs', fvExprs) ->
82     returnM (expr':exprs', fvExprs)
83
84 -- Grubby little function to do "seq" on namesets; replace by proper seq when GHC can do seq
85 grubby_seqNameSet ns result | isNullUFM ns = result
86                             | otherwise    = result
87 \end{code}
88
89 Variables. We look up the variable and return the resulting name. 
90
91 \begin{code}
92 rnLExpr :: LHsExpr RdrName -> RnM (LHsExpr Name, FreeVars)
93 rnLExpr = wrapLocFstM rnExpr
94
95 rnExpr :: HsExpr RdrName -> RnM (HsExpr Name, FreeVars)
96
97 rnExpr (HsVar v)
98   = do name           <- lookupOccRn v
99        ignore_asserts <- doptM Opt_IgnoreAsserts
100        finish_var ignore_asserts name
101   where
102     finish_var ignore_asserts name
103         | ignore_asserts || not (name `hasKey` assertIdKey)
104         = return (HsVar name, unitFV name)
105         | otherwise
106         = do { (e, fvs) <- mkAssertErrorExpr
107              ; return (e, fvs `addOneFV` name) }
108
109 rnExpr (HsIPVar v)
110   = newIPNameRn v               `thenM` \ name ->
111     returnM (HsIPVar name, emptyFVs)
112
113 rnExpr (HsLit lit@(HsString s))
114   = do {
115          opt_OverloadedStrings <- doptM Opt_OverloadedStrings
116        ; if opt_OverloadedStrings then
117             rnExpr (HsOverLit (mkHsIsString s))
118          else -- Same as below
119             rnLit lit           `thenM_`
120             returnM (HsLit lit, emptyFVs)
121        }
122
123 rnExpr (HsLit lit) 
124   = rnLit lit           `thenM_`
125     returnM (HsLit lit, emptyFVs)
126
127 rnExpr (HsOverLit lit) 
128   = rnOverLit lit               `thenM` \ (lit', fvs) ->
129     returnM (HsOverLit lit', fvs)
130
131 rnExpr (HsApp fun arg)
132   = rnLExpr fun         `thenM` \ (fun',fvFun) ->
133     rnLExpr arg         `thenM` \ (arg',fvArg) ->
134     returnM (HsApp fun' arg', fvFun `plusFV` fvArg)
135
136 rnExpr (OpApp e1 op _ e2) 
137   = rnLExpr e1                          `thenM` \ (e1', fv_e1) ->
138     rnLExpr e2                          `thenM` \ (e2', fv_e2) ->
139     rnLExpr op                          `thenM` \ (op'@(L _ (HsVar op_name)), fv_op) ->
140
141         -- Deal with fixity
142         -- When renaming code synthesised from "deriving" declarations
143         -- we used to avoid fixity stuff, but we can't easily tell any
144         -- more, so I've removed the test.  Adding HsPars in TcGenDeriv
145         -- should prevent bad things happening.
146     lookupFixityRn op_name              `thenM` \ fixity ->
147     mkOpAppRn e1' op' fixity e2'        `thenM` \ final_e -> 
148
149     returnM (final_e,
150               fv_e1 `plusFV` fv_op `plusFV` fv_e2)
151
152 rnExpr (NegApp e _)
153   = rnLExpr e                   `thenM` \ (e', fv_e) ->
154     lookupSyntaxName negateName `thenM` \ (neg_name, fv_neg) ->
155     mkNegAppRn e' neg_name      `thenM` \ final_e ->
156     returnM (final_e, fv_e `plusFV` fv_neg)
157
158 rnExpr (HsPar e)
159   = rnLExpr e           `thenM` \ (e', fvs_e) ->
160     returnM (HsPar e', fvs_e)
161
162 -- Template Haskell extensions
163 -- Don't ifdef-GHCI them because we want to fail gracefully
164 -- (not with an rnExpr crash) in a stage-1 compiler.
165 rnExpr e@(HsBracket br_body)
166   = checkTH e "bracket"         `thenM_`
167     rnBracket br_body           `thenM` \ (body', fvs_e) ->
168     returnM (HsBracket body', fvs_e)
169
170 rnExpr e@(HsSpliceE splice)
171   = rnSplice splice             `thenM` \ (splice', fvs) ->
172     returnM (HsSpliceE splice', fvs)
173
174 rnExpr section@(SectionL expr op)
175   = rnLExpr expr                `thenM` \ (expr', fvs_expr) ->
176     rnLExpr op                  `thenM` \ (op', fvs_op) ->
177     checkSectionPrec InfixL section op' expr' `thenM_`
178     returnM (SectionL expr' op', fvs_op `plusFV` fvs_expr)
179
180 rnExpr section@(SectionR op expr)
181   = rnLExpr op                                  `thenM` \ (op',   fvs_op) ->
182     rnLExpr expr                                        `thenM` \ (expr', fvs_expr) ->
183     checkSectionPrec InfixR section op' expr'   `thenM_`
184     returnM (SectionR op' expr', fvs_op `plusFV` fvs_expr)
185
186 rnExpr (HsCoreAnn ann expr)
187   = rnLExpr expr `thenM` \ (expr', fvs_expr) ->
188     returnM (HsCoreAnn ann expr', fvs_expr)
189
190 rnExpr (HsSCC lbl expr)
191   = rnLExpr expr                `thenM` \ (expr', fvs_expr) ->
192     returnM (HsSCC lbl expr', fvs_expr)
193 rnExpr (HsTickPragma info expr)
194   = rnLExpr expr                `thenM` \ (expr', fvs_expr) ->
195     returnM (HsTickPragma info expr', fvs_expr)
196
197 rnExpr (HsLam matches)
198   = rnMatchGroup LambdaExpr matches     `thenM` \ (matches', fvMatch) ->
199     returnM (HsLam matches', fvMatch)
200
201 rnExpr (HsCase expr matches)
202   = rnLExpr expr                        `thenM` \ (new_expr, e_fvs) ->
203     rnMatchGroup CaseAlt matches        `thenM` \ (new_matches, ms_fvs) ->
204     returnM (HsCase new_expr new_matches, e_fvs `plusFV` ms_fvs)
205
206 rnExpr (HsLet binds expr)
207   = rnLocalBindsAndThen binds           $ \ binds' ->
208     rnLExpr expr                         `thenM` \ (expr',fvExpr) ->
209     returnM (HsLet binds' expr', fvExpr)
210
211 rnExpr e@(HsDo do_or_lc stmts body _)
212   = do  { ((stmts', body'), fvs) <- rnStmts do_or_lc stmts $
213                                     rnLExpr body
214         ; return (HsDo do_or_lc stmts' body' placeHolderType, fvs) }
215
216 rnExpr (ExplicitList _ exps)
217   = rnExprs exps                        `thenM` \ (exps', fvs) ->
218     returnM  (ExplicitList placeHolderType exps', fvs)
219
220 rnExpr (ExplicitPArr _ exps)
221   = rnExprs exps                        `thenM` \ (exps', fvs) ->
222     returnM  (ExplicitPArr placeHolderType exps', fvs)
223
224 rnExpr e@(ExplicitTuple exps boxity)
225   = checkTupSize (length exps)                  `thenM_`
226     rnExprs exps                                `thenM` \ (exps', fvs) ->
227     returnM (ExplicitTuple exps' boxity, fvs)
228
229 rnExpr (RecordCon con_id _ rbinds)
230   = do  { conname <- lookupLocatedOccRn con_id
231         ; (rbinds', fvRbinds) <- rnHsRecFields "construction" (Just conname) 
232                                                 rnLExpr HsVar rbinds
233         ; return (RecordCon conname noPostTcExpr rbinds', 
234                   fvRbinds `addOneFV` unLoc conname) }
235
236 rnExpr (RecordUpd expr rbinds _ _ _)
237   = do  { (expr', fvExpr) <- rnLExpr expr
238         ; (rbinds', fvRbinds) <- rnHsRecFields "update" Nothing rnLExpr HsVar rbinds
239         ; return (RecordUpd expr' rbinds' [] [] [], 
240                   fvExpr `plusFV` fvRbinds) }
241
242 rnExpr (ExprWithTySig expr pty)
243   = do  { (pty', fvTy) <- rnHsTypeFVs doc pty
244         ; (expr', fvExpr) <- bindSigTyVarsFV (hsExplicitTvs pty') $
245                              rnLExpr expr
246         ; return (ExprWithTySig expr' pty', fvExpr `plusFV` fvTy) }
247   where 
248     doc = text "In an expression type signature"
249
250 rnExpr (HsIf p b1 b2)
251   = rnLExpr p           `thenM` \ (p', fvP) ->
252     rnLExpr b1          `thenM` \ (b1', fvB1) ->
253     rnLExpr b2          `thenM` \ (b2', fvB2) ->
254     returnM (HsIf p' b1' b2', plusFVs [fvP, fvB1, fvB2])
255
256 rnExpr (HsType a)
257   = rnHsTypeFVs doc a   `thenM` \ (t, fvT) -> 
258     returnM (HsType t, fvT)
259   where 
260     doc = text "In a type argument"
261
262 rnExpr (ArithSeq _ seq)
263   = rnArithSeq seq       `thenM` \ (new_seq, fvs) ->
264     returnM (ArithSeq noPostTcExpr new_seq, fvs)
265
266 rnExpr (PArrSeq _ seq)
267   = rnArithSeq seq       `thenM` \ (new_seq, fvs) ->
268     returnM (PArrSeq noPostTcExpr new_seq, fvs)
269 \end{code}
270
271 These three are pattern syntax appearing in expressions.
272 Since all the symbols are reservedops we can simply reject them.
273 We return a (bogus) EWildPat in each case.
274
275 \begin{code}
276 rnExpr e@EWildPat      = patSynErr e
277 rnExpr e@(EAsPat {})   = patSynErr e
278 rnExpr e@(ELazyPat {}) = patSynErr e
279 \end{code}
280
281 %************************************************************************
282 %*                                                                      *
283         Arrow notation
284 %*                                                                      *
285 %************************************************************************
286
287 \begin{code}
288 rnExpr (HsProc pat body)
289   = newArrowScope $
290     rnPatsAndThen ProcExpr [pat] $ \ [pat'] ->
291     rnCmdTop body                `thenM` \ (body',fvBody) ->
292     returnM (HsProc pat' body', fvBody)
293
294 rnExpr (HsArrApp arrow arg _ ho rtl)
295   = select_arrow_scope (rnLExpr arrow)  `thenM` \ (arrow',fvArrow) ->
296     rnLExpr arg                         `thenM` \ (arg',fvArg) ->
297     returnM (HsArrApp arrow' arg' placeHolderType ho rtl,
298              fvArrow `plusFV` fvArg)
299   where
300     select_arrow_scope tc = case ho of
301         HsHigherOrderApp -> tc
302         HsFirstOrderApp  -> escapeArrowScope tc
303
304 -- infix form
305 rnExpr (HsArrForm op (Just _) [arg1, arg2])
306   = escapeArrowScope (rnLExpr op)
307                         `thenM` \ (op'@(L _ (HsVar op_name)),fv_op) ->
308     rnCmdTop arg1       `thenM` \ (arg1',fv_arg1) ->
309     rnCmdTop arg2       `thenM` \ (arg2',fv_arg2) ->
310
311         -- Deal with fixity
312
313     lookupFixityRn op_name              `thenM` \ fixity ->
314     mkOpFormRn arg1' op' fixity arg2'   `thenM` \ final_e -> 
315
316     returnM (final_e,
317               fv_arg1 `plusFV` fv_op `plusFV` fv_arg2)
318
319 rnExpr (HsArrForm op fixity cmds)
320   = escapeArrowScope (rnLExpr op)       `thenM` \ (op',fvOp) ->
321     rnCmdArgs cmds                      `thenM` \ (cmds',fvCmds) ->
322     returnM (HsArrForm op' fixity cmds', fvOp `plusFV` fvCmds)
323
324 rnExpr other = pprPanic "rnExpr: unexpected expression" (ppr other)
325         -- HsWrap
326 \end{code}
327
328
329 %************************************************************************
330 %*                                                                      *
331         Arrow commands
332 %*                                                                      *
333 %************************************************************************
334
335 \begin{code}
336 rnCmdArgs [] = returnM ([], emptyFVs)
337 rnCmdArgs (arg:args)
338   = rnCmdTop arg        `thenM` \ (arg',fvArg) ->
339     rnCmdArgs args      `thenM` \ (args',fvArgs) ->
340     returnM (arg':args', fvArg `plusFV` fvArgs)
341
342
343 rnCmdTop = wrapLocFstM rnCmdTop'
344  where
345   rnCmdTop' (HsCmdTop cmd _ _ _) 
346    = rnLExpr (convertOpFormsLCmd cmd) `thenM` \ (cmd', fvCmd) ->
347      let 
348         cmd_names = [arrAName, composeAName, firstAName] ++
349                     nameSetToList (methodNamesCmd (unLoc cmd'))
350      in
351         -- Generate the rebindable syntax for the monad
352      lookupSyntaxTable cmd_names        `thenM` \ (cmd_names', cmd_fvs) ->
353
354      returnM (HsCmdTop cmd' [] placeHolderType cmd_names', 
355              fvCmd `plusFV` cmd_fvs)
356
357 ---------------------------------------------------
358 -- convert OpApp's in a command context to HsArrForm's
359
360 convertOpFormsLCmd :: LHsCmd id -> LHsCmd id
361 convertOpFormsLCmd = fmap convertOpFormsCmd
362
363 convertOpFormsCmd :: HsCmd id -> HsCmd id
364
365 convertOpFormsCmd (HsApp c e) = HsApp (convertOpFormsLCmd c) e
366 convertOpFormsCmd (HsLam match) = HsLam (convertOpFormsMatch match)
367 convertOpFormsCmd (OpApp c1 op fixity c2)
368   = let
369         arg1 = L (getLoc c1) $ HsCmdTop (convertOpFormsLCmd c1) [] placeHolderType []
370         arg2 = L (getLoc c2) $ HsCmdTop (convertOpFormsLCmd c2) [] placeHolderType []
371     in
372     HsArrForm op (Just fixity) [arg1, arg2]
373
374 convertOpFormsCmd (HsPar c) = HsPar (convertOpFormsLCmd c)
375
376 -- gaw 2004
377 convertOpFormsCmd (HsCase exp matches)
378   = HsCase exp (convertOpFormsMatch matches)
379
380 convertOpFormsCmd (HsIf exp c1 c2)
381   = HsIf exp (convertOpFormsLCmd c1) (convertOpFormsLCmd c2)
382
383 convertOpFormsCmd (HsLet binds cmd)
384   = HsLet binds (convertOpFormsLCmd cmd)
385
386 convertOpFormsCmd (HsDo ctxt stmts body ty)
387   = HsDo ctxt (map (fmap convertOpFormsStmt) stmts)
388               (convertOpFormsLCmd body) ty
389
390 -- Anything else is unchanged.  This includes HsArrForm (already done),
391 -- things with no sub-commands, and illegal commands (which will be
392 -- caught by the type checker)
393 convertOpFormsCmd c = c
394
395 convertOpFormsStmt (BindStmt pat cmd _ _)
396   = BindStmt pat (convertOpFormsLCmd cmd) noSyntaxExpr noSyntaxExpr
397 convertOpFormsStmt (ExprStmt cmd _ _)
398   = ExprStmt (convertOpFormsLCmd cmd) noSyntaxExpr placeHolderType
399 convertOpFormsStmt (RecStmt stmts lvs rvs es binds)
400   = RecStmt (map (fmap convertOpFormsStmt) stmts) lvs rvs es binds
401 convertOpFormsStmt stmt = stmt
402
403 convertOpFormsMatch (MatchGroup ms ty)
404   = MatchGroup (map (fmap convert) ms) ty
405  where convert (Match pat mty grhss)
406           = Match pat mty (convertOpFormsGRHSs grhss)
407
408 convertOpFormsGRHSs (GRHSs grhss binds)
409   = GRHSs (map convertOpFormsGRHS grhss) binds
410
411 convertOpFormsGRHS = fmap convert
412  where 
413    convert (GRHS stmts cmd) = GRHS stmts (convertOpFormsLCmd cmd)
414
415 ---------------------------------------------------
416 type CmdNeeds = FreeVars        -- Only inhabitants are 
417                                 --      appAName, choiceAName, loopAName
418
419 -- find what methods the Cmd needs (loop, choice, apply)
420 methodNamesLCmd :: LHsCmd Name -> CmdNeeds
421 methodNamesLCmd = methodNamesCmd . unLoc
422
423 methodNamesCmd :: HsCmd Name -> CmdNeeds
424
425 methodNamesCmd cmd@(HsArrApp _arrow _arg _ HsFirstOrderApp _rtl)
426   = emptyFVs
427 methodNamesCmd cmd@(HsArrApp _arrow _arg _ HsHigherOrderApp _rtl)
428   = unitFV appAName
429 methodNamesCmd cmd@(HsArrForm {}) = emptyFVs
430
431 methodNamesCmd (HsPar c) = methodNamesLCmd c
432
433 methodNamesCmd (HsIf p c1 c2)
434   = methodNamesLCmd c1 `plusFV` methodNamesLCmd c2 `addOneFV` choiceAName
435
436 methodNamesCmd (HsLet b c) = methodNamesLCmd c
437
438 methodNamesCmd (HsDo sc stmts body ty) 
439   = methodNamesStmts stmts `plusFV` methodNamesLCmd body
440
441 methodNamesCmd (HsApp c e) = methodNamesLCmd c
442
443 methodNamesCmd (HsLam match) = methodNamesMatch match
444
445 methodNamesCmd (HsCase scrut matches)
446   = methodNamesMatch matches `addOneFV` choiceAName
447
448 methodNamesCmd other = emptyFVs
449    -- Other forms can't occur in commands, but it's not convenient 
450    -- to error here so we just do what's convenient.
451    -- The type checker will complain later
452
453 ---------------------------------------------------
454 methodNamesMatch (MatchGroup ms _)
455   = plusFVs (map do_one ms)
456  where 
457     do_one (L _ (Match pats sig_ty grhss)) = methodNamesGRHSs grhss
458
459 -------------------------------------------------
460 -- gaw 2004
461 methodNamesGRHSs (GRHSs grhss binds) = plusFVs (map methodNamesGRHS grhss)
462
463 -------------------------------------------------
464 methodNamesGRHS (L _ (GRHS stmts rhs)) = methodNamesLCmd rhs
465
466 ---------------------------------------------------
467 methodNamesStmts stmts = plusFVs (map methodNamesLStmt stmts)
468
469 ---------------------------------------------------
470 methodNamesLStmt = methodNamesStmt . unLoc
471
472 methodNamesStmt (ExprStmt cmd _ _)     = methodNamesLCmd cmd
473 methodNamesStmt (BindStmt pat cmd _ _) = methodNamesLCmd cmd
474 methodNamesStmt (RecStmt stmts _ _ _ _)
475   = methodNamesStmts stmts `addOneFV` loopAName
476 methodNamesStmt (LetStmt b)  = emptyFVs
477 methodNamesStmt (ParStmt ss) = emptyFVs
478    -- ParStmt can't occur in commands, but it's not convenient to error 
479    -- here so we just do what's convenient
480 \end{code}
481
482
483 %************************************************************************
484 %*                                                                      *
485         Arithmetic sequences
486 %*                                                                      *
487 %************************************************************************
488
489 \begin{code}
490 rnArithSeq (From expr)
491  = rnLExpr expr         `thenM` \ (expr', fvExpr) ->
492    returnM (From expr', fvExpr)
493
494 rnArithSeq (FromThen expr1 expr2)
495  = rnLExpr expr1        `thenM` \ (expr1', fvExpr1) ->
496    rnLExpr expr2        `thenM` \ (expr2', fvExpr2) ->
497    returnM (FromThen expr1' expr2', fvExpr1 `plusFV` fvExpr2)
498
499 rnArithSeq (FromTo expr1 expr2)
500  = rnLExpr expr1        `thenM` \ (expr1', fvExpr1) ->
501    rnLExpr expr2        `thenM` \ (expr2', fvExpr2) ->
502    returnM (FromTo expr1' expr2', fvExpr1 `plusFV` fvExpr2)
503
504 rnArithSeq (FromThenTo expr1 expr2 expr3)
505  = rnLExpr expr1        `thenM` \ (expr1', fvExpr1) ->
506    rnLExpr expr2        `thenM` \ (expr2', fvExpr2) ->
507    rnLExpr expr3        `thenM` \ (expr3', fvExpr3) ->
508    returnM (FromThenTo expr1' expr2' expr3',
509             plusFVs [fvExpr1, fvExpr2, fvExpr3])
510 \end{code}
511
512 %************************************************************************
513 %*                                                                      *
514         Template Haskell brackets
515 %*                                                                      *
516 %************************************************************************
517
518 \begin{code}
519 rnBracket (VarBr n) = do { name <- lookupOccRn n
520                          ; this_mod <- getModule
521                          ; checkM (nameIsLocalOrFrom this_mod name) $   -- Reason: deprecation checking asumes the
522                            do { loadInterfaceForName msg name           -- home interface is loaded, and this is the
523                               ; return () }                             -- only way that is going to happen
524                          ; returnM (VarBr name, unitFV name) }
525                     where
526                       msg = ptext SLIT("Need interface for Template Haskell quoted Name")
527
528 rnBracket (ExpBr e) = do { (e', fvs) <- rnLExpr e
529                          ; return (ExpBr e', fvs) }
530 rnBracket (PatBr p) = do { (p', fvs) <- rnLPat p
531                          ; return (PatBr p', fvs) }
532 rnBracket (TypBr t) = do { (t', fvs) <- rnHsTypeFVs doc t
533                          ; return (TypBr t', fvs) }
534                     where
535                       doc = ptext SLIT("In a Template-Haskell quoted type")
536 rnBracket (DecBr group) 
537   = do  { gbl_env  <- getGblEnv
538
539         ; let gbl_env1 = gbl_env { tcg_mod = thFAKE }
540         -- Note the thFAKE.  The top-level names from the bracketed 
541         -- declarations will go into the name cache, and we don't want them to 
542         -- confuse the Names for the current module.  
543         -- By using a pretend module, thFAKE, we keep them safely out of the way.
544
545         ; avails <- getLocalDeclBinders gbl_env1 group
546         ; let names = concatMap availNames avails
547
548         ; let new_occs = map nameOccName names
549               trimmed_rdr_env = hideSomeUnquals (tcg_rdr_env gbl_env) new_occs
550
551         ; rdr_env' <- extendRdrEnvRn trimmed_rdr_env avails
552         -- In this situation we want to *shadow* top-level bindings.
553         --      foo = 1
554         --      bar = [d| foo = 1|]
555         -- If we don't shadow, we'll get an ambiguity complaint when we do 
556         -- a lookupTopBndrRn (which uses lookupGreLocalRn) on the binder of the 'foo'
557         --
558         -- Furthermore, arguably if the splice does define foo, that should hide
559         -- any foo's further out
560         --
561         -- The shadowing is acheived by the call to hideSomeUnquals, which removes
562         -- the unqualified bindings of things defined by the bracket
563
564         ; setGblEnv (gbl_env { tcg_rdr_env = rdr_env',
565                                tcg_dus = emptyDUs }) $ do
566                 -- The emptyDUs is so that we just collect uses for this group alone
567
568         { (tcg_env, group') <- rnSrcDecls group
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) 
599                 <- rnStmt ctxt stmt     $
600                    rnNormalStmts ctxt stmts thing_inside
601         ; return (((L loc stmt' : stmts'), thing), fvs) }
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 (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
627   = do  { checkErr (ok ctxt binds) 
628                    (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   = bindLocatedLocalsRn doc (collectLStmtsBinders rec_stmts)    $ \ bndrs ->
640     rn_rec_stmts bndrs rec_stmts        `thenM` \ 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 (ParStmt segs) thing_inside
655   = do  { parallel_list_comp <- doptM Opt_ParallelListComp
656         ; checkM parallel_list_comp parStmtErr
657         ; orig_lcl_env <- getLocalRdrEnv
658         ; ((segs',thing), fvs) <- go orig_lcl_env [] segs
659         ; return ((ParStmt segs', thing), fvs) }
660   where
661 --  type ParSeg id = [([LStmt id], [id])]
662 --  go :: NameSet -> [ParSeg RdrName]
663 --       -> RnM (([ParSeg Name], thing), FreeVars)
664
665     go orig_lcl_env bndrs [] 
666         = do { let { (bndrs', dups) = removeDups cmpByOcc bndrs
667                    ; inner_env = extendLocalRdrEnv orig_lcl_env bndrs' }
668              ; mappM dupErr dups
669              ; (thing, fvs) <- setLocalRdrEnv inner_env thing_inside
670              ; return (([], thing), fvs) }
671
672     go orig_lcl_env bndrs_so_far ((stmts, _) : segs)
673         = do { ((stmts', (bndrs, segs', thing)), fvs)
674                   <- rnNormalStmts par_ctxt stmts $ do
675                      {  -- Find the Names that are bound by stmts
676                        lcl_env <- getLocalRdrEnv
677                      ; let { rdr_bndrs = collectLStmtsBinders stmts
678                            ; bndrs = map ( expectJust "rnStmt"
679                                          . lookupLocalRdrEnv lcl_env
680                                          . unLoc) rdr_bndrs
681                            ; new_bndrs = nub bndrs ++ bndrs_so_far 
682                                 -- The nub is because there might be shadowing
683                                 --      x <- e1; x <- e2
684                                 -- So we'll look up (Unqual x) twice, getting
685                                 -- the second binding both times, which is the
686                         }       -- one we want
687
688                         -- Typecheck the thing inside, passing on all
689                         -- the Names bound, but separately; revert the envt
690                      ; ((segs', thing), fvs) <- setLocalRdrEnv orig_lcl_env $
691                                                 go orig_lcl_env new_bndrs segs
692
693                         -- Figure out which of the bound names are used
694                      ; let used_bndrs = filter (`elemNameSet` fvs) bndrs
695                      ; return ((used_bndrs, segs', thing), fvs) }
696
697              ; let seg' = (stmts', bndrs)
698              ; return (((seg':segs'), thing), 
699                        delListFromNameSet fvs bndrs) }
700
701     par_ctxt = ParStmtCtxt ctxt
702
703     cmpByOcc n1 n2 = nameOccName n1 `compare` nameOccName n2
704     dupErr vs = addErr (ptext SLIT("Duplicate binding in parallel list comprehension for:")
705                         <+> quotes (ppr (head vs)))
706 \end{code}
707
708
709 %************************************************************************
710 %*                                                                      *
711 \subsubsection{mdo expressions}
712 %*                                                                      *
713 %************************************************************************
714
715 \begin{code}
716 type FwdRefs = NameSet
717 type Segment stmts = (Defs,
718                       Uses,     -- May include defs
719                       FwdRefs,  -- A subset of uses that are 
720                                 --   (a) used before they are bound in this segment, or 
721                                 --   (b) used here, and bound in subsequent segments
722                       stmts)    -- Either Stmt or [Stmt]
723
724
725 ----------------------------------------------------
726 rnMDoStmts :: [LStmt RdrName]
727            -> RnM (thing, FreeVars)
728            -> RnM (([LStmt Name], thing), FreeVars)     
729 rnMDoStmts stmts thing_inside
730   =     -- Step1: bring all the binders of the mdo into scope
731         -- Remember that this also removes the binders from the
732         -- finally-returned free-vars
733     bindLocatedLocalsRn doc (collectLStmtsBinders stmts)        $ \ bndrs ->
734     do  { 
735         -- Step 2: Rename each individual stmt, making a
736         --         singleton segment.  At this stage the FwdRefs field
737         --         isn't finished: it's empty for all except a BindStmt
738         --         for which it's the fwd refs within the bind itself
739         --         (This set may not be empty, because we're in a recursive 
740         --          context.)
741           segs <- rn_rec_stmts bndrs stmts
742
743         ; (thing, fvs_later) <- thing_inside
744
745         ; let
746         -- Step 3: Fill in the fwd refs.
747         --         The segments are all singletons, but their fwd-ref
748         --         field mentions all the things used by the segment
749         --         that are bound after their use
750             segs_w_fwd_refs = addFwdRefs segs
751
752         -- Step 4: Group together the segments to make bigger segments
753         --         Invariant: in the result, no segment uses a variable
754         --                    bound in a later segment
755             grouped_segs = glomSegments segs_w_fwd_refs
756
757         -- Step 5: Turn the segments into Stmts
758         --         Use RecStmt when and only when there are fwd refs
759         --         Also gather up the uses from the end towards the
760         --         start, so we can tell the RecStmt which things are
761         --         used 'after' the RecStmt
762             (stmts', fvs) = segsToStmts grouped_segs fvs_later
763
764         ; return ((stmts', thing), fvs) }
765   where
766     doc = text "In a recursive mdo-expression"
767
768 ---------------------------------------------
769 rn_rec_stmts :: [Name] -> [LStmt RdrName] -> RnM [Segment (LStmt Name)]
770 rn_rec_stmts bndrs stmts = mappM (rn_rec_stmt bndrs) stmts      `thenM` \ segs_s ->
771                            returnM (concat segs_s)
772
773 ----------------------------------------------------
774 rn_rec_stmt :: [Name] -> LStmt RdrName -> RnM [Segment (LStmt Name)]
775         -- Rename a Stmt that is inside a RecStmt (or mdo)
776         -- Assumes all binders are already in scope
777         -- Turns each stmt into a singleton Stmt
778
779 rn_rec_stmt all_bndrs (L loc (ExprStmt expr _ _))
780   = rnLExpr expr                `thenM` \ (expr', fvs) ->
781     lookupSyntaxName thenMName  `thenM` \ (then_op, fvs1) ->
782     returnM [(emptyNameSet, fvs `plusFV` fvs1, emptyNameSet,
783               L loc (ExprStmt expr' then_op placeHolderType))]
784
785 rn_rec_stmt all_bndrs (L loc (BindStmt pat expr _ _))
786   = rnLExpr expr                `thenM` \ (expr', fv_expr) ->
787     rnLPat pat                  `thenM` \ (pat', fv_pat) ->
788     lookupSyntaxName bindMName  `thenM` \ (bind_op, fvs1) ->
789     lookupSyntaxName failMName  `thenM` \ (fail_op, fvs2) ->
790     let
791         bndrs = mkNameSet (collectPatBinders pat')
792         fvs   = fv_expr `plusFV` fv_pat `plusFV` fvs1 `plusFV` fvs2
793     in
794     returnM [(bndrs, fvs, bndrs `intersectNameSet` fvs,
795               L loc (BindStmt pat' expr' bind_op fail_op))]
796
797 rn_rec_stmt all_bndrs (L loc (LetStmt binds@(HsIPBinds _)))
798   = do  { addErr (badIpBinds (ptext SLIT("an mdo expression")) binds)
799         ; failM }
800
801 rn_rec_stmt all_bndrs (L loc (LetStmt (HsValBinds binds)))
802   = rnValBinds (trimWith all_bndrs) binds       `thenM` \ (binds', du_binds) ->
803     returnM [(duDefs du_binds, duUses du_binds, 
804               emptyNameSet, L loc (LetStmt (HsValBinds binds')))]
805
806 rn_rec_stmt all_bndrs (L loc (RecStmt stmts _ _ _ _))   -- Flatten Rec inside Rec
807   = rn_rec_stmts all_bndrs stmts
808
809 rn_rec_stmt all_bndrs stmt@(L _ (ParStmt _))    -- Syntactically illegal in mdo
810   = pprPanic "rn_rec_stmt" (ppr stmt)
811
812 ---------------------------------------------
813 addFwdRefs :: [Segment a] -> [Segment a]
814 -- So far the segments only have forward refs *within* the Stmt
815 --      (which happens for bind:  x <- ...x...)
816 -- This function adds the cross-seg fwd ref info
817
818 addFwdRefs pairs 
819   = fst (foldr mk_seg ([], emptyNameSet) pairs)
820   where
821     mk_seg (defs, uses, fwds, stmts) (segs, later_defs)
822         = (new_seg : segs, all_defs)
823         where
824           new_seg = (defs, uses, new_fwds, stmts)
825           all_defs = later_defs `unionNameSets` defs
826           new_fwds = fwds `unionNameSets` (uses `intersectNameSet` later_defs)
827                 -- Add the downstream fwd refs here
828
829 ----------------------------------------------------
830 --      Glomming the singleton segments of an mdo into 
831 --      minimal recursive groups.
832 --
833 -- At first I thought this was just strongly connected components, but
834 -- there's an important constraint: the order of the stmts must not change.
835 --
836 -- Consider
837 --      mdo { x <- ...y...
838 --            p <- z
839 --            y <- ...x...
840 --            q <- x
841 --            z <- y
842 --            r <- x }
843 --
844 -- Here, the first stmt mention 'y', which is bound in the third.  
845 -- But that means that the innocent second stmt (p <- z) gets caught
846 -- up in the recursion.  And that in turn means that the binding for
847 -- 'z' has to be included... and so on.
848 --
849 -- Start at the tail { r <- x }
850 -- Now add the next one { z <- y ; r <- x }
851 -- Now add one more     { q <- x ; z <- y ; r <- x }
852 -- Now one more... but this time we have to group a bunch into rec
853 --      { rec { y <- ...x... ; q <- x ; z <- y } ; r <- x }
854 -- Now one more, which we can add on without a rec
855 --      { p <- z ; 
856 --        rec { y <- ...x... ; q <- x ; z <- y } ; 
857 --        r <- x }
858 -- Finally we add the last one; since it mentions y we have to
859 -- glom it togeher with the first two groups
860 --      { rec { x <- ...y...; p <- z ; y <- ...x... ; 
861 --              q <- x ; z <- y } ; 
862 --        r <- x }
863
864 glomSegments :: [Segment (LStmt Name)] -> [Segment [LStmt Name]]
865
866 glomSegments [] = []
867 glomSegments ((defs,uses,fwds,stmt) : segs)
868         -- Actually stmts will always be a singleton
869   = (seg_defs, seg_uses, seg_fwds, seg_stmts)  : others
870   where
871     segs'            = glomSegments segs
872     (extras, others) = grab uses segs'
873     (ds, us, fs, ss) = unzip4 extras
874     
875     seg_defs  = plusFVs ds `plusFV` defs
876     seg_uses  = plusFVs us `plusFV` uses
877     seg_fwds  = plusFVs fs `plusFV` fwds
878     seg_stmts = stmt : concat ss
879
880     grab :: NameSet             -- The client
881          -> [Segment a]
882          -> ([Segment a],       -- Needed by the 'client'
883              [Segment a])       -- Not needed by the client
884         -- The result is simply a split of the input
885     grab uses dus 
886         = (reverse yeses, reverse noes)
887         where
888           (noes, yeses)           = span not_needed (reverse dus)
889           not_needed (defs,_,_,_) = not (intersectsNameSet defs uses)
890
891
892 ----------------------------------------------------
893 segsToStmts :: [Segment [LStmt Name]] 
894             -> FreeVars                 -- Free vars used 'later'
895             -> ([LStmt Name], FreeVars)
896
897 segsToStmts [] fvs_later = ([], fvs_later)
898 segsToStmts ((defs, uses, fwds, ss) : segs) fvs_later
899   = ASSERT( not (null ss) )
900     (new_stmt : later_stmts, later_uses `plusFV` uses)
901   where
902     (later_stmts, later_uses) = segsToStmts segs fvs_later
903     new_stmt | non_rec   = head ss
904              | otherwise = L (getLoc (head ss)) $ 
905                            RecStmt ss (nameSetToList used_later) (nameSetToList fwds) 
906                                       [] emptyLHsBinds
907              where
908                non_rec    = isSingleton ss && isEmptyNameSet fwds
909                used_later = defs `intersectNameSet` later_uses
910                                 -- The ones needed after the RecStmt
911 \end{code}
912
913 %************************************************************************
914 %*                                                                      *
915 \subsubsection{Assertion utils}
916 %*                                                                      *
917 %************************************************************************
918
919 \begin{code}
920 srcSpanPrimLit :: SrcSpan -> HsExpr Name
921 srcSpanPrimLit span = HsLit (HsStringPrim (mkFastString (showSDoc (ppr span))))
922
923 mkAssertErrorExpr :: RnM (HsExpr Name, FreeVars)
924 -- Return an expression for (assertError "Foo.hs:27")
925 mkAssertErrorExpr
926   = getSrcSpanM                         `thenM` \ sloc ->
927     let
928         expr = HsApp (L sloc (HsVar assertErrorName)) 
929                      (L sloc (srcSpanPrimLit sloc))
930     in
931     returnM (expr, emptyFVs)
932 \end{code}
933
934 %************************************************************************
935 %*                                                                      *
936 \subsubsection{Errors}
937 %*                                                                      *
938 %************************************************************************
939
940 \begin{code}
941 patSynErr e = do { addErr (sep [ptext SLIT("Pattern syntax in expression context:"),
942                                 nest 4 (ppr e)])
943                  ; return (EWildPat, emptyFVs) }
944
945 parStmtErr = addErr (ptext SLIT("Illegal parallel list comprehension: use -XParallelListComp"))
946
947 badIpBinds what binds
948   = hang (ptext SLIT("Implicit-parameter bindings illegal in") <+> what)
949          2 (ppr binds)
950 \end{code}
951
952