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