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