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