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