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