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