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