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