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