[project @ 2005-07-19 16:44:50 by simonpj]
[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        ( hasKey, assertIdKey, assertErrorName,
34                           loopAName, choiceAName, appAName, arrAName, composeAName, firstAName,
35                           negateName, thenMName, bindMName, failMName )
36 import Name             ( Name, nameOccName )
37 import NameSet
38 import RdrName          ( RdrName, emptyGlobalRdrEnv, extendLocalRdrEnv, lookupLocalRdrEnv )
39 import UnicodeUtil      ( stringToUtf8 )
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) = lookupOccRn n             `thenM` \ name -> 
530                       returnM (VarBr name, unitFV name)
531 rnBracket (ExpBr e) = rnLExpr e         `thenM` \ (e', fvs) ->
532                       returnM (ExpBr e', fvs)
533 rnBracket (PatBr p) = rnLPat p          `thenM` \ (p', fvs) ->
534                       returnM (PatBr p', fvs)
535 rnBracket (TypBr t) = rnHsTypeFVs doc t `thenM` \ (t', fvs) ->
536                       returnM (TypBr t', fvs)
537                     where
538                       doc = ptext SLIT("In a Template-Haskell quoted type")
539 rnBracket (DecBr group) 
540   = do  { gbl_env  <- getGblEnv
541         ; names    <- getLocalDeclBinders gbl_env group
542         ; rdr_env' <- extendRdrEnvRn (tcg_mod gbl_env) emptyGlobalRdrEnv names
543
544         ; setGblEnv (gbl_env { tcg_rdr_env = tcg_rdr_env gbl_env `plusOccEnv` rdr_env',
545                                tcg_dus = emptyDUs }) $ do
546                 -- Notice plusOccEnv, not plusGlobalRdrEnv.  In this situation we want
547                 -- to *shadow* top-level bindings.  E.g.
548                 --      foo = 1
549                 --      bar = [d| foo = 1|]
550                 -- So we drop down to plusOccEnv.  (Perhaps there should be a fn in RdrName.)
551                 --      
552                 -- The emptyDUs is so that we just collect uses for this group alone
553
554         { (tcg_env, group') <- rnSrcDecls group
555                 -- Discard the tcg_env; it contains only extra info about fixity
556         ; return (DecBr group', allUses (tcg_dus tcg_env)) } }
557 \end{code}
558
559 %************************************************************************
560 %*                                                                      *
561 \subsubsection{@Stmt@s: in @do@ expressions}
562 %*                                                                      *
563 %************************************************************************
564
565 \begin{code}
566 rnStmts :: HsStmtContext Name -> [LStmt RdrName] 
567         -> RnM (thing, FreeVars)
568         -> RnM (([LStmt Name], thing), FreeVars)
569
570 rnStmts (MDoExpr _) = rnMDoStmts
571 rnStmts ctxt        = rnNormalStmts ctxt
572
573 rnNormalStmts :: HsStmtContext Name -> [LStmt RdrName]
574               -> RnM (thing, FreeVars)
575               -> RnM (([LStmt Name], thing), FreeVars)  
576 -- Used for cases *other* than recursive mdo
577 -- Implements nested scopes
578
579 rnNormalStmts ctxt [] thing_inside 
580   = do  { (thing, fvs) <- thing_inside
581         ; return (([],thing), fvs) } 
582
583 rnNormalStmts ctxt (L loc stmt : stmts) thing_inside
584   = do  { ((stmt', (stmts', thing)), fvs) 
585                 <- rnStmt ctxt stmt     $
586                    rnNormalStmts ctxt stmts thing_inside
587         ; return (((L loc stmt' : stmts'), thing), fvs) }
588     
589 rnStmt :: HsStmtContext Name -> Stmt RdrName
590        -> RnM (thing, FreeVars)
591        -> RnM ((Stmt Name, thing), FreeVars)
592
593 rnStmt ctxt (ExprStmt expr _ _) thing_inside
594   = do  { (expr', fv_expr) <- rnLExpr expr
595         ; (then_op, fvs1)  <- lookupSyntaxName thenMName
596         ; (thing, fvs2)    <- thing_inside
597         ; return ((ExprStmt expr' then_op placeHolderType, thing),
598                   fv_expr `plusFV` fvs1 `plusFV` fvs2) }
599
600 rnStmt ctxt (BindStmt pat expr _ _) thing_inside
601   = do  { (expr', fv_expr) <- rnLExpr expr
602                 -- The binders do not scope over the expression
603         ; (bind_op, fvs1) <- lookupSyntaxName bindMName
604         ; (fail_op, fvs2) <- lookupSyntaxName failMName
605         ; rnPatsAndThen (StmtCtxt ctxt) [pat] $ \ [pat'] -> do
606         { (thing, fvs3) <- thing_inside
607         ; return ((BindStmt pat' expr' bind_op fail_op, thing),
608                   fv_expr `plusFV` fvs1 `plusFV` fvs2 `plusFV` fvs3) }}
609         -- fv_expr shouldn't really be filtered by the rnPatsAndThen
610         -- but it does not matter because the names are unique
611
612 rnStmt ctxt (LetStmt binds) thing_inside
613   = do  { checkErr (ok ctxt binds) 
614                    (badIpBinds (ptext SLIT("a parallel list comprehension:")) binds)
615         ; rnLocalBindsAndThen binds             $ \ binds' -> do
616         { (thing, fvs) <- thing_inside
617         ; return ((LetStmt binds', thing), fvs) }}
618   where
619         -- We do not allow implicit-parameter bindings in a parallel
620         -- list comprehension.  I'm not sure what it might mean.
621     ok (ParStmtCtxt _) (HsIPBinds _) = False
622     ok _               _             = True
623
624 rnStmt ctxt (RecStmt rec_stmts _ _ _ _) thing_inside
625   = bindLocatedLocalsRn doc (collectLStmtsBinders rec_stmts)    $ \ bndrs ->
626     rn_rec_stmts bndrs rec_stmts        `thenM` \ segs ->
627     thing_inside                        `thenM` \ (thing, fvs) ->
628     let
629         segs_w_fwd_refs          = addFwdRefs segs
630         (ds, us, fs, rec_stmts') = unzip4 segs_w_fwd_refs
631         later_vars = nameSetToList (plusFVs ds `intersectNameSet` fvs)
632         fwd_vars   = nameSetToList (plusFVs fs)
633         uses       = plusFVs us
634         rec_stmt   = RecStmt rec_stmts' later_vars fwd_vars [] emptyLHsBinds
635     in  
636     returnM ((rec_stmt, thing), uses `plusFV` fvs)
637   where
638     doc = text "In a recursive do statement"
639
640 rnStmt ctxt (ParStmt segs) thing_inside
641   = do  { opt_GlasgowExts <- doptM Opt_GlasgowExts
642         ; checkM opt_GlasgowExts parStmtErr
643         ; orig_lcl_env <- getLocalRdrEnv
644         ; ((segs',thing), fvs) <- go orig_lcl_env [] segs
645         ; return ((ParStmt segs', thing), fvs) }
646   where
647 --  type ParSeg id = [([LStmt id], [id])]
648 --  go :: NameSet -> [ParSeg RdrName]
649 --       -> RnM (([ParSeg Name], thing), FreeVars)
650
651     go orig_lcl_env bndrs [] 
652         = do { let { (bndrs', dups) = removeDups cmpByOcc bndrs
653                    ; inner_env = extendLocalRdrEnv orig_lcl_env bndrs' }
654              ; mappM dupErr dups
655              ; (thing, fvs) <- setLocalRdrEnv inner_env thing_inside
656              ; return (([], thing), fvs) }
657
658     go orig_lcl_env bndrs_so_far ((stmts, _) : segs)
659         = do { ((stmts', (bndrs, segs', thing)), fvs)
660                   <- rnNormalStmts par_ctxt stmts $ do
661                      {  -- Find the Names that are bound by stmts
662                        lcl_env <- getLocalRdrEnv
663                      ; let { rdr_bndrs = collectLStmtsBinders stmts
664                            ; bndrs = map ( fromJust
665                                          . lookupLocalRdrEnv lcl_env
666                                          . unLoc) rdr_bndrs
667                            ; new_bndrs = nub bndrs ++ bndrs_so_far 
668                                 -- The nub is because there might be shadowing
669                                 --      x <- e1; x <- e2
670                                 -- So we'll look up (Unqual x) twice, getting
671                                 -- the second binding both times, which is the
672                         }       -- one we want
673
674                         -- Typecheck the thing inside, passing on all
675                         -- the Names bound, but separately; revert the envt
676                      ; ((segs', thing), fvs) <- setLocalRdrEnv orig_lcl_env $
677                                                 go orig_lcl_env new_bndrs segs
678
679                         -- Figure out which of the bound names are used
680                      ; let used_bndrs = filter (`elemNameSet` fvs) bndrs
681                      ; return ((used_bndrs, segs', thing), fvs) }
682
683              ; let seg' = (stmts', bndrs)
684              ; return (((seg':segs'), thing), 
685                        delListFromNameSet fvs bndrs) }
686
687     par_ctxt = ParStmtCtxt ctxt
688
689     cmpByOcc n1 n2 = nameOccName n1 `compare` nameOccName n2
690     dupErr vs = addErr (ptext SLIT("Duplicate binding in parallel list comprehension for:")
691                         <+> quotes (ppr (head vs)))
692 \end{code}
693
694
695 %************************************************************************
696 %*                                                                      *
697 \subsubsection{mdo expressions}
698 %*                                                                      *
699 %************************************************************************
700
701 \begin{code}
702 type FwdRefs = NameSet
703 type Segment stmts = (Defs,
704                       Uses,     -- May include defs
705                       FwdRefs,  -- A subset of uses that are 
706                                 --   (a) used before they are bound in this segment, or 
707                                 --   (b) used here, and bound in subsequent segments
708                       stmts)    -- Either Stmt or [Stmt]
709
710
711 ----------------------------------------------------
712 rnMDoStmts :: [LStmt RdrName]
713            -> RnM (thing, FreeVars)
714            -> RnM (([LStmt Name], thing), FreeVars)     
715 rnMDoStmts stmts thing_inside
716   =     -- Step1: bring all the binders of the mdo into scope
717         -- Remember that this also removes the binders from the
718         -- finally-returned free-vars
719     bindLocatedLocalsRn doc (collectLStmtsBinders stmts)        $ \ bndrs ->
720     do  { 
721         -- Step 2: Rename each individual stmt, making a
722         --         singleton segment.  At this stage the FwdRefs field
723         --         isn't finished: it's empty for all except a BindStmt
724         --         for which it's the fwd refs within the bind itself
725         --         (This set may not be empty, because we're in a recursive 
726         --          context.)
727           segs <- rn_rec_stmts bndrs stmts
728
729         ; (thing, fvs_later) <- thing_inside
730
731         ; let
732         -- Step 3: Fill in the fwd refs.
733         --         The segments are all singletons, but their fwd-ref
734         --         field mentions all the things used by the segment
735         --         that are bound after their use
736             segs_w_fwd_refs = addFwdRefs segs
737
738         -- Step 4: Group together the segments to make bigger segments
739         --         Invariant: in the result, no segment uses a variable
740         --                    bound in a later segment
741             grouped_segs = glomSegments segs_w_fwd_refs
742
743         -- Step 5: Turn the segments into Stmts
744         --         Use RecStmt when and only when there are fwd refs
745         --         Also gather up the uses from the end towards the
746         --         start, so we can tell the RecStmt which things are
747         --         used 'after' the RecStmt
748             (stmts', fvs) = segsToStmts grouped_segs fvs_later
749
750         ; return ((stmts', thing), fvs) }
751   where
752     doc = text "In a recursive mdo-expression"
753
754 ---------------------------------------------
755 rn_rec_stmts :: [Name] -> [LStmt RdrName] -> RnM [Segment (LStmt Name)]
756 rn_rec_stmts bndrs stmts = mappM (rn_rec_stmt bndrs) stmts      `thenM` \ segs_s ->
757                            returnM (concat segs_s)
758
759 ----------------------------------------------------
760 rn_rec_stmt :: [Name] -> LStmt RdrName -> RnM [Segment (LStmt Name)]
761         -- Rename a Stmt that is inside a RecStmt (or mdo)
762         -- Assumes all binders are already in scope
763         -- Turns each stmt into a singleton Stmt
764
765 rn_rec_stmt all_bndrs (L loc (ExprStmt expr _ _))
766   = rnLExpr expr                `thenM` \ (expr', fvs) ->
767     lookupSyntaxName thenMName  `thenM` \ (then_op, fvs1) ->
768     returnM [(emptyNameSet, fvs `plusFV` fvs1, emptyNameSet,
769               L loc (ExprStmt expr' then_op placeHolderType))]
770
771 rn_rec_stmt all_bndrs (L loc (BindStmt pat expr _ _))
772   = rnLExpr expr                `thenM` \ (expr', fv_expr) ->
773     rnLPat pat                  `thenM` \ (pat', fv_pat) ->
774     lookupSyntaxName bindMName  `thenM` \ (bind_op, fvs1) ->
775     lookupSyntaxName failMName  `thenM` \ (fail_op, fvs2) ->
776     let
777         bndrs = mkNameSet (collectPatBinders pat')
778         fvs   = fv_expr `plusFV` fv_pat `plusFV` fvs1 `plusFV` fvs2
779     in
780     returnM [(bndrs, fvs, bndrs `intersectNameSet` fvs,
781               L loc (BindStmt pat' expr' bind_op fail_op))]
782
783 rn_rec_stmt all_bndrs (L loc (LetStmt binds@(HsIPBinds _)))
784   = do  { addErr (badIpBinds (ptext SLIT("an mdo expression")) binds)
785         ; failM }
786
787 rn_rec_stmt all_bndrs (L loc (LetStmt (HsValBinds binds)))
788   = rnValBinds (trimWith all_bndrs) binds       `thenM` \ (binds', du_binds) ->
789     returnM [(duDefs du_binds, duUses du_binds, 
790               emptyNameSet, L loc (LetStmt (HsValBinds binds')))]
791
792 rn_rec_stmt all_bndrs (L loc (RecStmt stmts _ _ _ _))   -- Flatten Rec inside Rec
793   = rn_rec_stmts all_bndrs stmts
794
795 rn_rec_stmt all_bndrs stmt@(L _ (ParStmt _))    -- Syntactically illegal in mdo
796   = pprPanic "rn_rec_stmt" (ppr stmt)
797
798 ---------------------------------------------
799 addFwdRefs :: [Segment a] -> [Segment a]
800 -- So far the segments only have forward refs *within* the Stmt
801 --      (which happens for bind:  x <- ...x...)
802 -- This function adds the cross-seg fwd ref info
803
804 addFwdRefs pairs 
805   = fst (foldr mk_seg ([], emptyNameSet) pairs)
806   where
807     mk_seg (defs, uses, fwds, stmts) (segs, later_defs)
808         = (new_seg : segs, all_defs)
809         where
810           new_seg = (defs, uses, new_fwds, stmts)
811           all_defs = later_defs `unionNameSets` defs
812           new_fwds = fwds `unionNameSets` (uses `intersectNameSet` later_defs)
813                 -- Add the downstream fwd refs here
814
815 ----------------------------------------------------
816 --      Glomming the singleton segments of an mdo into 
817 --      minimal recursive groups.
818 --
819 -- At first I thought this was just strongly connected components, but
820 -- there's an important constraint: the order of the stmts must not change.
821 --
822 -- Consider
823 --      mdo { x <- ...y...
824 --            p <- z
825 --            y <- ...x...
826 --            q <- x
827 --            z <- y
828 --            r <- x }
829 --
830 -- Here, the first stmt mention 'y', which is bound in the third.  
831 -- But that means that the innocent second stmt (p <- z) gets caught
832 -- up in the recursion.  And that in turn means that the binding for
833 -- 'z' has to be included... and so on.
834 --
835 -- Start at the tail { r <- x }
836 -- Now add the next one { z <- y ; r <- x }
837 -- Now add one more     { q <- x ; z <- y ; r <- x }
838 -- Now one more... but this time we have to group a bunch into rec
839 --      { rec { y <- ...x... ; q <- x ; z <- y } ; r <- x }
840 -- Now one more, which we can add on without a rec
841 --      { p <- z ; 
842 --        rec { y <- ...x... ; q <- x ; z <- y } ; 
843 --        r <- x }
844 -- Finally we add the last one; since it mentions y we have to
845 -- glom it togeher with the first two groups
846 --      { rec { x <- ...y...; p <- z ; y <- ...x... ; 
847 --              q <- x ; z <- y } ; 
848 --        r <- x }
849
850 glomSegments :: [Segment (LStmt Name)] -> [Segment [LStmt Name]]
851
852 glomSegments [] = []
853 glomSegments ((defs,uses,fwds,stmt) : segs)
854         -- Actually stmts will always be a singleton
855   = (seg_defs, seg_uses, seg_fwds, seg_stmts)  : others
856   where
857     segs'            = glomSegments segs
858     (extras, others) = grab uses segs'
859     (ds, us, fs, ss) = unzip4 extras
860     
861     seg_defs  = plusFVs ds `plusFV` defs
862     seg_uses  = plusFVs us `plusFV` uses
863     seg_fwds  = plusFVs fs `plusFV` fwds
864     seg_stmts = stmt : concat ss
865
866     grab :: NameSet             -- The client
867          -> [Segment a]
868          -> ([Segment a],       -- Needed by the 'client'
869              [Segment a])       -- Not needed by the client
870         -- The result is simply a split of the input
871     grab uses dus 
872         = (reverse yeses, reverse noes)
873         where
874           (noes, yeses)           = span not_needed (reverse dus)
875           not_needed (defs,_,_,_) = not (intersectsNameSet defs uses)
876
877
878 ----------------------------------------------------
879 segsToStmts :: [Segment [LStmt Name]] 
880             -> FreeVars                 -- Free vars used 'later'
881             -> ([LStmt Name], FreeVars)
882
883 segsToStmts [] fvs_later = ([], fvs_later)
884 segsToStmts ((defs, uses, fwds, ss) : segs) fvs_later
885   = ASSERT( not (null ss) )
886     (new_stmt : later_stmts, later_uses `plusFV` uses)
887   where
888     (later_stmts, later_uses) = segsToStmts segs fvs_later
889     new_stmt | non_rec   = head ss
890              | otherwise = L (getLoc (head ss)) $ 
891                            RecStmt ss (nameSetToList used_later) (nameSetToList fwds) 
892                                       [] emptyLHsBinds
893              where
894                non_rec    = isSingleton ss && isEmptyNameSet fwds
895                used_later = defs `intersectNameSet` later_uses
896                                 -- The ones needed after the RecStmt
897 \end{code}
898
899 %************************************************************************
900 %*                                                                      *
901 \subsubsection{Assertion utils}
902 %*                                                                      *
903 %************************************************************************
904
905 \begin{code}
906 mkAssertErrorExpr :: RnM (HsExpr Name, FreeVars)
907 -- Return an expression for (assertError "Foo.hs:27")
908 mkAssertErrorExpr
909   = getSrcSpanM                         `thenM` \ sloc ->
910     let
911         expr = HsApp (L sloc (HsVar assertErrorName)) (L sloc (HsLit msg))
912         msg  = HsStringPrim (mkFastString (stringToUtf8 (showSDoc (ppr sloc))))
913     in
914     returnM (expr, emptyFVs)
915 \end{code}
916
917 %************************************************************************
918 %*                                                                      *
919 \subsubsection{Errors}
920 %*                                                                      *
921 %************************************************************************
922
923 \begin{code}
924 patSynErr e 
925   = sep [ptext SLIT("Pattern syntax in expression context:"),
926          nest 4 (ppr e)]
927
928 parStmtErr = addErr (ptext SLIT("Illegal parallel list comprehension: use -fglasgow-exts"))
929
930 badIpBinds what binds
931   = hang (ptext SLIT("Implicit-parameter bindings illegal in") <+> what)
932          2 (ppr binds)
933 \end{code}