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