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