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