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