[project @ 2003-10-09 11:58:39 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         rnMatch, rnGRHSs, rnExpr, rnExprs, rnStmts,
15         checkPrecMatch
16    ) where
17
18 #include "HsVersions.h"
19
20 import {-# SOURCE #-} RnSource  ( rnSrcDecls, rnBindsAndThen, rnBinds ) 
21
22 --      RnSource imports RnBinds.rnTopMonoBinds, RnExpr.rnExpr
23 --      RnBinds  imports RnExpr.rnMatch, etc
24 --      RnExpr   imports [boot] RnSource.rnSrcDecls, RnSource.rnBinds
25
26 import HsSyn
27 import RdrHsSyn
28 import RnHsSyn
29 import TcRnMonad
30 import RnEnv
31 import RdrName          ( plusGlobalRdrEnv )
32 import RnNames          ( importsFromLocalDecls )
33 import RnTypes          ( rnHsTypeFVs, rnPat, litFVs, rnOverLit, rnPatsAndThen,
34                           dupFieldErr, precParseErr, sectionPrecErr, patSigErr, checkTupSize )
35 import CmdLineOpts      ( DynFlag(..) )
36 import BasicTypes       ( Fixity(..), FixityDirection(..), negateFixity, compareFixity )
37 import PrelNames        ( hasKey, assertIdKey, assertErrorName,
38                           loopAName, choiceAName, appAName, arrAName, composeAName, firstAName,
39                           negateName, monadNames, mfixName )
40 import Name             ( Name, nameOccName )
41 import NameSet
42 import UnicodeUtil      ( stringToUtf8 )
43 import UniqFM           ( isNullUFM )
44 import UniqSet          ( emptyUniqSet )
45 import Util             ( isSingleton )
46 import List             ( unzip4 )
47 import ListSetOps       ( removeDups )
48 import Outputable
49 import SrcLoc           ( noSrcLoc )
50 import FastString
51 \end{code}
52
53
54 ************************************************************************
55 *                                                                       *
56 \subsection{Match}
57 *                                                                       *
58 ************************************************************************
59
60 \begin{code}
61 rnMatch :: HsMatchContext Name -> RdrNameMatch -> RnM (RenamedMatch, FreeVars)
62
63 rnMatch ctxt match@(Match pats maybe_rhs_sig grhss)
64   = addSrcLoc (getMatchLoc match)       $
65
66         -- Deal with the rhs type signature
67     bindPatSigTyVarsFV rhs_sig_tys      $ 
68     doptM Opt_GlasgowExts               `thenM` \ opt_GlasgowExts ->
69     (case maybe_rhs_sig of
70         Nothing -> returnM (Nothing, emptyFVs)
71         Just ty | opt_GlasgowExts -> rnHsTypeFVs doc_sig ty     `thenM` \ (ty', ty_fvs) ->
72                                      returnM (Just ty', ty_fvs)
73                 | otherwise       -> addErr (patSigErr ty)      `thenM_`
74                                      returnM (Nothing, emptyFVs)
75     )                                   `thenM` \ (maybe_rhs_sig', ty_fvs) ->
76
77         -- Now the main event
78     rnPatsAndThen ctxt True pats $ \ pats' ->
79     rnGRHSs ctxt grhss           `thenM` \ (grhss', grhss_fvs) ->
80
81     returnM (Match pats' maybe_rhs_sig' grhss', grhss_fvs `plusFV` ty_fvs)
82         -- The bindPatSigTyVarsFV and rnPatsAndThen will remove the bound FVs
83   where
84      rhs_sig_tys =  case maybe_rhs_sig of
85                         Nothing -> []
86                         Just ty -> [ty]
87      doc_sig = text "In a result type-signature"
88 \end{code}
89
90
91 %************************************************************************
92 %*                                                                      *
93 \subsubsection{Guarded right-hand sides (GRHSs)}
94 %*                                                                      *
95 %************************************************************************
96
97 \begin{code}
98 rnGRHSs :: HsMatchContext Name -> RdrNameGRHSs -> RnM (RenamedGRHSs, FreeVars)
99
100 rnGRHSs ctxt (GRHSs grhss binds _)
101   = rnBindsAndThen binds        $ \ binds' ->
102     mapFvRn (rnGRHS ctxt) grhss `thenM` \ (grhss', fvGRHSs) ->
103     returnM (GRHSs grhss' binds' placeHolderType, fvGRHSs)
104
105 rnGRHS ctxt (GRHS guarded locn)
106   = addSrcLoc locn $                
107     doptM Opt_GlasgowExts               `thenM` \ opt_GlasgowExts ->
108     checkM (opt_GlasgowExts || is_standard_guard guarded)
109            (addWarn (nonStdGuardErr guarded))   `thenM_` 
110
111     rnStmts (PatGuard ctxt) guarded     `thenM` \ (guarded', fvs) ->
112     returnM (GRHS guarded' locn, fvs)
113   where
114         -- Standard Haskell 1.4 guards are just a single boolean
115         -- expression, rather than a list of qualifiers as in the
116         -- Glasgow extension
117     is_standard_guard [ResultStmt _ _]                 = True
118     is_standard_guard [ExprStmt _ _ _, ResultStmt _ _] = True
119     is_standard_guard other                            = False
120 \end{code}
121
122 %************************************************************************
123 %*                                                                      *
124 \subsubsection{Expressions}
125 %*                                                                      *
126 %************************************************************************
127
128 \begin{code}
129 rnExprs :: [RdrNameHsExpr] -> RnM ([RenamedHsExpr], FreeVars)
130 rnExprs ls = rnExprs' ls emptyUniqSet
131  where
132   rnExprs' [] acc = returnM ([], acc)
133   rnExprs' (expr:exprs) acc
134    = rnExpr expr                `thenM` \ (expr', fvExpr) ->
135
136         -- Now we do a "seq" on the free vars because typically it's small
137         -- or empty, especially in very long lists of constants
138     let
139         acc' = acc `plusFV` fvExpr
140     in
141     (grubby_seqNameSet acc' rnExprs') exprs acc'        `thenM` \ (exprs', fvExprs) ->
142     returnM (expr':exprs', fvExprs)
143
144 -- Grubby little function to do "seq" on namesets; replace by proper seq when GHC can do seq
145 grubby_seqNameSet ns result | isNullUFM ns = result
146                             | otherwise    = result
147 \end{code}
148
149 Variables. We look up the variable and return the resulting name. 
150
151 \begin{code}
152 rnExpr :: RdrNameHsExpr -> RnM (RenamedHsExpr, FreeVars)
153
154 rnExpr (HsVar v)
155   = lookupOccRn v       `thenM` \ name ->
156     doptM Opt_IgnoreAsserts `thenM` \ ignore_asserts ->
157     if name `hasKey` assertIdKey && not ignore_asserts then
158         -- We expand it to (GHC.Err.assertError location_string)
159         mkAssertErrorExpr       `thenM` \ (e, fvs) ->
160         returnM (e, fvs `addOneFV` name)
161                 -- Keep 'assert' as a free var, to ensure it's not reported as unused!
162     else
163         -- The normal case.  Even if the Id was 'assert', if we are 
164         -- ignoring assertions we leave it as GHC.Base.assert; 
165         -- this function just ignores its first arg.
166        returnM (HsVar name, unitFV name)
167
168 rnExpr (HsIPVar v)
169   = newIPNameRn v               `thenM` \ name ->
170     returnM (HsIPVar name, emptyFVs)
171
172 rnExpr (HsLit lit) 
173   = litFVs lit          `thenM` \ fvs -> 
174     returnM (HsLit lit, fvs)
175
176 rnExpr (HsOverLit lit) 
177   = rnOverLit lit               `thenM` \ (lit', fvs) ->
178     returnM (HsOverLit lit', fvs)
179
180 rnExpr (HsLam match)
181   = rnMatch LambdaExpr match    `thenM` \ (match', fvMatch) ->
182     returnM (HsLam match', fvMatch)
183
184 rnExpr (HsApp fun arg)
185   = rnExpr fun          `thenM` \ (fun',fvFun) ->
186     rnExpr arg          `thenM` \ (arg',fvArg) ->
187     returnM (HsApp fun' arg', fvFun `plusFV` fvArg)
188
189 rnExpr (OpApp e1 op _ e2) 
190   = rnExpr e1                           `thenM` \ (e1', fv_e1) ->
191     rnExpr e2                           `thenM` \ (e2', fv_e2) ->
192     rnExpr op                           `thenM` \ (op'@(HsVar op_name), fv_op) ->
193
194         -- Deal with fixity
195         -- When renaming code synthesised from "deriving" declarations
196         -- we used to avoid fixity stuff, but we can't easily tell any
197         -- more, so I've removed the test.  Adding HsPars in TcGenDeriv
198         -- should prevent bad things happening.
199     lookupFixityRn op_name              `thenM` \ fixity ->
200     mkOpAppRn e1' op' fixity e2'        `thenM` \ final_e -> 
201
202     returnM (final_e,
203               fv_e1 `plusFV` fv_op `plusFV` fv_e2)
204
205 rnExpr (NegApp e _)
206   = rnExpr e                    `thenM` \ (e', fv_e) ->
207     lookupSyntaxName negateName `thenM` \ (neg_name, fv_neg) ->
208     mkNegAppRn e' neg_name      `thenM` \ final_e ->
209     returnM (final_e, fv_e `plusFV` fv_neg)
210
211 rnExpr (HsPar e)
212   = rnExpr e            `thenM` \ (e', fvs_e) ->
213     returnM (HsPar e', fvs_e)
214
215 -- Template Haskell extensions
216 -- Don't ifdef-GHCI them because we want to fail gracefully
217 -- (not with an rnExpr crash) in a stage-1 compiler.
218 rnExpr e@(HsBracket br_body loc)
219   = addSrcLoc loc               $
220     checkTH e "bracket"         `thenM_`
221     rnBracket br_body           `thenM` \ (body', fvs_e) ->
222     returnM (HsBracket body' loc, fvs_e)
223
224 rnExpr e@(HsSplice n splice loc)
225   = addSrcLoc loc               $
226     checkTH e "splice"          `thenM_`
227     newLocalsRn [(n,loc)]       `thenM` \ [n'] ->
228     rnExpr splice               `thenM` \ (splice', fvs_e) ->
229     returnM (HsSplice n' splice' loc, fvs_e)
230
231 rnExpr e@(HsReify (Reify flavour name))
232   = checkTH e "reify"           `thenM_`
233     lookupGlobalOccRn name      `thenM` \ name' ->
234         -- For now, we can only reify top-level things
235     returnM (HsReify (Reify flavour name'), unitFV name')
236
237 rnExpr section@(SectionL expr op)
238   = rnExpr expr                                 `thenM` \ (expr', fvs_expr) ->
239     rnExpr op                                   `thenM` \ (op', fvs_op) ->
240     checkSectionPrec InfixL section op' expr' `thenM_`
241     returnM (SectionL expr' op', fvs_op `plusFV` fvs_expr)
242
243 rnExpr section@(SectionR op expr)
244   = rnExpr op                                   `thenM` \ (op',   fvs_op) ->
245     rnExpr expr                                 `thenM` \ (expr', fvs_expr) ->
246     checkSectionPrec InfixR section op' expr'   `thenM_`
247     returnM (SectionR op' expr', fvs_op `plusFV` fvs_expr)
248
249 rnExpr (HsCoreAnn ann expr)
250   = rnExpr expr `thenM` \ (expr', fvs_expr) ->
251     returnM (HsCoreAnn ann expr', fvs_expr)
252
253 rnExpr (HsSCC lbl expr)
254   = rnExpr expr         `thenM` \ (expr', fvs_expr) ->
255     returnM (HsSCC lbl expr', fvs_expr)
256
257 rnExpr (HsCase expr ms src_loc)
258   = addSrcLoc src_loc $
259     rnExpr expr                         `thenM` \ (new_expr, e_fvs) ->
260     mapFvRn (rnMatch CaseAlt) ms        `thenM` \ (new_ms, ms_fvs) ->
261     returnM (HsCase new_expr new_ms src_loc, e_fvs `plusFV` ms_fvs)
262
263 rnExpr (HsLet binds expr)
264   = rnBindsAndThen binds        $ \ binds' ->
265     rnExpr expr                  `thenM` \ (expr',fvExpr) ->
266     returnM (HsLet binds' expr', fvExpr)
267
268 rnExpr e@(HsDo do_or_lc stmts _ _ src_loc)
269   = addSrcLoc src_loc $
270     rnStmts do_or_lc stmts              `thenM` \ (stmts', fvs) ->
271
272         -- Check the statement list ends in an expression
273     case last stmts' of {
274         ResultStmt _ _ -> returnM () ;
275         _              -> addErr (doStmtListErr do_or_lc e)
276     }                                   `thenM_`
277
278         -- Generate the rebindable syntax for the monad
279     lookupSyntaxNames syntax_names      `thenM` \ (syntax_names', monad_fvs) ->
280
281     returnM (HsDo do_or_lc stmts' syntax_names' placeHolderType src_loc, 
282              fvs `plusFV` monad_fvs)
283   where
284     syntax_names = case do_or_lc of
285                         DoExpr  -> monadNames
286                         MDoExpr -> monadNames ++ [mfixName]
287                         other   -> []
288
289 rnExpr (ExplicitList _ exps)
290   = rnExprs exps                        `thenM` \ (exps', fvs) ->
291     returnM  (ExplicitList placeHolderType exps', fvs `addOneFV` listTyCon_name)
292
293 rnExpr (ExplicitPArr _ exps)
294   = rnExprs exps                        `thenM` \ (exps', fvs) ->
295     returnM  (ExplicitPArr placeHolderType exps', fvs)
296
297 rnExpr e@(ExplicitTuple exps boxity)
298   = checkTupSize tup_size                       `thenM_`
299     rnExprs exps                                `thenM` \ (exps', fvs) ->
300     returnM (ExplicitTuple exps' boxity, fvs `addOneFV` tycon_name)
301   where
302     tup_size   = length exps
303     tycon_name = tupleTyCon_name boxity tup_size
304
305 rnExpr (RecordCon con_id rbinds)
306   = lookupOccRn con_id                  `thenM` \ conname ->
307     rnRbinds "construction" rbinds      `thenM` \ (rbinds', fvRbinds) ->
308     returnM (RecordCon conname rbinds', fvRbinds `addOneFV` conname)
309
310 rnExpr (RecordUpd expr rbinds)
311   = rnExpr expr                 `thenM` \ (expr', fvExpr) ->
312     rnRbinds "update" rbinds    `thenM` \ (rbinds', fvRbinds) ->
313     returnM (RecordUpd expr' rbinds', fvExpr `plusFV` fvRbinds)
314
315 rnExpr (ExprWithTySig expr pty)
316   = rnExpr expr                 `thenM` \ (expr', fvExpr) ->
317     rnHsTypeFVs doc pty         `thenM` \ (pty', fvTy) ->
318     returnM (ExprWithTySig expr' pty', fvExpr `plusFV` fvTy)
319   where 
320     doc = text "In an expression type signature"
321
322 rnExpr (HsIf p b1 b2 src_loc)
323   = addSrcLoc src_loc $
324     rnExpr p            `thenM` \ (p', fvP) ->
325     rnExpr b1           `thenM` \ (b1', fvB1) ->
326     rnExpr b2           `thenM` \ (b2', fvB2) ->
327     returnM (HsIf p' b1' b2' src_loc, plusFVs [fvP, fvB1, fvB2])
328
329 rnExpr (HsType a)
330   = rnHsTypeFVs doc a   `thenM` \ (t, fvT) -> 
331     returnM (HsType t, fvT)
332   where 
333     doc = text "In a type argument"
334
335 rnExpr (ArithSeqIn seq)
336   = rnArithSeq seq       `thenM` \ (new_seq, fvs) ->
337     returnM (ArithSeqIn new_seq, fvs)
338
339 rnExpr (PArrSeqIn seq)
340   = rnArithSeq seq       `thenM` \ (new_seq, fvs) ->
341     returnM (PArrSeqIn new_seq, fvs)
342 \end{code}
343
344 These three are pattern syntax appearing in expressions.
345 Since all the symbols are reservedops we can simply reject them.
346 We return a (bogus) EWildPat in each case.
347
348 \begin{code}
349 rnExpr e@EWildPat = addErr (patSynErr e)        `thenM_`
350                     returnM (EWildPat, emptyFVs)
351
352 rnExpr e@(EAsPat _ _) = addErr (patSynErr e)    `thenM_`
353                         returnM (EWildPat, emptyFVs)
354
355 rnExpr e@(ELazyPat _) = addErr (patSynErr e)    `thenM_`
356                         returnM (EWildPat, emptyFVs)
357 \end{code}
358
359 %************************************************************************
360 %*                                                                      *
361         Arrow notation
362 %*                                                                      *
363 %************************************************************************
364
365 \begin{code}
366 rnExpr (HsProc pat body src_loc)
367   = addSrcLoc src_loc $
368     rnPatsAndThen ProcExpr True [pat] $ \ [pat'] ->
369     rnCmdTop body                     `thenM` \ (body',fvBody) ->
370     returnM (HsProc pat' body' src_loc, fvBody)
371
372 rnExpr (HsArrApp arrow arg _ ho rtl srcloc)
373   = rnExpr arrow        `thenM` \ (arrow',fvArrow) ->
374     rnExpr arg          `thenM` \ (arg',fvArg) ->
375     returnM (HsArrApp arrow' arg' placeHolderType ho rtl srcloc,
376              fvArrow `plusFV` fvArg)
377
378 -- infix form
379 rnExpr (HsArrForm op (Just _) [arg1, arg2] srcloc)
380   = rnExpr op           `thenM` \ (op'@(HsVar op_name),fv_op) ->
381     rnCmdTop arg1       `thenM` \ (arg1',fv_arg1) ->
382     rnCmdTop arg2       `thenM` \ (arg2',fv_arg2) ->
383
384         -- Deal with fixity
385
386     lookupFixityRn op_name              `thenM` \ fixity ->
387     mkOpFormRn arg1' op' fixity arg2'   `thenM` \ final_e -> 
388
389     returnM (final_e,
390               fv_arg1 `plusFV` fv_op `plusFV` fv_arg2)
391
392 rnExpr (HsArrForm op fixity cmds srcloc)
393   = rnExpr op           `thenM` \ (op',fvOp) ->
394     rnCmdArgs cmds      `thenM` \ (cmds',fvCmds) ->
395     returnM (HsArrForm op' fixity cmds' srcloc,
396              fvOp `plusFV` fvCmds)
397
398 ---------------------------
399 -- Deal with fixity (cf mkOpAppRn for the method)
400
401 mkOpFormRn :: RenamedHsCmdTop           -- Left operand; already rearranged
402           -> RenamedHsExpr -> Fixity    -- Operator and fixity
403           -> RenamedHsCmdTop            -- Right operand (not an infix)
404           -> RnM RenamedHsCmd
405
406 ---------------------------
407 -- (e11 `op1` e12) `op2` e2
408 mkOpFormRn a1@(HsCmdTop (HsArrForm op1 (Just fix1) [a11,a12] loc1) _ _ _) op2 fix2 a2
409   | nofix_error
410   = addErr (precParseErr (ppr_op op1,fix1) (ppr_op op2,fix2))   `thenM_`
411     returnM (HsArrForm op2 (Just fix2) [a1, a2] loc1)
412
413   | associate_right
414   = mkOpFormRn a12 op2 fix2 a2          `thenM` \ new_c ->
415     returnM (HsArrForm op1 (Just fix1)
416         [a11, HsCmdTop new_c [] placeHolderType []] loc1)
417   where
418     (nofix_error, associate_right) = compareFixity fix1 fix2
419
420 ---------------------------
421 --      Default case
422 mkOpFormRn arg1 op fix arg2                     -- Default case, no rearrangment
423   = returnM (HsArrForm op (Just fix) [arg1, arg2] noSrcLoc)
424
425 \end{code}
426
427
428 %************************************************************************
429 %*                                                                      *
430         Arrow commands
431 %*                                                                      *
432 %************************************************************************
433
434 \begin{code}
435 rnCmdArgs [] = returnM ([], emptyFVs)
436 rnCmdArgs (arg:args)
437   = rnCmdTop arg        `thenM` \ (arg',fvArg) ->
438     rnCmdArgs args      `thenM` \ (args',fvArgs) ->
439     returnM (arg':args', fvArg `plusFV` fvArgs)
440
441 rnCmdTop (HsCmdTop cmd _ _ _) 
442   = rnExpr (convertOpFormsCmd cmd)      `thenM` \ (cmd', fvCmd) ->
443     let 
444         cmd_names = [arrAName, composeAName, firstAName] ++
445                     nameSetToList (methodNamesCmd cmd')
446     in
447         -- Generate the rebindable syntax for the monad
448     lookupSyntaxNames cmd_names         `thenM` \ (cmd_names', cmd_fvs) ->
449
450     returnM (HsCmdTop cmd' [] placeHolderType cmd_names', 
451              fvCmd `plusFV` cmd_fvs)
452
453 ---------------------------------------------------
454 -- convert OpApp's in a command context to HsArrForm's
455
456 convertOpFormsCmd :: HsCmd id -> HsCmd id
457
458 convertOpFormsCmd (HsApp c e) = HsApp (convertOpFormsCmd c) e
459
460 convertOpFormsCmd (HsLam match) = HsLam (convertOpFormsMatch match)
461
462 convertOpFormsCmd (OpApp c1 op fixity c2)
463   = let
464         arg1 = HsCmdTop (convertOpFormsCmd c1) [] placeHolderType []
465         arg2 = HsCmdTop (convertOpFormsCmd c2) [] placeHolderType []
466     in
467     HsArrForm op (Just fixity) [arg1, arg2] noSrcLoc
468
469 convertOpFormsCmd (HsPar c) = HsPar (convertOpFormsCmd c)
470
471 convertOpFormsCmd (HsCase exp matches locn)
472   = HsCase exp (map convertOpFormsMatch matches) locn
473
474 convertOpFormsCmd (HsIf exp c1 c2 locn)
475   = HsIf exp (convertOpFormsCmd c1) (convertOpFormsCmd c2) locn
476
477 convertOpFormsCmd (HsLet binds cmd)
478   = HsLet binds (convertOpFormsCmd cmd)
479
480 convertOpFormsCmd (HsDo ctxt stmts ids ty locn)
481   = HsDo ctxt (map convertOpFormsStmt stmts) ids ty locn
482
483 -- Anything else is unchanged.  This includes HsArrForm (already done),
484 -- things with no sub-commands, and illegal commands (which will be
485 -- caught by the type checker)
486 convertOpFormsCmd c = c
487
488 convertOpFormsStmt (BindStmt pat cmd locn)
489   = BindStmt pat (convertOpFormsCmd cmd) locn
490 convertOpFormsStmt (ResultStmt cmd locn)
491   = ResultStmt (convertOpFormsCmd cmd) locn
492 convertOpFormsStmt (ExprStmt cmd ty locn)
493   = ExprStmt (convertOpFormsCmd cmd) ty locn
494 convertOpFormsStmt (RecStmt stmts lvs rvs es)
495   = RecStmt (map convertOpFormsStmt stmts) lvs rvs es
496 convertOpFormsStmt stmt = stmt
497
498 convertOpFormsMatch (Match pat mty grhss)
499   = Match pat mty (convertOpFormsGRHSs grhss)
500
501 convertOpFormsGRHSs (GRHSs grhss binds ty)
502   = GRHSs (map convertOpFormsGRHS grhss) binds ty
503
504 convertOpFormsGRHS (GRHS stmts locn)
505   = let
506         (ResultStmt cmd locn') = last stmts
507     in
508     GRHS (init stmts ++ [ResultStmt (convertOpFormsCmd cmd) locn']) locn
509
510 ---------------------------------------------------
511 type CmdNeeds = FreeVars        -- Only inhabitants are 
512                                 --      appAName, choiceAName, loopAName
513
514 -- find what methods the Cmd needs (loop, choice, apply)
515 methodNamesCmd :: HsCmd Name -> CmdNeeds
516
517 methodNamesCmd cmd@(HsArrApp _arrow _arg _ HsFirstOrderApp _rtl _srcloc)
518   = emptyFVs
519 methodNamesCmd cmd@(HsArrApp _arrow _arg _ HsHigherOrderApp _rtl _srcloc)
520   = unitFV appAName
521 methodNamesCmd cmd@(HsArrForm {}) = emptyFVs
522
523 methodNamesCmd (HsPar c) = methodNamesCmd c
524
525 methodNamesCmd (HsIf p c1 c2 loc)
526   = methodNamesCmd c1 `plusFV` methodNamesCmd c2 `addOneFV` choiceAName
527
528 methodNamesCmd (HsLet b c) = methodNamesCmd c
529
530 methodNamesCmd (HsDo sc stmts rbs ty loc) = methodNamesStmts stmts
531
532 methodNamesCmd (HsApp c e) = methodNamesCmd c
533
534 methodNamesCmd (HsLam match) = methodNamesMatch match
535
536 methodNamesCmd (HsCase scrut matches loc)
537   = plusFVs (map methodNamesMatch matches) `addOneFV` choiceAName
538
539 methodNamesCmd other = emptyFVs
540    -- Other forms can't occur in commands, but it's not convenient 
541    -- to error here so we just do what's convenient.
542    -- The type checker will complain later
543
544 ---------------------------------------------------
545 methodNamesMatch (Match pats sig_ty grhss) = methodNamesGRHSs grhss
546
547 -------------------------------------------------
548 methodNamesGRHSs (GRHSs grhss binds ty) = plusFVs (map methodNamesGRHS grhss)
549
550 -------------------------------------------------
551 methodNamesGRHS (GRHS stmts loc) = methodNamesStmt (last stmts)
552
553 ---------------------------------------------------
554 methodNamesStmts stmts = plusFVs (map methodNamesStmt stmts)
555
556 ---------------------------------------------------
557 methodNamesStmt (ResultStmt cmd loc) = methodNamesCmd cmd
558 methodNamesStmt (ExprStmt cmd ty loc) = methodNamesCmd cmd
559 methodNamesStmt (BindStmt pat cmd loc) = methodNamesCmd cmd
560 methodNamesStmt (RecStmt stmts lvs rvs es)
561   = methodNamesStmts stmts `addOneFV` loopAName
562 methodNamesStmt (LetStmt b)  = emptyFVs
563 methodNamesStmt (ParStmt ss) = emptyFVs
564    -- ParStmt can't occur in commands, but it's not convenient to error 
565    -- here so we just do what's convenient
566 \end{code}
567
568
569 %************************************************************************
570 %*                                                                      *
571         Arithmetic sequences
572 %*                                                                      *
573 %************************************************************************
574
575 \begin{code}
576 rnArithSeq (From expr)
577  = rnExpr expr  `thenM` \ (expr', fvExpr) ->
578    returnM (From expr', fvExpr)
579
580 rnArithSeq (FromThen expr1 expr2)
581  = rnExpr expr1         `thenM` \ (expr1', fvExpr1) ->
582    rnExpr expr2 `thenM` \ (expr2', fvExpr2) ->
583    returnM (FromThen expr1' expr2', fvExpr1 `plusFV` fvExpr2)
584
585 rnArithSeq (FromTo expr1 expr2)
586  = rnExpr expr1 `thenM` \ (expr1', fvExpr1) ->
587    rnExpr expr2 `thenM` \ (expr2', fvExpr2) ->
588    returnM (FromTo expr1' expr2', fvExpr1 `plusFV` fvExpr2)
589
590 rnArithSeq (FromThenTo expr1 expr2 expr3)
591  = rnExpr expr1 `thenM` \ (expr1', fvExpr1) ->
592    rnExpr expr2 `thenM` \ (expr2', fvExpr2) ->
593    rnExpr expr3 `thenM` \ (expr3', fvExpr3) ->
594    returnM (FromThenTo expr1' expr2' expr3',
595             plusFVs [fvExpr1, fvExpr2, fvExpr3])
596 \end{code}
597
598
599 %************************************************************************
600 %*                                                                      *
601 \subsubsection{@Rbinds@s and @Rpats@s: in record expressions}
602 %*                                                                      *
603 %************************************************************************
604
605 \begin{code}
606 rnRbinds str rbinds 
607   = mappM_ field_dup_err dup_fields     `thenM_`
608     mapFvRn rn_rbind rbinds             `thenM` \ (rbinds', fvRbind) ->
609     returnM (rbinds', fvRbind)
610   where
611     (_, dup_fields) = removeDups compare [ f | (f,_) <- rbinds ]
612
613     field_dup_err dups = addErr (dupFieldErr str dups)
614
615     rn_rbind (field, expr)
616       = lookupGlobalOccRn field `thenM` \ fieldname ->
617         rnExpr expr             `thenM` \ (expr', fvExpr) ->
618         returnM ((fieldname, expr'), fvExpr `addOneFV` fieldname)
619 \end{code}
620
621 %************************************************************************
622 %*                                                                      *
623         Template Haskell brackets
624 %*                                                                      *
625 %************************************************************************
626
627 \begin{code}
628 rnBracket (ExpBr e) = rnExpr e          `thenM` \ (e', fvs) ->
629                       returnM (ExpBr e', fvs)
630 rnBracket (PatBr p) = rnPat p           `thenM` \ (p', fvs) ->
631                       returnM (PatBr p', fvs)
632 rnBracket (TypBr t) = rnHsTypeFVs doc t `thenM` \ (t', fvs) ->
633                       returnM (TypBr t', fvs)
634                     where
635                       doc = ptext SLIT("In a Template-Haskell quoted type")
636 rnBracket (DecBr group) 
637   = importsFromLocalDecls group `thenM` \ (rdr_env, avails) ->
638         -- Discard avails (not useful here)
639
640     updGblEnv (\gbl -> gbl { tcg_rdr_env = rdr_env `plusGlobalRdrEnv` tcg_rdr_env gbl }) $
641
642     rnSrcDecls group    `thenM` \ (tcg_env, group', dus) ->
643         -- Discard the tcg_env; it contains only extra info about fixity
644
645     returnM (DecBr group', duUses dus `minusNameSet` duDefs dus)
646 \end{code}
647
648 %************************************************************************
649 %*                                                                      *
650 \subsubsection{@Stmt@s: in @do@ expressions}
651 %*                                                                      *
652 %************************************************************************
653
654 \begin{code}
655 rnStmts :: HsStmtContext Name -> [RdrNameStmt] -> RnM ([RenamedStmt], FreeVars)
656
657 rnStmts MDoExpr stmts = rnMDoStmts         stmts
658 rnStmts ctxt   stmts  = rnNormalStmts ctxt stmts
659
660 rnNormalStmts :: HsStmtContext Name -> [RdrNameStmt] -> RnM ([RenamedStmt], FreeVars)   
661 -- Used for cases *other* than recursive mdo
662 -- Implements nested scopes
663
664 rnNormalStmts ctxt [] = returnM ([], emptyFVs)
665         -- Happens at the end of the sub-lists of a ParStmts
666
667 rnNormalStmts ctxt (ExprStmt expr _ src_loc : stmts)
668   = addSrcLoc src_loc           $
669     rnExpr expr                 `thenM` \ (expr', fv_expr) ->
670     rnNormalStmts ctxt stmts    `thenM` \ (stmts', fvs) ->
671     returnM (ExprStmt expr' placeHolderType src_loc : stmts',
672              fv_expr `plusFV` fvs)
673
674 rnNormalStmts ctxt [ResultStmt expr src_loc]
675   = addSrcLoc src_loc   $
676     rnExpr expr         `thenM` \ (expr', fv_expr) ->
677     returnM ([ResultStmt expr' src_loc], fv_expr)
678
679 rnNormalStmts ctxt (BindStmt pat expr src_loc : stmts) 
680   = addSrcLoc src_loc                   $
681     rnExpr expr                         `thenM` \ (expr', fv_expr) ->
682         -- The binders do not scope over the expression
683
684     let
685      reportUnused = 
686        case ctxt of
687          ParStmtCtxt{} -> False
688          _ -> True
689     in
690     rnPatsAndThen (StmtCtxt ctxt) reportUnused [pat] $ \ [pat'] ->
691     rnNormalStmts ctxt stmts                         `thenM` \ (stmts', fvs) ->
692     returnM (BindStmt pat' expr' src_loc : stmts',
693              fv_expr `plusFV` fvs)      -- fv_expr shouldn't really be filtered by
694                                         -- the rnPatsAndThen, but it does not matter
695
696 rnNormalStmts ctxt (LetStmt binds : stmts)
697   = checkErr (ok ctxt binds) (badIpBinds binds) `thenM_`
698     rnBindsAndThen binds                        ( \ binds' ->
699     rnNormalStmts ctxt stmts                    `thenM` \ (stmts', fvs) ->
700     returnM (LetStmt binds' : stmts', fvs))
701   where
702         -- We do not allow implicit-parameter bindings in a parallel
703         -- list comprehension.  I'm not sure what it might mean.
704     ok (ParStmtCtxt _) (IPBinds _) = False      
705     ok _               _           = True
706
707 rnNormalStmts ctxt (ParStmt stmtss : stmts)
708   = doptM Opt_GlasgowExts               `thenM` \ opt_GlasgowExts ->
709     checkM opt_GlasgowExts parStmtErr   `thenM_`
710     mapFvRn rn_branch stmtss            `thenM` \ (stmtss', fv_stmtss) ->
711     let
712         bndrss :: [[Name]]      -- NB: Name, not RdrName
713         bndrss        = map collectStmtsBinders stmtss'
714         (bndrs, dups) = removeDups cmpByOcc (concat bndrss)
715     in
716     mappM dupErr dups                   `thenM` \ _ ->
717     bindLocalNamesFV bndrs              $
718         -- Note: binders are returned in scope order, so one may
719         --       shadow the next; e.g. x <- xs; x <- ys
720     rnNormalStmts ctxt stmts                    `thenM` \ (stmts', fvs) ->
721
722         -- Cut down the exported binders to just the ones needed in the body
723     let
724         used_bndrs_s = map (filter (`elemNameSet` fvs)) bndrss
725         unused_bndrs = filter (not . (`elemNameSet` fvs)) bndrs
726     in
727      -- With processing of the branches and the tail of comprehension done,
728      -- we can finally compute&report any unused ParStmt binders.
729     warnUnusedMatches unused_bndrs  `thenM_`
730     returnM (ParStmt (stmtss' `zip` used_bndrs_s) : stmts', 
731              fv_stmtss `plusFV` fvs)
732   where
733     rn_branch (stmts, _) = rnNormalStmts (ParStmtCtxt ctxt) stmts
734
735     cmpByOcc n1 n2 = nameOccName n1 `compare` nameOccName n2
736     dupErr (v:_) = addErr (ptext SLIT("Duplicate binding in parallel list comprehension for:")
737                             <+> quotes (ppr v))
738
739 rnNormalStmts ctxt (RecStmt rec_stmts _ _ _ : stmts)
740   = bindLocalsRn doc (collectStmtsBinders rec_stmts)    $ \ _ ->
741     rn_rec_stmts rec_stmts                              `thenM` \ segs ->
742     rnNormalStmts ctxt stmts                            `thenM` \ (stmts', fvs) ->
743     let
744         segs_w_fwd_refs          = addFwdRefs segs
745         (ds, us, fs, rec_stmts') = unzip4 segs_w_fwd_refs
746         later_vars = nameSetToList (plusFVs ds `intersectNameSet` fvs)
747         fwd_vars   = nameSetToList (plusFVs fs)
748         uses       = plusFVs us
749     in  
750     returnM (RecStmt rec_stmts' later_vars fwd_vars [] : stmts', uses `plusFV` fvs)
751   where
752     doc = text "In a recursive do statement"
753 \end{code}
754
755
756 %************************************************************************
757 %*                                                                      *
758 \subsubsection{mdo expressions}
759 %*                                                                      *
760 %************************************************************************
761
762 \begin{code}
763 type FwdRefs = NameSet
764 type Segment stmts = (Defs,
765                       Uses,     -- May include defs
766                       FwdRefs,  -- A subset of uses that are 
767                                 --   (a) used before they are bound in this segment, or 
768                                 --   (b) used here, and bound in subsequent segments
769                       stmts)    -- Either Stmt or [Stmt]
770
771
772 ----------------------------------------------------
773 rnMDoStmts :: [RdrNameStmt] -> RnM ([RenamedStmt], FreeVars)
774 rnMDoStmts stmts
775   =     -- Step1: bring all the binders of the mdo into scope
776         -- Remember that this also removes the binders from the
777         -- finally-returned free-vars
778     bindLocalsRn doc (collectStmtsBinders stmts)        $ \ _ ->
779         
780         -- Step 2: Rename each individual stmt, making a
781         --         singleton segment.  At this stage the FwdRefs field
782         --         isn't finished: it's empty for all except a BindStmt
783         --         for which it's the fwd refs within the bind itself
784         --         (This set may not be empty, because we're in a recursive 
785         --          context.)
786     rn_rec_stmts stmts                                  `thenM` \ segs ->
787     let
788         -- Step 3: Fill in the fwd refs.
789         --         The segments are all singletons, but their fwd-ref
790         --         field mentions all the things used by the segment
791         --         that are bound after their use
792         segs_w_fwd_refs = addFwdRefs segs
793
794         -- Step 4: Group together the segments to make bigger segments
795         --         Invariant: in the result, no segment uses a variable
796         --                    bound in a later segment
797         grouped_segs = glomSegments segs_w_fwd_refs
798
799         -- Step 5: Turn the segments into Stmts
800         --         Use RecStmt when and only when there are fwd refs
801         --         Also gather up the uses from the end towards the
802         --         start, so we can tell the RecStmt which things are
803         --         used 'after' the RecStmt
804         stmts_w_fvs = segsToStmts grouped_segs
805     in
806     returnM stmts_w_fvs
807   where
808     doc = text "In a mdo-expression"
809
810
811 ----------------------------------------------------
812 rn_rec_stmt :: RdrNameStmt -> RnM [Segment RenamedStmt]
813         -- Rename a Stmt that is inside a RecStmt (or mdo)
814         -- Assumes all binders are already in scope
815         -- Turns each stmt into a singleton Stmt
816
817 rn_rec_stmt (ExprStmt expr _ src_loc)
818   = addSrcLoc src_loc (rnExpr expr)     `thenM` \ (expr', fvs) ->
819     returnM [(emptyNameSet, fvs, emptyNameSet,
820               ExprStmt expr' placeHolderType src_loc)]
821
822 rn_rec_stmt (ResultStmt expr src_loc)
823   = addSrcLoc src_loc (rnExpr expr)     `thenM` \ (expr', fvs) ->
824     returnM [(emptyNameSet, fvs, emptyNameSet,
825               ResultStmt expr' src_loc)]
826
827 rn_rec_stmt (BindStmt pat expr src_loc)
828   = addSrcLoc src_loc   $
829     rnExpr expr         `thenM` \ (expr', fv_expr) ->
830     rnPat pat           `thenM` \ (pat', fv_pat) ->
831     let
832         bndrs = mkNameSet (collectPatBinders pat')
833         fvs   = fv_expr `plusFV` fv_pat
834     in
835     returnM [(bndrs, fvs, bndrs `intersectNameSet` fvs,
836               BindStmt pat' expr' src_loc)]
837
838 rn_rec_stmt (LetStmt binds)
839   = rnBinds binds               `thenM` \ (binds', du_binds) ->
840     returnM [(duDefs du_binds, duUses du_binds, 
841               emptyNameSet, LetStmt binds')]
842
843 rn_rec_stmt (RecStmt stmts _ _ _)       -- Flatten Rec inside Rec
844   = rn_rec_stmts stmts
845
846 rn_rec_stmt stmt@(ParStmt _)    -- Syntactically illegal in mdo
847   = pprPanic "rn_rec_stmt" (ppr stmt)
848
849 ---------------------------------------------
850 rn_rec_stmts :: [RdrNameStmt] -> RnM [Segment RenamedStmt]
851 rn_rec_stmts stmts = mappM rn_rec_stmt stmts    `thenM` \ segs_s ->
852                      returnM (concat segs_s)
853
854
855 ---------------------------------------------
856 addFwdRefs :: [Segment a] -> [Segment a]
857 -- So far the segments only have forward refs *within* the Stmt
858 --      (which happens for bind:  x <- ...x...)
859 -- This function adds the cross-seg fwd ref info
860
861 addFwdRefs pairs 
862   = fst (foldr mk_seg ([], emptyNameSet) pairs)
863   where
864     mk_seg (defs, uses, fwds, stmts) (segs, later_defs)
865         = (new_seg : segs, all_defs)
866         where
867           new_seg = (defs, uses, new_fwds, stmts)
868           all_defs = later_defs `unionNameSets` defs
869           new_fwds = fwds `unionNameSets` (uses `intersectNameSet` later_defs)
870                 -- Add the downstream fwd refs here
871
872 ----------------------------------------------------
873 --      Glomming the singleton segments of an mdo into 
874 --      minimal recursive groups.
875 --
876 -- At first I thought this was just strongly connected components, but
877 -- there's an important constraint: the order of the stmts must not change.
878 --
879 -- Consider
880 --      mdo { x <- ...y...
881 --            p <- z
882 --            y <- ...x...
883 --            q <- x
884 --            z <- y
885 --            r <- x }
886 --
887 -- Here, the first stmt mention 'y', which is bound in the third.  
888 -- But that means that the innocent second stmt (p <- z) gets caught
889 -- up in the recursion.  And that in turn means that the binding for
890 -- 'z' has to be included... and so on.
891 --
892 -- Start at the tail { r <- x }
893 -- Now add the next one { z <- y ; r <- x }
894 -- Now add one more     { q <- x ; z <- y ; r <- x }
895 -- Now one more... but this time we have to group a bunch into rec
896 --      { rec { y <- ...x... ; q <- x ; z <- y } ; r <- x }
897 -- Now one more, which we can add on without a rec
898 --      { p <- z ; 
899 --        rec { y <- ...x... ; q <- x ; z <- y } ; 
900 --        r <- x }
901 -- Finally we add the last one; since it mentions y we have to
902 -- glom it togeher with the first two groups
903 --      { rec { x <- ...y...; p <- z ; y <- ...x... ; 
904 --              q <- x ; z <- y } ; 
905 --        r <- x }
906
907 glomSegments :: [Segment RenamedStmt] -> [Segment [RenamedStmt]]
908
909 glomSegments [] = []
910 glomSegments ((defs,uses,fwds,stmt) : segs)
911         -- Actually stmts will always be a singleton
912   = (seg_defs, seg_uses, seg_fwds, seg_stmts)  : others
913   where
914     segs'            = glomSegments segs
915     (extras, others) = grab uses segs'
916     (ds, us, fs, ss) = unzip4 extras
917     
918     seg_defs  = plusFVs ds `plusFV` defs
919     seg_uses  = plusFVs us `plusFV` uses
920     seg_fwds  = plusFVs fs `plusFV` fwds
921     seg_stmts = stmt : concat ss
922
923     grab :: NameSet             -- The client
924          -> [Segment a]
925          -> ([Segment a],       -- Needed by the 'client'
926              [Segment a])       -- Not needed by the client
927         -- The result is simply a split of the input
928     grab uses dus 
929         = (reverse yeses, reverse noes)
930         where
931           (noes, yeses)           = span not_needed (reverse dus)
932           not_needed (defs,_,_,_) = not (intersectsNameSet defs uses)
933
934
935 ----------------------------------------------------
936 segsToStmts :: [Segment [RenamedStmt]] -> ([RenamedStmt], FreeVars)
937
938 segsToStmts [] = ([], emptyFVs)
939 segsToStmts ((defs, uses, fwds, ss) : segs)
940   = (new_stmt : later_stmts, later_uses `plusFV` uses)
941   where
942     (later_stmts, later_uses) = segsToStmts segs
943     new_stmt | non_rec   = head ss
944              | otherwise = RecStmt ss (nameSetToList used_later) (nameSetToList fwds) []
945              where
946                non_rec    = isSingleton ss && isEmptyNameSet fwds
947                used_later = defs `intersectNameSet` later_uses
948                                 -- The ones needed after the RecStmt
949 \end{code}
950
951 %************************************************************************
952 %*                                                                      *
953 \subsubsection{Precedence Parsing}
954 %*                                                                      *
955 %************************************************************************
956
957 @mkOpAppRn@ deals with operator fixities.  The argument expressions
958 are assumed to be already correctly arranged.  It needs the fixities
959 recorded in the OpApp nodes, because fixity info applies to the things
960 the programmer actually wrote, so you can't find it out from the Name.
961
962 Furthermore, the second argument is guaranteed not to be another
963 operator application.  Why? Because the parser parses all
964 operator appications left-associatively, EXCEPT negation, which
965 we need to handle specially.
966
967 \begin{code}
968 mkOpAppRn :: RenamedHsExpr                      -- Left operand; already rearranged
969           -> RenamedHsExpr -> Fixity            -- Operator and fixity
970           -> RenamedHsExpr                      -- Right operand (not an OpApp, but might
971                                                 -- be a NegApp)
972           -> RnM RenamedHsExpr
973
974 ---------------------------
975 -- (e11 `op1` e12) `op2` e2
976 mkOpAppRn e1@(OpApp e11 op1 fix1 e12) op2 fix2 e2
977   | nofix_error
978   = addErr (precParseErr (ppr_op op1,fix1) (ppr_op op2,fix2))   `thenM_`
979     returnM (OpApp e1 op2 fix2 e2)
980
981   | associate_right
982   = mkOpAppRn e12 op2 fix2 e2           `thenM` \ new_e ->
983     returnM (OpApp e11 op1 fix1 new_e)
984   where
985     (nofix_error, associate_right) = compareFixity fix1 fix2
986
987 ---------------------------
988 --      (- neg_arg) `op` e2
989 mkOpAppRn e1@(NegApp neg_arg neg_name) op2 fix2 e2
990   | nofix_error
991   = addErr (precParseErr (pp_prefix_minus,negateFixity) (ppr_op op2,fix2))      `thenM_`
992     returnM (OpApp e1 op2 fix2 e2)
993
994   | associate_right
995   = mkOpAppRn neg_arg op2 fix2 e2       `thenM` \ new_e ->
996     returnM (NegApp new_e neg_name)
997   where
998     (nofix_error, associate_right) = compareFixity negateFixity fix2
999
1000 ---------------------------
1001 --      e1 `op` - neg_arg
1002 mkOpAppRn e1 op1 fix1 e2@(NegApp neg_arg _)     -- NegApp can occur on the right
1003   | not associate_right                         -- We *want* right association
1004   = addErr (precParseErr (ppr_op op1, fix1) (pp_prefix_minus, negateFixity))    `thenM_`
1005     returnM (OpApp e1 op1 fix1 e2)
1006   where
1007     (_, associate_right) = compareFixity fix1 negateFixity
1008
1009 ---------------------------
1010 --      Default case
1011 mkOpAppRn e1 op fix e2                  -- Default case, no rearrangment
1012   = ASSERT2( right_op_ok fix e2,
1013              ppr e1 $$ text "---" $$ ppr op $$ text "---" $$ ppr fix $$ text "---" $$ ppr e2
1014     )
1015     returnM (OpApp e1 op fix e2)
1016
1017 -- Parser left-associates everything, but 
1018 -- derived instances may have correctly-associated things to
1019 -- in the right operarand.  So we just check that the right operand is OK
1020 right_op_ok fix1 (OpApp _ _ fix2 _)
1021   = not error_please && associate_right
1022   where
1023     (error_please, associate_right) = compareFixity fix1 fix2
1024 right_op_ok fix1 other
1025   = True
1026
1027 -- Parser initially makes negation bind more tightly than any other operator
1028 -- And "deriving" code should respect this (use HsPar if not)
1029 mkNegAppRn neg_arg neg_name
1030   = ASSERT( not_op_app neg_arg )
1031     returnM (NegApp neg_arg neg_name)
1032
1033 not_op_app (OpApp _ _ _ _) = False
1034 not_op_app other           = True
1035 \end{code}
1036
1037 \begin{code}
1038 checkPrecMatch :: Bool -> Name -> RenamedMatch -> RnM ()
1039
1040 checkPrecMatch False fn match
1041   = returnM ()
1042
1043 checkPrecMatch True op (Match (p1:p2:_) _ _)
1044         -- True indicates an infix lhs
1045   =     -- See comments with rnExpr (OpApp ...) about "deriving"
1046     checkPrec op p1 False       `thenM_`
1047     checkPrec op p2 True
1048
1049 checkPrecMatch True op _ = panic "checkPrecMatch"
1050
1051 checkPrec op (ConPatIn op1 (InfixCon _ _)) right
1052   = lookupFixityRn op   `thenM` \  op_fix@(Fixity op_prec  op_dir) ->
1053     lookupFixityRn op1  `thenM` \ op1_fix@(Fixity op1_prec op1_dir) ->
1054     let
1055         inf_ok = op1_prec > op_prec || 
1056                  (op1_prec == op_prec &&
1057                   (op1_dir == InfixR && op_dir == InfixR && right ||
1058                    op1_dir == InfixL && op_dir == InfixL && not right))
1059
1060         info  = (ppr_op op,  op_fix)
1061         info1 = (ppr_op op1, op1_fix)
1062         (infol, infor) = if right then (info, info1) else (info1, info)
1063     in
1064     checkErr inf_ok (precParseErr infol infor)
1065
1066 checkPrec op pat right
1067   = returnM ()
1068
1069 -- Check precedence of (arg op) or (op arg) respectively
1070 -- If arg is itself an operator application, then either
1071 --   (a) its precedence must be higher than that of op
1072 --   (b) its precedency & associativity must be the same as that of op
1073 checkSectionPrec direction section op arg
1074   = case arg of
1075         OpApp _ op fix _ -> go_for_it (ppr_op op)     fix
1076         NegApp _ _       -> go_for_it pp_prefix_minus negateFixity
1077         other            -> returnM ()
1078   where
1079     HsVar op_name = op
1080     go_for_it pp_arg_op arg_fix@(Fixity arg_prec assoc)
1081         = lookupFixityRn op_name        `thenM` \ op_fix@(Fixity op_prec _) ->
1082           checkErr (op_prec < arg_prec
1083                      || op_prec == arg_prec && direction == assoc)
1084                   (sectionPrecErr (ppr_op op_name, op_fix)      
1085                   (pp_arg_op, arg_fix) section)
1086 \end{code}
1087
1088
1089 %************************************************************************
1090 %*                                                                      *
1091 \subsubsection{Assertion utils}
1092 %*                                                                      *
1093 %************************************************************************
1094
1095 \begin{code}
1096 mkAssertErrorExpr :: RnM (RenamedHsExpr, FreeVars)
1097 -- Return an expression for (assertError "Foo.hs:27")
1098 mkAssertErrorExpr
1099   = getSrcLocM                          `thenM` \ sloc ->
1100     let
1101         expr = HsApp (HsVar assertErrorName) (HsLit msg)
1102         msg  = HsStringPrim (mkFastString (stringToUtf8 (showSDoc (ppr sloc))))
1103     in
1104     returnM (expr, emptyFVs)
1105 \end{code}
1106
1107 %************************************************************************
1108 %*                                                                      *
1109 \subsubsection{Errors}
1110 %*                                                                      *
1111 %************************************************************************
1112
1113 \begin{code}
1114 ppr_op op = quotes (ppr op)     -- Here, op can be a Name or a (Var n), where n is a Name
1115 pp_prefix_minus = ptext SLIT("prefix `-'")
1116
1117 nonStdGuardErr guard
1118   = hang (ptext
1119     SLIT("accepting non-standard pattern guards (-fglasgow-exts to suppress this message)")
1120     ) 4 (ppr guard)
1121
1122 patSynErr e 
1123   = sep [ptext SLIT("Pattern syntax in expression context:"),
1124          nest 4 (ppr e)]
1125
1126 doStmtListErr do_or_lc e
1127   = sep [quotes (text binder_name) <+> ptext SLIT("statements must end in expression:"),
1128          nest 4 (ppr e)]
1129   where
1130     binder_name = case do_or_lc of
1131                         MDoExpr -> "mdo"
1132                         other   -> "do"
1133
1134 #ifdef GHCI 
1135 checkTH e what = returnM ()     -- OK
1136 #else
1137 checkTH e what  -- Raise an error in a stage-1 compiler
1138   = addErr (vcat [ptext SLIT("Template Haskell") <+> text what <+>  
1139                   ptext SLIT("illegal in a stage-1 compiler"),
1140                   nest 2 (ppr e)])
1141 #endif   
1142
1143 parStmtErr = addErr (ptext SLIT("Illegal parallel list comprehension: use -fglasgow-exts"))
1144
1145 badIpBinds binds
1146   = hang (ptext SLIT("Implicit-parameter bindings illegal in a parallel list comprehension:")) 4
1147          (ppr binds)
1148 \end{code}