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