Fix warnings
[ghc-hetmet.git] / compiler / rename / RnEnv.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-2006
3 %
4 \section[RnEnv]{Environment manipulation for the renamer monad}
5
6 \begin{code}
7 module RnEnv ( 
8         newTopSrcBinder, lookupFamInstDeclBndr,
9         lookupLocatedTopBndrRn, lookupTopBndrRn,
10         lookupLocatedOccRn, lookupOccRn, 
11         lookupGlobalOccRn, lookupGlobalOccRn_maybe,
12         lookupLocalDataTcNames, lookupSigOccRn,
13         lookupFixityRn, lookupTyFixityRn, 
14         lookupInstDeclBndr, lookupSubBndr, lookupConstructorFields,
15         lookupSyntaxName, lookupSyntaxTable, lookupIfThenElse,
16         lookupGreRn, lookupGreLocalRn, lookupGreRn_maybe,
17         getLookupOccRn, addUsedRdrNames,
18
19         newLocalBndrRn, newLocalBndrsRn, newIPNameRn,
20         bindLocalName, bindLocalNames, bindLocalNamesFV, 
21         MiniFixityEnv, emptyFsEnv, extendFsEnv, lookupFsEnv,
22         addLocalFixities,
23         bindLocatedLocalsFV, bindLocatedLocalsRn,
24         bindSigTyVarsFV, bindPatSigTyVars, bindPatSigTyVarsFV,
25         bindTyVarsRn, bindTyVarsFV, extendTyVarEnvFVRn,
26
27         checkDupRdrNames, checkDupAndShadowedRdrNames,
28         checkDupNames, checkDupAndShadowedNames, 
29         addFvRn, mapFvRn, mapMaybeFvRn, mapFvRnCPS,
30         warnUnusedMatches,
31         warnUnusedTopBinds, warnUnusedLocalBinds,
32         dataTcOccs, unknownNameErr, kindSigErr, perhapsForallMsg
33     ) where
34
35 #include "HsVersions.h"
36
37 import LoadIface        ( loadInterfaceForName, loadSrcInterface )
38 import IfaceEnv         ( lookupOrig, newGlobalBinder, newIPName )
39 import HsSyn
40 import RdrHsSyn         ( extractHsTyRdrTyVars )
41 import RdrName
42 import HscTypes         ( availNames, ModIface(..), FixItem(..), lookupFixity)
43 import TcEnv            ( tcLookupDataCon, tcLookupField, isBrackStage )
44 import TcRnMonad
45 import Id               ( isRecordSelector )
46 import Name
47 import NameSet
48 import NameEnv
49 import Module           ( ModuleName, moduleName )
50 import UniqFM
51 import DataCon          ( dataConFieldLabels )
52 import PrelNames        ( mkUnboundName, rOOT_MAIN, consDataConKey, forall_tv_RDR )
53 import Unique
54 import BasicTypes
55 import ErrUtils         ( Message )
56 import SrcLoc
57 import Outputable
58 import Util
59 import Maybes
60 import ListSetOps       ( removeDups )
61 import DynFlags
62 import FastString
63 import Control.Monad
64 import Data.List
65 import qualified Data.Set as Set
66 \end{code}
67
68 \begin{code}
69 -- XXX
70 thenM :: Monad a => a b -> (b -> a c) -> a c
71 thenM = (>>=)
72 \end{code}
73
74 %*********************************************************
75 %*                                                      *
76                 Source-code binders
77 %*                                                      *
78 %*********************************************************
79
80 \begin{code}
81 newTopSrcBinder :: Located RdrName -> RnM Name
82 newTopSrcBinder (L loc rdr_name)
83   | Just name <- isExact_maybe rdr_name
84   =     -- This is here to catch 
85         --   (a) Exact-name binders created by Template Haskell
86         --   (b) The PrelBase defn of (say) [] and similar, for which
87         --       the parser reads the special syntax and returns an Exact RdrName
88         -- We are at a binding site for the name, so check first that it 
89         -- the current module is the correct one; otherwise GHC can get
90         -- very confused indeed. This test rejects code like
91         --      data T = (,) Int Int
92         -- unless we are in GHC.Tup
93     ASSERT2( isExternalName name,  ppr name )
94     do  { this_mod <- getModule
95         ; unless (this_mod == nameModule name)
96                  (addErrAt loc (badOrigBinding rdr_name))
97         ; return name }
98
99
100   | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
101   = do  { this_mod <- getModule
102         ; unless (rdr_mod == this_mod || rdr_mod == rOOT_MAIN)
103                  (addErrAt loc (badOrigBinding rdr_name))
104         -- When reading External Core we get Orig names as binders, 
105         -- but they should agree with the module gotten from the monad
106         --
107         -- We can get built-in syntax showing up here too, sadly.  If you type
108         --      data T = (,,,)
109         -- the constructor is parsed as a type, and then RdrHsSyn.tyConToDataCon 
110         -- uses setRdrNameSpace to make it into a data constructors.  At that point
111         -- the nice Exact name for the TyCon gets swizzled to an Orig name.
112         -- Hence the badOrigBinding error message.
113         --
114         -- Except for the ":Main.main = ..." definition inserted into 
115         -- the Main module; ugh!
116
117         -- Because of this latter case, we call newGlobalBinder with a module from 
118         -- the RdrName, not from the environment.  In principle, it'd be fine to 
119         -- have an arbitrary mixture of external core definitions in a single module,
120         -- (apart from module-initialisation issues, perhaps).
121         ; newGlobalBinder rdr_mod rdr_occ loc }
122                 --TODO, should pass the whole span
123
124   | otherwise
125   = do  { unless (not (isQual rdr_name))
126                  (addErrAt loc (badQualBndrErr rdr_name))
127                 -- Binders should not be qualified; if they are, and with a different
128                 -- module name, we we get a confusing "M.T is not in scope" error later
129
130         ; stage <- getStage
131         ; if isBrackStage stage then
132                 -- We are inside a TH bracket, so make an *Internal* name
133                 -- See Note [Top-level Names in Template Haskell decl quotes] in RnNames
134              do { uniq <- newUnique
135                 ; return (mkInternalName uniq (rdrNameOcc rdr_name) loc) } 
136           else  
137                 -- Normal case
138              do { this_mod <- getModule
139                 ; newGlobalBinder this_mod (rdrNameOcc rdr_name) loc } }
140 \end{code}
141
142 %*********************************************************
143 %*                                                      *
144         Source code occurrences
145 %*                                                      *
146 %*********************************************************
147
148 Looking up a name in the RnEnv.
149
150 Note [Type and class operator definitions]
151 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
152 We want to reject all of these unless we have -XTypeOperators (Trac #3265)
153    data a :*: b  = ...
154    class a :*: b where ...
155    data (:*:) a b  = ....
156    class (:*:) a b where ...
157 The latter two mean that we are not just looking for a
158 *syntactically-infix* declaration, but one that uses an operator
159 OccName.  We use OccName.isSymOcc to detect that case, which isn't
160 terribly efficient, but there seems to be no better way.
161
162 \begin{code}
163 lookupTopBndrRn :: RdrName -> RnM Name
164 lookupTopBndrRn n = do nopt <- lookupTopBndrRn_maybe n
165                        case nopt of 
166                          Just n' -> return n'
167                          Nothing -> do traceRn $ text "lookupTopBndrRn"
168                                        unboundName WL_LocalTop n
169
170 lookupLocatedTopBndrRn :: Located RdrName -> RnM (Located Name)
171 lookupLocatedTopBndrRn = wrapLocM lookupTopBndrRn
172
173 lookupTopBndrRn_maybe :: RdrName -> RnM (Maybe Name)
174 -- Look up a top-level source-code binder.   We may be looking up an unqualified 'f',
175 -- and there may be several imported 'f's too, which must not confuse us.
176 -- For example, this is OK:
177 --      import Foo( f )
178 --      infix 9 f       -- The 'f' here does not need to be qualified
179 --      f x = x         -- Nor here, of course
180 -- So we have to filter out the non-local ones.
181 --
182 -- A separate function (importsFromLocalDecls) reports duplicate top level
183 -- decls, so here it's safe just to choose an arbitrary one.
184 --
185 -- There should never be a qualified name in a binding position in Haskell,
186 -- but there can be if we have read in an external-Core file.
187 -- The Haskell parser checks for the illegal qualified name in Haskell 
188 -- source files, so we don't need to do so here.
189
190 lookupTopBndrRn_maybe rdr_name
191   | Just name <- isExact_maybe rdr_name
192   = return (Just name)
193
194   | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name    
195         -- This deals with the case of derived bindings, where
196         -- we don't bother to call newTopSrcBinder first
197         -- We assume there is no "parent" name
198   = do  { loc <- getSrcSpanM
199         ; n <- newGlobalBinder rdr_mod rdr_occ loc 
200         ; return (Just n)}
201
202   | otherwise
203   = do  {  -- Check for operators in type or class declarations
204            -- See Note [Type and class operator definitions]
205           let occ = rdrNameOcc rdr_name
206         ; when (isTcOcc occ && isSymOcc occ)
207                (do { op_ok <- xoptM Opt_TypeOperators
208                    ; unless op_ok (addErr (opDeclErr rdr_name)) })
209
210         ; mb_gre <- lookupGreLocalRn rdr_name
211         ; case mb_gre of
212                 Nothing  -> return Nothing
213                 Just gre -> return (Just $ gre_name gre) }
214               
215
216 -----------------------------------------------
217 lookupInstDeclBndr :: Name -> RdrName -> RnM Name
218 -- This is called on the method name on the left-hand side of an 
219 -- instance declaration binding. eg.  instance Functor T where
220 --                                       fmap = ...
221 --                                       ^^^^ called on this
222 -- Regardless of how many unqualified fmaps are in scope, we want
223 -- the one that comes from the Functor class.
224 --
225 -- Furthermore, note that we take no account of whether the 
226 -- name is only in scope qualified.  I.e. even if method op is
227 -- in scope as M.op, we still allow plain 'op' on the LHS of
228 -- an instance decl
229 lookupInstDeclBndr cls rdr
230   = do { when (isQual rdr)
231               (addErr (badQualBndrErr rdr)) 
232                 -- In an instance decl you aren't allowed
233                 -- to use a qualified name for the method
234                 -- (Although it'd make perfect sense.)
235        ; lookupSubBndr (ParentIs cls) doc rdr }
236   where
237     doc = ptext (sLit "method of class") <+> quotes (ppr cls)
238
239 -----------------------------------------------
240 lookupConstructorFields :: Name -> RnM [Name]
241 -- Look up the fields of a given constructor
242 --   *  For constructors from this module, use the record field env,
243 --      which is itself gathered from the (as yet un-typechecked)
244 --      data type decls
245 -- 
246 --    * For constructors from imported modules, use the *type* environment
247 --      since imported modles are already compiled, the info is conveniently
248 --      right there
249
250 lookupConstructorFields con_name
251   = do  { this_mod <- getModule
252         ; if nameIsLocalOrFrom this_mod con_name then
253           do { RecFields field_env _ <- getRecFieldEnv
254              ; return (lookupNameEnv field_env con_name `orElse` []) }
255           else 
256           do { con <- tcLookupDataCon con_name
257              ; return (dataConFieldLabels con) } }
258
259 -----------------------------------------------
260 -- Used for record construction and pattern matching
261 -- When the -XDisambiguateRecordFields flag is on, take account of the
262 -- constructor name to disambiguate which field to use; it's just the
263 -- same as for instance decls
264 -- 
265 -- NB: Consider this:
266 --      module Foo where { data R = R { fld :: Int } }
267 --      module Odd where { import Foo; fld x = x { fld = 3 } }
268 -- Arguably this should work, because the reference to 'fld' is
269 -- unambiguous because there is only one field id 'fld' in scope.
270 -- But currently it's rejected.
271
272 lookupSubBndr :: Parent  -- NoParent   => just look it up as usual
273                          -- ParentIs p => use p to disambiguate
274               -> SDoc -> RdrName 
275               -> RnM Name
276 lookupSubBndr parent doc rdr_name
277   | Just n <- isExact_maybe rdr_name   -- This happens in derived code
278   = return n
279
280   | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
281   = lookupOrig rdr_mod rdr_occ
282
283   | otherwise   -- Find all the things the rdr-name maps to
284   = do  {       -- and pick the one with the right parent name
285         ; env <- getGlobalRdrEnv
286         ; let gres = lookupGlobalRdrEnv env (rdrNameOcc rdr_name)
287         ; case pick parent gres  of
288                 -- NB: lookupGlobalRdrEnv, not lookupGRE_RdrName!
289                 --     The latter does pickGREs, but we want to allow 'x'
290                 --     even if only 'M.x' is in scope
291             [gre] -> do { addUsedRdrName gre (used_rdr_name gre)
292                         ; return (gre_name gre) }
293             []    -> do { addErr (unknownSubordinateErr doc rdr_name)
294                         ; traceRn (text "RnEnv.lookup_sub_bndr" <+> (ppr rdr_name $$ ppr gres))
295                         ; return (mkUnboundName rdr_name) }
296             gres  -> do { addNameClashErrRn rdr_name gres
297                         ; return (gre_name (head gres)) } }
298   where
299     rdr_occ = rdrNameOcc rdr_name    
300
301     pick NoParent gres          -- Normal lookup 
302       = pickGREs rdr_name gres
303     pick (ParentIs p) gres      -- Disambiguating lookup
304       | isUnqual rdr_name = filter (right_parent p) gres
305       | otherwise         = filter (right_parent p) (pickGREs rdr_name gres)
306
307     right_parent p (GRE { gre_par = ParentIs p' }) = p==p' 
308     right_parent _ _                               = False
309
310     -- Note [Usage for sub-bndrs]
311     used_rdr_name gre
312       | isQual rdr_name = rdr_name
313       | otherwise       = case gre_prov gre of
314                             LocalDef    -> rdr_name
315                             Imported is -> used_rdr_name_from_is is
316
317     used_rdr_name_from_is imp_specs     -- rdr_name is unqualified
318       | not (all (is_qual . is_decl) imp_specs) 
319       = rdr_name    -- An unqualified import is available
320       | otherwise
321       =             -- Only qualified imports available, so make up 
322                     -- a suitable qualifed name from the first imp_spec
323         ASSERT( not (null imp_specs) )
324         mkRdrQual (is_as (is_decl (head imp_specs))) rdr_occ
325
326 newIPNameRn :: IPName RdrName -> TcRnIf m n (IPName Name)
327 newIPNameRn ip_rdr = newIPName (mapIPName rdrNameOcc ip_rdr)
328
329 -- If the family is declared locally, it will not yet be in the main
330 -- environment; hence, we pass in an extra one here, which we check first.
331 -- See "Note [Looking up family names in family instances]" in 'RnNames'.
332 --
333 lookupFamInstDeclBndr :: GlobalRdrEnv -> Located RdrName -> RnM Name
334 lookupFamInstDeclBndr tyclGroupEnv (L loc rdr_name)
335   = setSrcSpan loc $
336       case lookupGRE_RdrName rdr_name tyclGroupEnv of
337         (gre:_) -> return $ gre_name gre
338           -- if there is more than one, an error will be raised elsewhere
339         []      -> lookupOccRn rdr_name
340 \end{code}
341
342 Note [Usage for sub-bndrs]
343 ~~~~~~~~~~~~~~~~~~~~~~~~~~
344 If you have this
345    import qualified M( C( f ) ) 
346    instance M.C T where
347      f x = x
348 then is the qualified import M.f used?  Obviously yes.
349 But the RdrName used in the instance decl is unqualified.  In effect,
350 we fill in the qualification by looking for f's whose class is M.C
351 But when adding to the UsedRdrNames we must make that qualification
352 explicit (saying "used  M.f"), otherwise we get "Redundant import of M.f".
353
354 So we make up a suitable (fake) RdrName.  But be careful
355    import qualifed M
356    import M( C(f) )
357    instance C T where
358      f x = x
359 Here we want to record a use of 'f', not of 'M.f', otherwise
360 we'll miss the fact that the qualified import is redundant.
361
362 --------------------------------------------------
363 --              Occurrences
364 --------------------------------------------------
365
366 \begin{code}
367 getLookupOccRn :: RnM (Name -> Maybe Name)
368 getLookupOccRn
369   = getLocalRdrEnv                      `thenM` \ local_env ->
370     return (lookupLocalRdrOcc local_env . nameOccName)
371
372 lookupLocatedOccRn :: Located RdrName -> RnM (Located Name)
373 lookupLocatedOccRn = wrapLocM lookupOccRn
374
375 -- lookupOccRn looks up an occurrence of a RdrName
376 lookupOccRn :: RdrName -> RnM Name
377 lookupOccRn rdr_name
378   = do { local_env <- getLocalRdrEnv
379        ; case lookupLocalRdrEnv local_env rdr_name of {
380           Just name -> return name ;
381           Nothing   -> do
382
383        { mb_name <- lookupGlobalOccRn_maybe rdr_name
384        ; case mb_name of {
385                 Just n  -> return n ;
386                 Nothing -> do
387
388        { -- We allow qualified names on the command line to refer to 
389          --  *any* name exported by any module in scope, just as if there
390          -- was an "import qualified M" declaration for every module.
391          allow_qual <- doptM Opt_ImplicitImportQualified
392        ; is_ghci <- getIsGHCi
393                -- This test is not expensive,
394                -- and only happens for failed lookups
395        ; if isQual rdr_name && allow_qual && is_ghci
396          then lookupQualifiedName rdr_name
397          else unboundName WL_Any rdr_name } } } } }
398
399
400 lookupGlobalOccRn :: RdrName -> RnM Name
401 -- lookupGlobalOccRn is like lookupOccRn, except that it looks in the global 
402 -- environment.  Adds an error message if the RdrName is not in scope.
403 lookupGlobalOccRn rdr_name
404   = do { mb_name <- lookupGlobalOccRn_maybe rdr_name
405        ; case mb_name of
406            Just n  -> return n
407            Nothing -> unboundName WL_Global rdr_name }
408
409 lookupGlobalOccRn_maybe :: RdrName -> RnM (Maybe Name)
410 -- No filter function; does not report an error on failure
411
412 lookupGlobalOccRn_maybe rdr_name
413   | Just n <- isExact_maybe rdr_name   -- This happens in derived code
414   = return (Just n)
415
416   | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
417   = do { n <- lookupOrig rdr_mod rdr_occ; return (Just n) }
418
419   | otherwise
420   = do  { mb_gre <- lookupGreRn_maybe rdr_name
421         ; case mb_gre of
422                 Nothing  -> return Nothing
423                 Just gre -> return (Just (gre_name gre)) }
424
425
426 --------------------------------------------------
427 --      Lookup in the Global RdrEnv of the module
428 --------------------------------------------------
429
430 lookupGreRn_maybe :: RdrName -> RnM (Maybe GlobalRdrElt)
431 -- Just look up the RdrName in the GlobalRdrEnv
432 lookupGreRn_maybe rdr_name 
433   = lookupGreRn_help rdr_name (lookupGRE_RdrName rdr_name)
434
435 lookupGreRn :: RdrName -> RnM GlobalRdrElt
436 -- If not found, add error message, and return a fake GRE
437 lookupGreRn rdr_name 
438   = do  { mb_gre <- lookupGreRn_maybe rdr_name
439         ; case mb_gre of {
440             Just gre -> return gre ;
441             Nothing  -> do
442         { traceRn $ text "lookupGreRn"
443         ; name <- unboundName WL_Global rdr_name
444         ; return (GRE { gre_name = name, gre_par = NoParent,
445                         gre_prov = LocalDef }) }}}
446
447 lookupGreLocalRn :: RdrName -> RnM (Maybe GlobalRdrElt)
448 -- Similar, but restricted to locally-defined things
449 lookupGreLocalRn rdr_name 
450   = lookupGreRn_help rdr_name lookup_fn
451   where
452     lookup_fn env = filter isLocalGRE (lookupGRE_RdrName rdr_name env)
453
454 lookupGreRn_help :: RdrName                     -- Only used in error message
455                  -> (GlobalRdrEnv -> [GlobalRdrElt])    -- Lookup function
456                  -> RnM (Maybe GlobalRdrElt)
457 -- Checks for exactly one match; reports deprecations
458 -- Returns Nothing, without error, if too few
459 lookupGreRn_help rdr_name lookup 
460   = do  { env <- getGlobalRdrEnv
461         ; case lookup env of
462             []    -> return Nothing
463             [gre] -> do { addUsedRdrName gre rdr_name
464                         ; return (Just gre) }
465             gres  -> do { addNameClashErrRn rdr_name gres
466                         ; return (Just (head gres)) } }
467
468 addUsedRdrName :: GlobalRdrElt -> RdrName -> RnM ()
469 -- Record usage of imported RdrNames
470 addUsedRdrName gre rdr
471   | isLocalGRE gre = return ()
472   | otherwise      = do { env <- getGblEnv
473                         ; updMutVar (tcg_used_rdrnames env)
474                                     (\s -> Set.insert rdr s) }
475
476 addUsedRdrNames :: [RdrName] -> RnM ()
477 -- Record used sub-binders
478 -- We don't check for imported-ness here, because it's inconvenient
479 -- and not stritly necessary.
480 addUsedRdrNames rdrs
481   = do { env <- getGblEnv
482        ; updMutVar (tcg_used_rdrnames env)
483                    (\s -> foldr Set.insert s rdrs) }
484
485 ------------------------------
486 --      GHCi support
487 ------------------------------
488
489 -- A qualified name on the command line can refer to any module at all: we
490 -- try to load the interface if we don't already have it.
491 lookupQualifiedName :: RdrName -> RnM Name
492 lookupQualifiedName rdr_name
493   | Just (mod,occ) <- isQual_maybe rdr_name
494    -- Note: we want to behave as we would for a source file import here,
495    -- and respect hiddenness of modules/packages, hence loadSrcInterface.
496    = loadSrcInterface doc mod False Nothing     `thenM` \ iface ->
497
498    case  [ (mod,occ) | 
499            (mod,avails) <- mi_exports iface,
500            avail        <- avails,
501            name         <- availNames avail,
502            name == occ ] of
503       ((mod,occ):ns) -> ASSERT (null ns) 
504                         lookupOrig mod occ
505       _ -> unboundName WL_Any rdr_name
506
507   | otherwise
508   = pprPanic "RnEnv.lookupQualifiedName" (ppr rdr_name)
509   where
510     doc = ptext (sLit "Need to find") <+> ppr rdr_name
511 \end{code}
512
513 Note [Looking up signature names]
514 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
515 lookupSigOccRn is used for type signatures and pragmas
516 Is this valid?
517   module A
518         import M( f )
519         f :: Int -> Int
520         f x = x
521 It's clear that the 'f' in the signature must refer to A.f
522 The Haskell98 report does not stipulate this, but it will!
523 So we must treat the 'f' in the signature in the same way
524 as the binding occurrence of 'f', using lookupBndrRn
525
526 However, consider this case:
527         import M( f )
528         f :: Int -> Int
529         g x = x
530 We don't want to say 'f' is out of scope; instead, we want to
531 return the imported 'f', so that later on the reanamer will
532 correctly report "misplaced type sig".
533
534 \begin{code}
535 lookupSigOccRn :: Maybe NameSet    -- Just ns => these are the binders
536                                    --            in the same group
537                                    -- Nothing => signatures without 
538                                    --            binders are expected
539                                    --            (a) top-level (SPECIALISE prags)
540                                    --            (b) class decls
541                                    --            (c) hs-boot files
542                -> Sig RdrName
543                -> Located RdrName -> RnM (Located Name)
544 lookupSigOccRn mb_bound_names sig
545   = wrapLocM $ \ rdr_name -> 
546     do { mb_name <- lookupBindGroupOcc mb_bound_names (hsSigDoc sig) rdr_name
547        ; case mb_name of
548            Left err   -> do { addErr err; return (mkUnboundName rdr_name) }
549            Right name -> return name }
550
551 lookupBindGroupOcc :: Maybe NameSet  -- See notes on the (Maybe NameSet)
552                    -> SDoc           --  in lookupSigOccRn
553                    -> RdrName -> RnM (Either Message Name)
554 -- Looks up the RdrName, expecting it to resolve to one of the 
555 -- bound names passed in.  If not, return an appropriate error message
556 --
557 -- See Note [Looking up signature names]
558 lookupBindGroupOcc mb_bound_names what rdr_name
559   = do  { local_env <- getLocalRdrEnv
560         ; case lookupLocalRdrEnv local_env rdr_name of {
561             Just n  -> check_local_name n;
562             Nothing -> do       -- Not defined in a nested scope
563
564         { env <- getGlobalRdrEnv 
565         ; let gres = lookupGlobalRdrEnv env (rdrNameOcc rdr_name)
566         ; case (filter isLocalGRE gres) of
567             (gre:_) -> check_local_name (gre_name gre)
568                         -- If there is more than one local GRE for the 
569                         -- same OccName 'f', that will be reported separately
570                         -- as a duplicate top-level binding for 'f'
571             [] | null gres -> bale_out_with empty
572                | otherwise -> bale_out_with import_msg
573         }}}
574     where
575       check_local_name name     -- The name is in scope, and not imported
576           = case mb_bound_names of
577                   Just bound_names | not (name `elemNameSet` bound_names)
578                                    -> bale_out_with local_msg
579                   _other -> return (Right name)
580
581       bale_out_with msg 
582         = return (Left (sep [ ptext (sLit "The") <+> what
583                                 <+> ptext (sLit "for") <+> quotes (ppr rdr_name)
584                            , nest 2 $ ptext (sLit "lacks an accompanying binding")]
585                        $$ nest 2 msg))
586
587       local_msg = parens $ ptext (sLit "The")  <+> what <+> ptext (sLit "must be given where")
588                            <+> quotes (ppr rdr_name) <+> ptext (sLit "is declared")
589
590       import_msg = parens $ ptext (sLit "You cannot give a") <+> what
591                           <+> ptext (sLit "for an imported value")
592
593 ---------------
594 lookupLocalDataTcNames :: NameSet -> SDoc -> RdrName -> RnM [Name]
595 -- GHC extension: look up both the tycon and data con 
596 -- for con-like things
597 -- Complain if neither is in scope
598 lookupLocalDataTcNames bound_names what rdr_name
599   | Just n <- isExact_maybe rdr_name    
600         -- Special case for (:), which doesn't get into the GlobalRdrEnv
601   = return [n]  -- For this we don't need to try the tycon too
602   | otherwise
603   = do  { mb_gres <- mapM (lookupBindGroupOcc (Just bound_names) what)
604                           (dataTcOccs rdr_name)
605         ; let (errs, names) = splitEithers mb_gres
606         ; when (null names) (addErr (head errs))        -- Bleat about one only
607         ; return names }
608
609 dataTcOccs :: RdrName -> [RdrName]
610 -- If the input is a data constructor, return both it and a type
611 -- constructor.  This is useful when we aren't sure which we are
612 -- looking at.
613 dataTcOccs rdr_name
614   | Just n <- isExact_maybe rdr_name            -- Ghastly special case
615   , n `hasKey` consDataConKey = [rdr_name]      -- see note below
616   | isDataOcc occ             = [rdr_name, rdr_name_tc]
617   | otherwise                 = [rdr_name]
618   where    
619     occ         = rdrNameOcc rdr_name
620     rdr_name_tc = setRdrNameSpace rdr_name tcName
621
622 -- If the user typed "[]" or "(,,)", we'll generate an Exact RdrName,
623 -- and setRdrNameSpace generates an Orig, which is fine
624 -- But it's not fine for (:), because there *is* no corresponding type
625 -- constructor.  If we generate an Orig tycon for GHC.Base.(:), it'll
626 -- appear to be in scope (because Orig's simply allocate a new name-cache
627 -- entry) and then we get an error when we use dataTcOccs in 
628 -- TcRnDriver.tcRnGetInfo.  Large sigh.
629 \end{code}
630
631
632 %*********************************************************
633 %*                                                      *
634                 Fixities
635 %*                                                      *
636 %*********************************************************
637
638 \begin{code}
639 --------------------------------
640 type FastStringEnv a = UniqFM a         -- Keyed by FastString
641
642
643 emptyFsEnv  :: FastStringEnv a
644 lookupFsEnv :: FastStringEnv a -> FastString -> Maybe a
645 extendFsEnv :: FastStringEnv a -> FastString -> a -> FastStringEnv a
646
647 emptyFsEnv  = emptyUFM
648 lookupFsEnv = lookupUFM
649 extendFsEnv = addToUFM
650
651 --------------------------------
652 type MiniFixityEnv = FastStringEnv (Located Fixity)
653         -- Mini fixity env for the names we're about 
654         -- to bind, in a single binding group
655         --
656         -- It is keyed by the *FastString*, not the *OccName*, because
657         -- the single fixity decl       infix 3 T
658         -- affects both the data constructor T and the type constrctor T
659         --
660         -- We keep the location so that if we find
661         -- a duplicate, we can report it sensibly
662
663 --------------------------------
664 -- Used for nested fixity decls to bind names along with their fixities.
665 -- the fixities are given as a UFM from an OccName's FastString to a fixity decl
666
667 addLocalFixities :: MiniFixityEnv -> [Name] -> RnM a -> RnM a
668 addLocalFixities mini_fix_env names thing_inside
669   = extendFixityEnv (mapCatMaybes find_fixity names) thing_inside
670   where
671     find_fixity name 
672       = case lookupFsEnv mini_fix_env (occNameFS occ) of
673           Just (L _ fix) -> Just (name, FixItem occ fix)
674           Nothing        -> Nothing
675       where
676         occ = nameOccName name
677 \end{code}
678
679 --------------------------------
680 lookupFixity is a bit strange.  
681
682 * Nested local fixity decls are put in the local fixity env, which we
683   find with getFixtyEnv
684
685 * Imported fixities are found in the HIT or PIT
686
687 * Top-level fixity decls in this module may be for Names that are
688     either  Global         (constructors, class operations)
689     or      Local/Exported (everything else)
690   (See notes with RnNames.getLocalDeclBinders for why we have this split.)
691   We put them all in the local fixity environment
692
693 \begin{code}
694 lookupFixityRn :: Name -> RnM Fixity
695 lookupFixityRn name
696   = getModule                           `thenM` \ this_mod -> 
697     if nameIsLocalOrFrom this_mod name
698     then do     -- It's defined in this module
699       local_fix_env <- getFixityEnv             
700       traceRn (text "lookupFixityRn: looking up name in local environment:" <+> 
701                vcat [ppr name, ppr local_fix_env])
702       return $ lookupFixity local_fix_env name
703     else        -- It's imported
704       -- For imported names, we have to get their fixities by doing a
705       -- loadInterfaceForName, and consulting the Ifaces that comes back
706       -- from that, because the interface file for the Name might not
707       -- have been loaded yet.  Why not?  Suppose you import module A,
708       -- which exports a function 'f', thus;
709       --        module CurrentModule where
710       --          import A( f )
711       --        module A( f ) where
712       --          import B( f )
713       -- Then B isn't loaded right away (after all, it's possible that
714       -- nothing from B will be used).  When we come across a use of
715       -- 'f', we need to know its fixity, and it's then, and only
716       -- then, that we load B.hi.  That is what's happening here.
717       --
718       -- loadInterfaceForName will find B.hi even if B is a hidden module,
719       -- and that's what we want.
720         loadInterfaceForName doc name   `thenM` \ iface -> do {
721           traceRn (text "lookupFixityRn: looking up name in iface cache and found:" <+> 
722                    vcat [ppr name, ppr $ mi_fix_fn iface (nameOccName name)]);
723            return (mi_fix_fn iface (nameOccName name))
724                                                            }
725   where
726     doc = ptext (sLit "Checking fixity for") <+> ppr name
727
728 ---------------
729 lookupTyFixityRn :: Located Name -> RnM Fixity
730 lookupTyFixityRn (L _ n) = lookupFixityRn n
731
732 \end{code}
733
734 %************************************************************************
735 %*                                                                      *
736                         Rebindable names
737         Dealing with rebindable syntax is driven by the 
738         Opt_RebindableSyntax dynamic flag.
739
740         In "deriving" code we don't want to use rebindable syntax
741         so we switch off the flag locally
742
743 %*                                                                      *
744 %************************************************************************
745
746 Haskell 98 says that when you say "3" you get the "fromInteger" from the
747 Standard Prelude, regardless of what is in scope.   However, to experiment
748 with having a language that is less coupled to the standard prelude, we're
749 trying a non-standard extension that instead gives you whatever "Prelude.fromInteger"
750 happens to be in scope.  Then you can
751         import Prelude ()
752         import MyPrelude as Prelude
753 to get the desired effect.
754
755 At the moment this just happens for
756   * fromInteger, fromRational on literals (in expressions and patterns)
757   * negate (in expressions)
758   * minus  (arising from n+k patterns)
759   * "do" notation
760
761 We store the relevant Name in the HsSyn tree, in 
762   * HsIntegral/HsFractional/HsIsString
763   * NegApp
764   * NPlusKPat
765   * HsDo
766 respectively.  Initially, we just store the "standard" name (PrelNames.fromIntegralName,
767 fromRationalName etc), but the renamer changes this to the appropriate user
768 name if Opt_NoImplicitPrelude is on.  That is what lookupSyntaxName does.
769
770 We treat the orignal (standard) names as free-vars too, because the type checker
771 checks the type of the user thing against the type of the standard thing.
772
773 \begin{code}
774 lookupIfThenElse :: RnM (Maybe (SyntaxExpr Name), FreeVars)
775 -- Different to lookupSyntaxName because in the non-rebindable
776 -- case we desugar directly rather than calling an existing function
777 -- Hence the (Maybe (SyntaxExpr Name)) return type
778 lookupIfThenElse 
779   = do { rebind <- xoptM Opt_RebindableSyntax
780        ; if not rebind 
781          then return (Nothing, emptyFVs)
782          else do { ite <- lookupOccRn (mkVarUnqual (fsLit "ifThenElse"))
783                  ; return (Just (HsVar ite), unitFV ite) } }
784
785 lookupSyntaxName :: Name                                -- The standard name
786                  -> RnM (SyntaxExpr Name, FreeVars)     -- Possibly a non-standard name
787 lookupSyntaxName std_name
788   = xoptM Opt_RebindableSyntax          `thenM` \ rebindable_on -> 
789     if not rebindable_on then normal_case 
790     else
791         -- Get the similarly named thing from the local environment
792     lookupOccRn (mkRdrUnqual (nameOccName std_name)) `thenM` \ usr_name ->
793     return (HsVar usr_name, unitFV usr_name)
794   where
795     normal_case = return (HsVar std_name, emptyFVs)
796
797 lookupSyntaxTable :: [Name]                             -- Standard names
798                   -> RnM (SyntaxTable Name, FreeVars)   -- See comments with HsExpr.ReboundNames
799 lookupSyntaxTable std_names
800   = xoptM Opt_RebindableSyntax          `thenM` \ rebindable_on -> 
801     if not rebindable_on then normal_case 
802     else
803         -- Get the similarly named thing from the local environment
804     mapM (lookupOccRn . mkRdrUnqual . nameOccName) std_names    `thenM` \ usr_names ->
805
806     return (std_names `zip` map HsVar usr_names, mkFVs usr_names)
807   where
808     normal_case = return (std_names `zip` map HsVar std_names, emptyFVs)
809 \end{code}
810
811
812 %*********************************************************
813 %*                                                      *
814 \subsection{Binding}
815 %*                                                      *
816 %*********************************************************
817
818 \begin{code}
819 newLocalBndrRn :: Located RdrName -> RnM Name
820 -- Used for non-top-level binders.  These should
821 -- never be qualified.
822 newLocalBndrRn (L loc rdr_name)
823   | Just name <- isExact_maybe rdr_name 
824   = return name -- This happens in code generated by Template Haskell
825                 -- although I'm not sure why. Perhpas it's the call
826                 -- in RnPat.newName LetMk?
827   | otherwise
828   = do { unless (isUnqual rdr_name)
829                 (addErrAt loc (badQualBndrErr rdr_name))
830        ; uniq <- newUnique
831        ; return (mkInternalName uniq (rdrNameOcc rdr_name) loc) }
832
833 newLocalBndrsRn :: [Located RdrName] -> RnM [Name]
834 newLocalBndrsRn = mapM newLocalBndrRn
835
836 ---------------------
837 bindLocatedLocalsRn :: [Located RdrName]
838                     -> ([Name] -> RnM a)
839                     -> RnM a
840 bindLocatedLocalsRn rdr_names_w_loc enclosed_scope
841   = do { checkDupAndShadowedRdrNames rdr_names_w_loc
842
843         -- Make fresh Names and extend the environment
844        ; names <- newLocalBndrsRn rdr_names_w_loc
845        ; bindLocalNames names (enclosed_scope names) }
846
847 bindLocalNames :: [Name] -> RnM a -> RnM a
848 bindLocalNames names enclosed_scope
849   = do { name_env <- getLocalRdrEnv
850        ; setLocalRdrEnv (extendLocalRdrEnvList name_env names)
851                         enclosed_scope }
852
853 bindLocalName :: Name -> RnM a -> RnM a
854 bindLocalName name enclosed_scope
855   = do { name_env <- getLocalRdrEnv
856        ; setLocalRdrEnv (extendLocalRdrEnv name_env name)
857                         enclosed_scope }
858
859 bindLocalNamesFV :: [Name] -> RnM (a, FreeVars) -> RnM (a, FreeVars)
860 bindLocalNamesFV names enclosed_scope
861   = do  { (result, fvs) <- bindLocalNames names enclosed_scope
862         ; return (result, delFVs names fvs) }
863
864
865 -------------------------------------
866         -- binLocalsFVRn is the same as bindLocalsRn
867         -- except that it deals with free vars
868 bindLocatedLocalsFV :: [Located RdrName] 
869                     -> ([Name] -> RnM (a,FreeVars)) -> RnM (a, FreeVars)
870 bindLocatedLocalsFV rdr_names enclosed_scope
871   = bindLocatedLocalsRn rdr_names       $ \ names ->
872     enclosed_scope names                `thenM` \ (thing, fvs) ->
873     return (thing, delFVs names fvs)
874
875 -------------------------------------
876 bindTyVarsFV ::  [LHsTyVarBndr RdrName]
877               -> ([LHsTyVarBndr Name] -> RnM (a, FreeVars))
878               -> RnM (a, FreeVars)
879 bindTyVarsFV tyvars thing_inside
880   = bindTyVarsRn tyvars $ \ tyvars' ->
881     do { (res, fvs) <- thing_inside tyvars'
882        ; return (res, delFVs (map hsLTyVarName tyvars') fvs) }
883
884 bindTyVarsRn ::  [LHsTyVarBndr RdrName]
885               -> ([LHsTyVarBndr Name] -> RnM a)
886               -> RnM a
887 -- Haskell-98 binding of type variables; e.g. within a data type decl
888 bindTyVarsRn tyvar_names enclosed_scope
889   = bindLocatedLocalsRn located_tyvars  $ \ names ->
890     do { kind_sigs_ok <- xoptM Opt_KindSignatures
891        ; unless (null kinded_tyvars || kind_sigs_ok) 
892                 (mapM_ (addErr . kindSigErr) kinded_tyvars)
893        ; enclosed_scope (zipWith replace tyvar_names names) }
894   where 
895     replace (L loc n1) n2 = L loc (replaceTyVarName n1 n2)
896     located_tyvars = hsLTyVarLocNames tyvar_names
897     kinded_tyvars  = [n | L _ (KindedTyVar n _) <- tyvar_names]
898
899 bindPatSigTyVars :: [LHsType RdrName] -> ([Name] -> RnM a) -> RnM a
900   -- Find the type variables in the pattern type 
901   -- signatures that must be brought into scope
902 bindPatSigTyVars tys thing_inside
903   = do  { scoped_tyvars <- xoptM Opt_ScopedTypeVariables
904         ; if not scoped_tyvars then 
905                 thing_inside []
906           else 
907     do  { name_env <- getLocalRdrEnv
908         ; let locd_tvs  = [ tv | ty <- tys
909                                , tv <- extractHsTyRdrTyVars ty
910                                , not (unLoc tv `elemLocalRdrEnv` name_env) ]
911               nubbed_tvs = nubBy eqLocated locd_tvs
912                 -- The 'nub' is important.  For example:
913                 --      f (x :: t) (y :: t) = ....
914                 -- We don't want to complain about binding t twice!
915
916         ; bindLocatedLocalsRn nubbed_tvs thing_inside }}
917
918 bindPatSigTyVarsFV :: [LHsType RdrName]
919                    -> RnM (a, FreeVars)
920                    -> RnM (a, FreeVars)
921 bindPatSigTyVarsFV tys thing_inside
922   = bindPatSigTyVars tys        $ \ tvs ->
923     thing_inside                `thenM` \ (result,fvs) ->
924     return (result, fvs `delListFromNameSet` tvs)
925
926 bindSigTyVarsFV :: [Name]
927                 -> RnM (a, FreeVars)
928                 -> RnM (a, FreeVars)
929 bindSigTyVarsFV tvs thing_inside
930   = do  { scoped_tyvars <- xoptM Opt_ScopedTypeVariables
931         ; if not scoped_tyvars then 
932                 thing_inside 
933           else
934                 bindLocalNamesFV tvs thing_inside }
935
936 extendTyVarEnvFVRn :: [Name] -> RnM (a, FreeVars) -> RnM (a, FreeVars)
937         -- This function is used only in rnSourceDecl on InstDecl
938 extendTyVarEnvFVRn tyvars thing_inside = bindLocalNamesFV tyvars thing_inside
939
940 -------------------------------------
941 checkDupRdrNames :: [Located RdrName] -> RnM ()
942 checkDupRdrNames rdr_names_w_loc
943   =     -- Check for duplicated names in a binding group
944     mapM_ (dupNamesErr getLoc) dups
945   where
946     (_, dups) = removeDups (\n1 n2 -> unLoc n1 `compare` unLoc n2) rdr_names_w_loc
947
948 checkDupNames :: [Name] -> RnM ()
949 checkDupNames names
950   =     -- Check for duplicated names in a binding group
951     mapM_ (dupNamesErr nameSrcSpan) dups
952   where
953     (_, dups) = removeDups (\n1 n2 -> nameOccName n1 `compare` nameOccName n2) names
954
955 ---------------------
956 checkDupAndShadowedRdrNames :: [Located RdrName] -> RnM ()
957 checkDupAndShadowedRdrNames loc_rdr_names
958   = do  { checkDupRdrNames loc_rdr_names
959         ; envs <- getRdrEnvs
960         ; checkShadowedOccs envs loc_occs }
961   where
962     loc_occs = [(loc,rdrNameOcc rdr) | L loc rdr <- loc_rdr_names]
963
964 checkDupAndShadowedNames :: (GlobalRdrEnv, LocalRdrEnv) -> [Name] -> RnM ()
965 checkDupAndShadowedNames envs names
966   = do { checkDupNames names
967        ; checkShadowedOccs envs loc_occs }
968   where
969     loc_occs = [(nameSrcSpan name, nameOccName name) | name <- names]
970
971 -------------------------------------
972 checkShadowedOccs :: (GlobalRdrEnv, LocalRdrEnv) -> [(SrcSpan,OccName)] -> RnM ()
973 checkShadowedOccs (global_env,local_env) loc_occs
974   = ifDOptM Opt_WarnNameShadowing $ 
975     do  { traceRn (text "shadow" <+> ppr loc_occs)
976         ; mapM_ check_shadow loc_occs }
977   where
978     check_shadow (loc, occ)
979         | startsWithUnderscore occ = return ()  -- Do not report shadowing for "_x"
980                                                 -- See Trac #3262
981         | Just n <- mb_local = complain [ptext (sLit "bound at") <+> ppr (nameSrcLoc n)]
982         | otherwise = do { gres' <- filterM is_shadowed_gre gres
983                          ; complain (map pprNameProvenance gres') }
984         where
985           complain []      = return ()
986           complain pp_locs = addWarnAt loc (shadowedNameWarn occ pp_locs)
987           mb_local = lookupLocalRdrOcc local_env occ
988           gres     = lookupGRE_RdrName (mkRdrUnqual occ) global_env
989                 -- Make an Unqualified RdrName and look that up, so that
990                 -- we don't find any GREs that are in scope qualified-only
991
992     is_shadowed_gre :: GlobalRdrElt -> RnM Bool 
993         -- Returns False for record selectors that are shadowed, when
994         -- punning or wild-cards are on (cf Trac #2723)
995     is_shadowed_gre gre@(GRE { gre_par = ParentIs _ })
996         = do { dflags <- getDOpts
997              ; if (xopt Opt_RecordPuns dflags || xopt Opt_RecordWildCards dflags) 
998                then do { is_fld <- is_rec_fld gre; return (not is_fld) }
999                else return True }
1000     is_shadowed_gre _other = return True
1001
1002     is_rec_fld gre      -- Return True for record selector ids
1003         | isLocalGRE gre = do { RecFields _ fld_set <- getRecFieldEnv
1004                               ; return (gre_name gre `elemNameSet` fld_set) }
1005         | otherwise      = do { sel_id <- tcLookupField (gre_name gre)
1006                               ; return (isRecordSelector sel_id) }
1007 \end{code}
1008
1009
1010 %************************************************************************
1011 %*                                                                      *
1012                What to do when a lookup fails
1013 %*                                                                      *
1014 %************************************************************************
1015
1016 \begin{code}
1017 data WhereLooking = WL_Any        -- Any binding
1018                   | WL_Global     -- Any top-level binding (local or imported)
1019                   | WL_LocalTop   -- Any top-level binding in this module
1020
1021 unboundName :: WhereLooking -> RdrName -> RnM Name
1022 unboundName where_look rdr_name
1023   = do  { show_helpful_errors <- doptM Opt_HelpfulErrors
1024         ; let err = unknownNameErr rdr_name
1025         ; if not show_helpful_errors
1026           then addErr err
1027           else do { extra_err <- unknownNameSuggestErr where_look rdr_name
1028                   ; addErr (err $$ extra_err) }
1029
1030         ; env <- getGlobalRdrEnv;
1031         ; traceRn (vcat [unknownNameErr rdr_name, 
1032                          ptext (sLit "Global envt is:"),
1033                          nest 3 (pprGlobalRdrEnv env)])
1034
1035         ; return (mkUnboundName rdr_name) }
1036
1037 unknownNameErr :: RdrName -> SDoc
1038 unknownNameErr rdr_name
1039   = vcat [ hang (ptext (sLit "Not in scope:")) 
1040               2 (pprNonVarNameSpace (occNameSpace (rdrNameOcc rdr_name))
1041                           <+> quotes (ppr rdr_name))
1042          , extra ]
1043   where
1044     extra | rdr_name == forall_tv_RDR = perhapsForallMsg
1045           | otherwise                 = empty
1046
1047 type HowInScope = Either SrcSpan ImpDeclSpec
1048      -- Left loc    =>  locally bound at loc
1049      -- Right ispec =>  imported as specified by ispec
1050
1051 unknownNameSuggestErr :: WhereLooking -> RdrName -> RnM SDoc
1052 unknownNameSuggestErr where_look tried_rdr_name
1053   = do { local_env <- getLocalRdrEnv
1054        ; global_env <- getGlobalRdrEnv
1055
1056        ; let all_possibilities :: [(String, (RdrName, HowInScope))]
1057              all_possibilities
1058                 =  [ (showSDoc (ppr r), (r, Left loc))
1059                    | (r,loc) <- local_possibilities local_env ]
1060                 ++ [ (showSDoc (ppr r), rp) | (r,rp) <- global_possibilities global_env ]
1061
1062              suggest = fuzzyLookup (showSDoc (ppr tried_rdr_name)) all_possibilities
1063              perhaps = ptext (sLit "Perhaps you meant")
1064              extra_err = case suggest of
1065                            []  -> empty
1066                            [p] -> perhaps <+> pp_item p
1067                            ps  -> sep [ perhaps <+> ptext (sLit "one of these:")
1068                                       , nest 2 (pprWithCommas pp_item ps) ]
1069        ; return extra_err }
1070   where
1071     pp_item :: (RdrName, HowInScope) -> SDoc
1072     pp_item (rdr, Left loc) = quotes (ppr rdr) <+>   -- Locally defined
1073                               parens (ptext (sLit "line") <+> int (srcSpanStartLine loc'))
1074         where loc' = case loc of
1075                      UnhelpfulSpan _ ->
1076                          panic "unknownNameSuggestErr UnhelpfulSpan"
1077                      RealSrcSpan l -> l
1078     pp_item (rdr, Right is) = quotes (ppr rdr) <+>   -- Imported
1079                               parens (ptext (sLit "imported from") <+> ppr (is_mod is))
1080
1081     tried_occ     = rdrNameOcc tried_rdr_name
1082     tried_is_sym  = isSymOcc tried_occ
1083     tried_ns      = occNameSpace tried_occ
1084     tried_is_qual = isQual tried_rdr_name
1085
1086     correct_name_space occ =  occNameSpace occ == tried_ns
1087                            && isSymOcc occ == tried_is_sym
1088         -- Treat operator and non-operators as non-matching
1089         -- This heuristic avoids things like
1090         --      Not in scope 'f'; perhaps you meant '+' (from Prelude)
1091
1092     local_ok = case where_look of { WL_Any -> True; _ -> False }
1093     local_possibilities :: LocalRdrEnv -> [(RdrName, SrcSpan)]
1094     local_possibilities env
1095       | tried_is_qual = []
1096       | not local_ok  = []
1097       | otherwise     = [ (mkRdrUnqual occ, nameSrcSpan name)
1098                         | name <- occEnvElts env
1099                         , let occ = nameOccName name
1100                         , correct_name_space occ]
1101
1102     gre_ok :: GlobalRdrElt -> Bool
1103     gre_ok = case where_look of
1104                    WL_LocalTop -> isLocalGRE
1105                    _           -> \_ -> True
1106
1107     global_possibilities :: GlobalRdrEnv -> [(RdrName, (RdrName, HowInScope))]
1108     global_possibilities global_env
1109       | tried_is_qual = [ (rdr_qual, (rdr_qual, how))
1110                         | gre <- globalRdrEnvElts global_env
1111                         , gre_ok gre
1112                         , let name = gre_name gre
1113                               occ  = nameOccName name
1114                         , correct_name_space occ
1115                         , (mod, how) <- quals_in_scope name (gre_prov gre)
1116                         , let rdr_qual = mkRdrQual mod occ ]
1117
1118       | otherwise = [ (rdr_unqual, pair)
1119                     | gre <- globalRdrEnvElts global_env
1120                     , gre_ok gre
1121                     , let name = gre_name gre
1122                           prov = gre_prov gre
1123                           occ  = nameOccName name
1124                           rdr_unqual = mkRdrUnqual occ
1125                     , correct_name_space occ
1126                     , pair <- case (unquals_in_scope name prov, quals_only occ prov) of
1127                                 (how:_, _)    -> [ (rdr_unqual, how) ]
1128                                 ([],    pr:_) -> [ pr ]  -- See Note [Only-quals]
1129                                 ([],    [])   -> [] ]
1130
1131               -- Note [Only-quals]
1132               -- The second alternative returns those names with the same
1133               -- OccName as the one we tried, but live in *qualified* imports
1134               -- e.g. if you have:
1135               --
1136               -- > import qualified Data.Map as Map
1137               -- > foo :: Map
1138               --
1139               -- then we suggest @Map.Map@.
1140
1141     --------------------
1142     unquals_in_scope :: Name -> Provenance -> [HowInScope]
1143     unquals_in_scope n LocalDef      = [ Left (nameSrcSpan n) ]
1144     unquals_in_scope _ (Imported is) = [ Right ispec
1145                                        | i <- is, let ispec = is_decl i
1146                                        , not (is_qual ispec) ]
1147
1148     --------------------
1149     quals_in_scope :: Name -> Provenance -> [(ModuleName, HowInScope)]
1150     -- Ones for which the qualified version is in scope
1151     quals_in_scope n LocalDef      = case nameModule_maybe n of
1152                                        Nothing -> []
1153                                        Just m  -> [(moduleName m, Left (nameSrcSpan n))]
1154     quals_in_scope _ (Imported is) = [ (is_as ispec, Right ispec)
1155                                      | i <- is, let ispec = is_decl i ]
1156
1157     --------------------
1158     quals_only :: OccName -> Provenance -> [(RdrName, HowInScope)]
1159     -- Ones for which *only* the qualified version is in scope
1160     quals_only _   LocalDef      = []
1161     quals_only occ (Imported is) = [ (mkRdrQual (is_as ispec) occ, Right ispec)
1162                                    | i <- is, let ispec = is_decl i, is_qual ispec ]
1163 \end{code}
1164
1165 %************************************************************************
1166 %*                                                                      *
1167 \subsection{Free variable manipulation}
1168 %*                                                                      *
1169 %************************************************************************
1170
1171 \begin{code}
1172 -- A useful utility
1173 addFvRn :: FreeVars -> RnM (thing, FreeVars) -> RnM (thing, FreeVars)
1174 addFvRn fvs1 thing_inside = do { (res, fvs2) <- thing_inside
1175                                ; return (res, fvs1 `plusFV` fvs2) }
1176
1177 mapFvRn :: (a -> RnM (b, FreeVars)) -> [a] -> RnM ([b], FreeVars)
1178 mapFvRn f xs = do stuff <- mapM f xs
1179                   case unzip stuff of
1180                       (ys, fvs_s) -> return (ys, plusFVs fvs_s)
1181
1182 mapMaybeFvRn :: (a -> RnM (b, FreeVars)) -> Maybe a -> RnM (Maybe b, FreeVars)
1183 mapMaybeFvRn _ Nothing = return (Nothing, emptyFVs)
1184 mapMaybeFvRn f (Just x) = do { (y, fvs) <- f x; return (Just y, fvs) }
1185
1186 -- because some of the rename functions are CPSed:
1187 -- maps the function across the list from left to right; 
1188 -- collects all the free vars into one set
1189 mapFvRnCPS :: (a  -> (b   -> RnM c) -> RnM c) 
1190            -> [a] -> ([b] -> RnM c) -> RnM c
1191
1192 mapFvRnCPS _ []     cont = cont []
1193 mapFvRnCPS f (x:xs) cont = f x             $ \ x' -> 
1194                            mapFvRnCPS f xs $ \ xs' ->
1195                            cont (x':xs')
1196 \end{code}
1197
1198
1199 %************************************************************************
1200 %*                                                                      *
1201 \subsection{Envt utility functions}
1202 %*                                                                      *
1203 %************************************************************************
1204
1205 \begin{code}
1206 warnUnusedTopBinds :: [GlobalRdrElt] -> RnM ()
1207 warnUnusedTopBinds gres
1208     = ifDOptM Opt_WarnUnusedBinds
1209     $ do isBoot <- tcIsHsBoot
1210          let noParent gre = case gre_par gre of
1211                             NoParent -> True
1212                             ParentIs _ -> False
1213              -- Don't warn about unused bindings with parents in
1214              -- .hs-boot files, as you are sometimes required to give
1215              -- unused bindings (trac #3449).
1216              gres' = if isBoot then filter noParent gres
1217                                else                 gres
1218          warnUnusedGREs gres'
1219
1220 warnUnusedLocalBinds, warnUnusedMatches :: [Name] -> FreeVars -> RnM ()
1221 warnUnusedLocalBinds = check_unused Opt_WarnUnusedBinds
1222 warnUnusedMatches    = check_unused Opt_WarnUnusedMatches
1223
1224 check_unused :: DynFlag -> [Name] -> FreeVars -> RnM ()
1225 check_unused flag bound_names used_names
1226  = ifDOptM flag (warnUnusedLocals (filterOut (`elemNameSet` used_names) bound_names))
1227
1228 -------------------------
1229 --      Helpers
1230 warnUnusedGREs :: [GlobalRdrElt] -> RnM ()
1231 warnUnusedGREs gres 
1232  = warnUnusedBinds [(n,p) | GRE {gre_name = n, gre_prov = p} <- gres]
1233
1234 warnUnusedLocals :: [Name] -> RnM ()
1235 warnUnusedLocals names
1236  = warnUnusedBinds [(n,LocalDef) | n<-names]
1237
1238 warnUnusedBinds :: [(Name,Provenance)] -> RnM ()
1239 warnUnusedBinds names  = mapM_ warnUnusedName (filter reportable names)
1240  where reportable (name,_) 
1241         | isWiredInName name = False    -- Don't report unused wired-in names
1242                                         -- Otherwise we get a zillion warnings
1243                                         -- from Data.Tuple
1244         | otherwise = not (startsWithUnderscore (nameOccName name))
1245
1246 -------------------------
1247
1248 warnUnusedName :: (Name, Provenance) -> RnM ()
1249 warnUnusedName (name, LocalDef)
1250   = addUnusedWarning name (nameSrcSpan name)
1251                      (ptext (sLit "Defined but not used"))
1252
1253 warnUnusedName (name, Imported is)
1254   = mapM_ warn is
1255   where
1256     warn spec = addUnusedWarning name span msg
1257         where
1258            span = importSpecLoc spec
1259            pp_mod = quotes (ppr (importSpecModule spec))
1260            msg = ptext (sLit "Imported from") <+> pp_mod <+> ptext (sLit "but not used")
1261
1262 addUnusedWarning :: Name -> SrcSpan -> SDoc -> RnM ()
1263 addUnusedWarning name span msg
1264   = addWarnAt span $
1265     sep [msg <> colon, 
1266          nest 2 $ pprNonVarNameSpace (occNameSpace (nameOccName name))
1267                         <+> quotes (ppr name)]
1268 \end{code}
1269
1270 \begin{code}
1271 addNameClashErrRn :: RdrName -> [GlobalRdrElt] -> RnM ()
1272 addNameClashErrRn rdr_name names
1273   = addErr (vcat [ptext (sLit "Ambiguous occurrence") <+> quotes (ppr rdr_name),
1274                   ptext (sLit "It could refer to") <+> vcat (msg1 : msgs)])
1275   where
1276     (np1:nps) = names
1277     msg1 = ptext  (sLit "either") <+> mk_ref np1
1278     msgs = [ptext (sLit "    or") <+> mk_ref np | np <- nps]
1279     mk_ref gre = sep [quotes (ppr (gre_name gre)) <> comma, pprNameProvenance gre]
1280
1281 shadowedNameWarn :: OccName -> [SDoc] -> SDoc
1282 shadowedNameWarn occ shadowed_locs
1283   = sep [ptext (sLit "This binding for") <+> quotes (ppr occ)
1284             <+> ptext (sLit "shadows the existing binding") <> plural shadowed_locs,
1285          nest 2 (vcat shadowed_locs)]
1286
1287 perhapsForallMsg :: SDoc
1288 perhapsForallMsg 
1289   = vcat [ ptext (sLit "Perhaps you intended to use -XExplicitForAll or similar flag")
1290          , ptext (sLit "to enable explicit-forall syntax: forall <tvs>. <type>")]
1291
1292 unknownSubordinateErr :: SDoc -> RdrName -> SDoc
1293 unknownSubordinateErr doc op    -- Doc is "method of class" or 
1294                                 -- "field of constructor"
1295   = quotes (ppr op) <+> ptext (sLit "is not a (visible)") <+> doc
1296
1297 badOrigBinding :: RdrName -> SDoc
1298 badOrigBinding name
1299   = ptext (sLit "Illegal binding of built-in syntax:") <+> ppr (rdrNameOcc name)
1300         -- The rdrNameOcc is because we don't want to print Prelude.(,)
1301
1302 dupNamesErr :: Outputable n => (n -> SrcSpan) -> [n] -> RnM ()
1303 dupNamesErr get_loc names
1304   = addErrAt big_loc $
1305     vcat [ptext (sLit "Conflicting definitions for") <+> quotes (ppr (head names)),
1306           locations]
1307   where
1308     locs      = map get_loc names
1309     big_loc   = foldr1 combineSrcSpans locs
1310     locations = ptext (sLit "Bound at:") <+> vcat (map ppr (sortLe (<=) locs))
1311
1312 kindSigErr :: Outputable a => a -> SDoc
1313 kindSigErr thing
1314   = hang (ptext (sLit "Illegal kind signature for") <+> quotes (ppr thing))
1315        2 (ptext (sLit "Perhaps you intended to use -XKindSignatures"))
1316
1317
1318 badQualBndrErr :: RdrName -> SDoc
1319 badQualBndrErr rdr_name
1320   = ptext (sLit "Qualified name in binding position:") <+> ppr rdr_name
1321
1322 opDeclErr :: RdrName -> SDoc
1323 opDeclErr n 
1324   = hang (ptext (sLit "Illegal declaration of a type or class operator") <+> quotes (ppr n))
1325        2 (ptext (sLit "Use -XTypeOperators to declare operators in type and declarations"))
1326 \end{code}