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