Take vectorisation declarations into account during the initial occurrence analysis...
[ghc-hetmet.git] / compiler / rename / RnEnv.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-2006
3 %
4 \section[RnEnv]{Environment manipulation for the renamer monad}
5
6 \begin{code}
7 module RnEnv ( 
8         newTopSrcBinder, lookupFamInstDeclBndr,
9         lookupLocatedTopBndrRn, lookupTopBndrRn,
10         lookupLocatedOccRn, lookupOccRn, 
11         lookupGlobalOccRn, lookupGlobalOccRn_maybe,
12         lookupLocalDataTcNames, lookupSigOccRn,
13         lookupFixityRn, lookupTyFixityRn, 
14         lookupInstDeclBndr, lookupSubBndr, lookupConstructorFields,
15         lookupSyntaxName, lookupSyntaxTable, lookupIfThenElse,
16         lookupGreRn, lookupGreLocalRn, lookupGreRn_maybe,
17         getLookupOccRn, addUsedRdrNames,
18
19         newLocalBndrRn, newLocalBndrsRn, newIPNameRn,
20         bindLocalName, bindLocalNames, bindLocalNamesFV, 
21         MiniFixityEnv, emptyFsEnv, extendFsEnv, lookupFsEnv,
22         addLocalFixities,
23         bindLocatedLocalsFV, bindLocatedLocalsRn,
24         bindSigTyVarsFV, bindPatSigTyVars, bindPatSigTyVarsFV,
25         bindTyVarsRn, bindTyVarsFV, extendTyVarEnvFVRn,
26
27         checkDupRdrNames, checkDupAndShadowedRdrNames,
28         checkDupNames, checkDupAndShadowedNames, 
29         addFvRn, mapFvRn, mapMaybeFvRn, mapFvRnCPS,
30         warnUnusedMatches,
31         warnUnusedTopBinds, warnUnusedLocalBinds,
32         dataTcOccs, unknownNameErr, kindSigErr, perhapsForallMsg
33     ) where
34
35 #include "HsVersions.h"
36
37 import LoadIface        ( loadInterfaceForName, loadSrcInterface )
38 import IfaceEnv         ( lookupOrig, newGlobalBinder, newIPName )
39 import HsSyn
40 import RdrHsSyn         ( extractHsTyRdrTyVars )
41 import RdrName
42 import HscTypes         ( availNames, ModIface(..), FixItem(..), lookupFixity)
43 import TcEnv            ( tcLookupDataCon, tcLookupField, isBrackStage )
44 import TcRnMonad
45 import Id               ( isRecordSelector )
46 import Name
47 import NameSet
48 import NameEnv
49 import Module           ( ModuleName, moduleName )
50 import UniqFM
51 import DataCon          ( dataConFieldLabels )
52 import PrelNames        ( mkUnboundName, rOOT_MAIN, consDataConKey, forall_tv_RDR )
53 import Unique
54 import BasicTypes
55 import ErrUtils         ( Message )
56 import SrcLoc
57 import Outputable
58 import Util
59 import Maybes
60 import ListSetOps       ( removeDups )
61 import DynFlags
62 import FastString
63 import Control.Monad
64 import Data.List
65 import qualified Data.Set as Set
66 \end{code}
67
68 \begin{code}
69 -- XXX
70 thenM :: Monad a => a b -> (b -> a c) -> a c
71 thenM = (>>=)
72 \end{code}
73
74 %*********************************************************
75 %*                                                      *
76                 Source-code binders
77 %*                                                      *
78 %*********************************************************
79
80 \begin{code}
81 newTopSrcBinder :: Located RdrName -> RnM Name
82 newTopSrcBinder (L loc rdr_name)
83   | Just name <- isExact_maybe rdr_name
84   =     -- This is here to catch 
85         --   (a) Exact-name binders created by Template Haskell
86         --   (b) The PrelBase defn of (say) [] and similar, for which
87         --       the parser reads the special syntax and returns an Exact RdrName
88         -- We are at a binding site for the name, so check first that it 
89         -- the current module is the correct one; otherwise GHC can get
90         -- very confused indeed. This test rejects code like
91         --      data T = (,) Int Int
92         -- unless we are in GHC.Tup
93     ASSERT2( isExternalName name,  ppr name )
94     do  { this_mod <- getModule
95         ; unless (this_mod == nameModule name)
96                  (addErrAt loc (badOrigBinding rdr_name))
97         ; return name }
98
99
100   | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
101   = do  { this_mod <- getModule
102         ; unless (rdr_mod == this_mod || rdr_mod == rOOT_MAIN)
103                  (addErrAt loc (badOrigBinding rdr_name))
104         -- When reading External Core we get Orig names as binders, 
105         -- but they should agree with the module gotten from the monad
106         --
107         -- We can get built-in syntax showing up here too, sadly.  If you type
108         --      data T = (,,,)
109         -- the constructor is parsed as a type, and then RdrHsSyn.tyConToDataCon 
110         -- uses setRdrNameSpace to make it into a data constructors.  At that point
111         -- the nice Exact name for the TyCon gets swizzled to an Orig name.
112         -- Hence the badOrigBinding error message.
113         --
114         -- Except for the ":Main.main = ..." definition inserted into 
115         -- the Main module; ugh!
116
117         -- Because of this latter case, we call newGlobalBinder with a module from 
118         -- the RdrName, not from the environment.  In principle, it'd be fine to 
119         -- have an arbitrary mixture of external core definitions in a single module,
120         -- (apart from module-initialisation issues, perhaps).
121         ; newGlobalBinder rdr_mod rdr_occ loc }
122                 --TODO, should pass the whole span
123
124   | otherwise
125   = do  { unless (not (isQual rdr_name))
126                  (addErrAt loc (badQualBndrErr rdr_name))
127                 -- Binders should not be qualified; if they are, and with a different
128                 -- module name, we we get a confusing "M.T is not in scope" error later
129
130         ; stage <- getStage
131         ; if isBrackStage stage then
132                 -- We are inside a TH bracket, so make an *Internal* name
133                 -- See Note [Top-level Names in Template Haskell decl quotes] in RnNames
134              do { uniq <- newUnique
135                 ; return (mkInternalName uniq (rdrNameOcc rdr_name) loc) } 
136           else  
137                 -- Normal case
138              do { this_mod <- getModule
139                 ; newGlobalBinder this_mod (rdrNameOcc rdr_name) loc } }
140 \end{code}
141
142 %*********************************************************
143 %*                                                      *
144         Source code occurrences
145 %*                                                      *
146 %*********************************************************
147
148 Looking up a name in the RnEnv.
149
150 Note [Type and class operator definitions]
151 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
152 We want to reject all of these unless we have -XTypeOperators (Trac #3265)
153    data a :*: b  = ...
154    class a :*: b where ...
155    data (:*:) a b  = ....
156    class (:*:) a b where ...
157 The latter two mean that we are not just looking for a
158 *syntactically-infix* declaration, but one that uses an operator
159 OccName.  We use OccName.isSymOcc to detect that case, which isn't
160 terribly efficient, but there seems to be no better way.
161
162 \begin{code}
163 lookupTopBndrRn :: RdrName -> RnM Name
164 lookupTopBndrRn n = do nopt <- lookupTopBndrRn_maybe n
165                        case nopt of 
166                          Just n' -> return n'
167                          Nothing -> do traceRn $ text "lookupTopBndrRn"
168                                        unboundName WL_LocalTop n
169
170 lookupLocatedTopBndrRn :: Located RdrName -> RnM (Located Name)
171 lookupLocatedTopBndrRn = wrapLocM lookupTopBndrRn
172
173 lookupTopBndrRn_maybe :: RdrName -> RnM (Maybe Name)
174 -- Look up a top-level source-code binder.   We may be looking up an unqualified 'f',
175 -- and there may be several imported 'f's too, which must not confuse us.
176 -- For example, this is OK:
177 --      import Foo( f )
178 --      infix 9 f       -- The 'f' here does not need to be qualified
179 --      f x = x         -- Nor here, of course
180 -- So we have to filter out the non-local ones.
181 --
182 -- A separate function (importsFromLocalDecls) reports duplicate top level
183 -- decls, so here it's safe just to choose an arbitrary one.
184 --
185 -- There should never be a qualified name in a binding position in Haskell,
186 -- but there can be if we have read in an external-Core file.
187 -- The Haskell parser checks for the illegal qualified name in Haskell 
188 -- source files, so we don't need to do so here.
189
190 lookupTopBndrRn_maybe rdr_name
191   | Just name <- isExact_maybe rdr_name
192   = return (Just name)
193
194   | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name    
195         -- This deals with the case of derived bindings, where
196         -- we don't bother to call newTopSrcBinder first
197         -- We assume there is no "parent" name
198   = do  { loc <- getSrcSpanM
199         ; n <- newGlobalBinder rdr_mod rdr_occ loc 
200         ; return (Just n)}
201
202   | otherwise
203   = do  {  -- Check for operators in type or class declarations
204            -- See Note [Type and class operator definitions]
205           let occ = rdrNameOcc rdr_name
206         ; when (isTcOcc occ && isSymOcc occ)
207                (do { op_ok <- xoptM Opt_TypeOperators
208                    ; unless op_ok (addErr (opDeclErr rdr_name)) })
209
210         ; mb_gre <- lookupGreLocalRn rdr_name
211         ; case mb_gre of
212                 Nothing  -> return Nothing
213                 Just gre -> return (Just $ gre_name gre) }
214               
215
216 -----------------------------------------------
217 lookupInstDeclBndr :: Name -> RdrName -> RnM Name
218 -- This is called on the method name on the left-hand side of an 
219 -- instance declaration binding. eg.  instance Functor T where
220 --                                       fmap = ...
221 --                                       ^^^^ called on this
222 -- Regardless of how many unqualified fmaps are in scope, we want
223 -- the one that comes from the Functor class.
224 --
225 -- Furthermore, note that we take no account of whether the 
226 -- name is only in scope qualified.  I.e. even if method op is
227 -- in scope as M.op, we still allow plain 'op' on the LHS of
228 -- an instance decl
229 lookupInstDeclBndr cls rdr
230   = do { when (isQual rdr)
231               (addErr (badQualBndrErr rdr)) 
232                 -- In an instance decl you aren't allowed
233                 -- to use a qualified name for the method
234                 -- (Although it'd make perfect sense.)
235        ; lookupSubBndr (ParentIs cls) doc rdr }
236   where
237     doc = ptext (sLit "method of class") <+> quotes (ppr cls)
238
239 -----------------------------------------------
240 lookupConstructorFields :: Name -> RnM [Name]
241 -- Look up the fields of a given constructor
242 --   *  For constructors from this module, use the record field env,
243 --      which is itself gathered from the (as yet un-typechecked)
244 --      data type decls
245 -- 
246 --    * For constructors from imported modules, use the *type* environment
247 --      since imported modles are already compiled, the info is conveniently
248 --      right there
249
250 lookupConstructorFields con_name
251   = do  { this_mod <- getModule
252         ; if nameIsLocalOrFrom this_mod con_name then
253           do { RecFields field_env _ <- getRecFieldEnv
254              ; return (lookupNameEnv field_env con_name `orElse` []) }
255           else 
256           do { con <- tcLookupDataCon con_name
257              ; return (dataConFieldLabels con) } }
258
259 -----------------------------------------------
260 -- Used for record construction and pattern matching
261 -- When the -XDisambiguateRecordFields flag is on, take account of the
262 -- constructor name to disambiguate which field to use; it's just the
263 -- same as for instance decls
264 -- 
265 -- NB: Consider this:
266 --      module Foo where { data R = R { fld :: Int } }
267 --      module Odd where { import Foo; fld x = x { fld = 3 } }
268 -- Arguably this should work, because the reference to 'fld' is
269 -- unambiguous because there is only one field id 'fld' in scope.
270 -- But currently it's rejected.
271
272 lookupSubBndr :: Parent  -- NoParent   => just look it up as usual
273                          -- ParentIs p => use p to disambiguate
274               -> SDoc -> RdrName 
275               -> RnM Name
276 lookupSubBndr parent doc rdr_name
277   | Just n <- isExact_maybe rdr_name   -- This happens in derived code
278   = return n
279
280   | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
281   = lookupOrig rdr_mod rdr_occ
282
283   | otherwise   -- Find all the things the rdr-name maps to
284   = do  {       -- and pick the one with the right parent name
285         ; env <- getGlobalRdrEnv
286         ; let gres = lookupGlobalRdrEnv env (rdrNameOcc rdr_name)
287         ; case pick parent gres  of
288                 -- NB: lookupGlobalRdrEnv, not lookupGRE_RdrName!
289                 --     The latter does pickGREs, but we want to allow 'x'
290                 --     even if only 'M.x' is in scope
291             [gre] -> do { 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 lookupIfThenElse :: RnM (Maybe (SyntaxExpr Name), FreeVars)
758 -- Different to lookupSyntaxName because in the non-rebindable
759 -- case we desugar directly rather than calling an existing function
760 -- Hence the (Maybe (SyntaxExpr Name)) return type
761 lookupIfThenElse 
762   = do { rebind <- xoptM Opt_RebindableSyntax
763        ; if not rebind 
764          then return (Nothing, emptyFVs)
765          else do { ite <- lookupOccRn (mkVarUnqual (fsLit "ifThenElse"))
766                  ; return (Just (HsVar ite), unitFV ite) } }
767
768 lookupSyntaxName :: Name                                -- The standard name
769                  -> RnM (SyntaxExpr Name, FreeVars)     -- Possibly a non-standard name
770 lookupSyntaxName std_name
771   = xoptM Opt_RebindableSyntax          `thenM` \ rebindable_on -> 
772     if not rebindable_on then normal_case 
773     else
774         -- Get the similarly named thing from the local environment
775     lookupOccRn (mkRdrUnqual (nameOccName std_name)) `thenM` \ usr_name ->
776     return (HsVar usr_name, unitFV usr_name)
777   where
778     normal_case = return (HsVar std_name, emptyFVs)
779
780 lookupSyntaxTable :: [Name]                             -- Standard names
781                   -> RnM (SyntaxTable Name, FreeVars)   -- See comments with HsExpr.ReboundNames
782 lookupSyntaxTable std_names
783   = xoptM Opt_RebindableSyntax          `thenM` \ rebindable_on -> 
784     if not rebindable_on then normal_case 
785     else
786         -- Get the similarly named thing from the local environment
787     mapM (lookupOccRn . mkRdrUnqual . nameOccName) std_names    `thenM` \ usr_names ->
788
789     return (std_names `zip` map HsVar usr_names, mkFVs usr_names)
790   where
791     normal_case = return (std_names `zip` map HsVar std_names, emptyFVs)
792 \end{code}
793
794
795 %*********************************************************
796 %*                                                      *
797 \subsection{Binding}
798 %*                                                      *
799 %*********************************************************
800
801 \begin{code}
802 newLocalBndrRn :: Located RdrName -> RnM Name
803 -- Used for non-top-level binders.  These should
804 -- never be qualified.
805 newLocalBndrRn (L loc rdr_name)
806   | Just name <- isExact_maybe rdr_name 
807   = return name -- This happens in code generated by Template Haskell
808                 -- although I'm not sure why. Perhpas it's the call
809                 -- in RnPat.newName LetMk?
810   | otherwise
811   = do { unless (isUnqual rdr_name)
812                 (addErrAt loc (badQualBndrErr rdr_name))
813        ; uniq <- newUnique
814        ; return (mkInternalName uniq (rdrNameOcc rdr_name) loc) }
815
816 newLocalBndrsRn :: [Located RdrName] -> RnM [Name]
817 newLocalBndrsRn = mapM newLocalBndrRn
818
819 ---------------------
820 bindLocatedLocalsRn :: [Located RdrName]
821                     -> ([Name] -> RnM a)
822                     -> RnM a
823 bindLocatedLocalsRn rdr_names_w_loc enclosed_scope
824   = do { checkDupAndShadowedRdrNames rdr_names_w_loc
825
826         -- Make fresh Names and extend the environment
827        ; names <- newLocalBndrsRn rdr_names_w_loc
828        ; bindLocalNames names (enclosed_scope names) }
829
830 bindLocalNames :: [Name] -> RnM a -> RnM a
831 bindLocalNames names enclosed_scope
832   = do { name_env <- getLocalRdrEnv
833        ; setLocalRdrEnv (extendLocalRdrEnvList name_env names)
834                         enclosed_scope }
835
836 bindLocalName :: Name -> RnM a -> RnM a
837 bindLocalName name enclosed_scope
838   = do { name_env <- getLocalRdrEnv
839        ; setLocalRdrEnv (extendLocalRdrEnv name_env name)
840                         enclosed_scope }
841
842 bindLocalNamesFV :: [Name] -> RnM (a, FreeVars) -> RnM (a, FreeVars)
843 bindLocalNamesFV names enclosed_scope
844   = do  { (result, fvs) <- bindLocalNames names enclosed_scope
845         ; return (result, delFVs names fvs) }
846
847
848 -------------------------------------
849         -- binLocalsFVRn is the same as bindLocalsRn
850         -- except that it deals with free vars
851 bindLocatedLocalsFV :: [Located RdrName] 
852                     -> ([Name] -> RnM (a,FreeVars)) -> RnM (a, FreeVars)
853 bindLocatedLocalsFV rdr_names enclosed_scope
854   = bindLocatedLocalsRn rdr_names       $ \ names ->
855     enclosed_scope names                `thenM` \ (thing, fvs) ->
856     return (thing, delFVs names fvs)
857
858 -------------------------------------
859 bindTyVarsFV ::  [LHsTyVarBndr RdrName]
860               -> ([LHsTyVarBndr Name] -> RnM (a, FreeVars))
861               -> RnM (a, FreeVars)
862 bindTyVarsFV tyvars thing_inside
863   = bindTyVarsRn tyvars $ \ tyvars' ->
864     do { (res, fvs) <- thing_inside tyvars'
865        ; return (res, delFVs (map hsLTyVarName tyvars') fvs) }
866
867 bindTyVarsRn ::  [LHsTyVarBndr RdrName]
868               -> ([LHsTyVarBndr Name] -> RnM a)
869               -> RnM a
870 -- Haskell-98 binding of type variables; e.g. within a data type decl
871 bindTyVarsRn tyvar_names enclosed_scope
872   = bindLocatedLocalsRn located_tyvars  $ \ names ->
873     do { kind_sigs_ok <- xoptM Opt_KindSignatures
874        ; unless (null kinded_tyvars || kind_sigs_ok) 
875                 (mapM_ (addErr . kindSigErr) kinded_tyvars)
876        ; enclosed_scope (zipWith replace tyvar_names names) }
877   where 
878     replace (L loc n1) n2 = L loc (replaceTyVarName n1 n2)
879     located_tyvars = hsLTyVarLocNames tyvar_names
880     kinded_tyvars  = [n | L _ (KindedTyVar n _) <- tyvar_names]
881
882 bindPatSigTyVars :: [LHsType RdrName] -> ([Name] -> RnM a) -> RnM a
883   -- Find the type variables in the pattern type 
884   -- signatures that must be brought into scope
885 bindPatSigTyVars tys thing_inside
886   = do  { scoped_tyvars <- xoptM Opt_ScopedTypeVariables
887         ; if not scoped_tyvars then 
888                 thing_inside []
889           else 
890     do  { name_env <- getLocalRdrEnv
891         ; let locd_tvs  = [ tv | ty <- tys
892                                , tv <- extractHsTyRdrTyVars ty
893                                , not (unLoc tv `elemLocalRdrEnv` name_env) ]
894               nubbed_tvs = nubBy eqLocated locd_tvs
895                 -- The 'nub' is important.  For example:
896                 --      f (x :: t) (y :: t) = ....
897                 -- We don't want to complain about binding t twice!
898
899         ; bindLocatedLocalsRn nubbed_tvs thing_inside }}
900
901 bindPatSigTyVarsFV :: [LHsType RdrName]
902                    -> RnM (a, FreeVars)
903                    -> RnM (a, FreeVars)
904 bindPatSigTyVarsFV tys thing_inside
905   = bindPatSigTyVars tys        $ \ tvs ->
906     thing_inside                `thenM` \ (result,fvs) ->
907     return (result, fvs `delListFromNameSet` tvs)
908
909 bindSigTyVarsFV :: [Name]
910                 -> RnM (a, FreeVars)
911                 -> RnM (a, FreeVars)
912 bindSigTyVarsFV tvs thing_inside
913   = do  { scoped_tyvars <- xoptM Opt_ScopedTypeVariables
914         ; if not scoped_tyvars then 
915                 thing_inside 
916           else
917                 bindLocalNamesFV tvs thing_inside }
918
919 extendTyVarEnvFVRn :: [Name] -> RnM (a, FreeVars) -> RnM (a, FreeVars)
920         -- This function is used only in rnSourceDecl on InstDecl
921 extendTyVarEnvFVRn tyvars thing_inside = bindLocalNamesFV tyvars thing_inside
922
923 -------------------------------------
924 checkDupRdrNames :: [Located RdrName] -> RnM ()
925 checkDupRdrNames rdr_names_w_loc
926   =     -- Check for duplicated names in a binding group
927     mapM_ (dupNamesErr getLoc) dups
928   where
929     (_, dups) = removeDups (\n1 n2 -> unLoc n1 `compare` unLoc n2) rdr_names_w_loc
930
931 checkDupNames :: [Name] -> RnM ()
932 checkDupNames names
933   =     -- Check for duplicated names in a binding group
934     mapM_ (dupNamesErr nameSrcSpan) dups
935   where
936     (_, dups) = removeDups (\n1 n2 -> nameOccName n1 `compare` nameOccName n2) names
937
938 ---------------------
939 checkDupAndShadowedRdrNames :: [Located RdrName] -> RnM ()
940 checkDupAndShadowedRdrNames loc_rdr_names
941   = do  { checkDupRdrNames loc_rdr_names
942         ; envs <- getRdrEnvs
943         ; checkShadowedOccs envs loc_occs }
944   where
945     loc_occs = [(loc,rdrNameOcc rdr) | L loc rdr <- loc_rdr_names]
946
947 checkDupAndShadowedNames :: (GlobalRdrEnv, LocalRdrEnv) -> [Name] -> RnM ()
948 checkDupAndShadowedNames envs names
949   = do { checkDupNames names
950        ; checkShadowedOccs envs loc_occs }
951   where
952     loc_occs = [(nameSrcSpan name, nameOccName name) | name <- names]
953
954 -------------------------------------
955 checkShadowedOccs :: (GlobalRdrEnv, LocalRdrEnv) -> [(SrcSpan,OccName)] -> RnM ()
956 checkShadowedOccs (global_env,local_env) loc_occs
957   = ifDOptM Opt_WarnNameShadowing $ 
958     do  { traceRn (text "shadow" <+> ppr loc_occs)
959         ; mapM_ check_shadow loc_occs }
960   where
961     check_shadow (loc, occ)
962         | startsWithUnderscore occ = return ()  -- Do not report shadowing for "_x"
963                                                 -- See Trac #3262
964         | Just n <- mb_local = complain [ptext (sLit "bound at") <+> ppr (nameSrcLoc n)]
965         | otherwise = do { gres' <- filterM is_shadowed_gre gres
966                          ; complain (map pprNameProvenance gres') }
967         where
968           complain []      = return ()
969           complain pp_locs = addWarnAt loc (shadowedNameWarn occ pp_locs)
970           mb_local = lookupLocalRdrOcc local_env occ
971           gres     = lookupGRE_RdrName (mkRdrUnqual occ) global_env
972                 -- Make an Unqualified RdrName and look that up, so that
973                 -- we don't find any GREs that are in scope qualified-only
974
975     is_shadowed_gre :: GlobalRdrElt -> RnM Bool 
976         -- Returns False for record selectors that are shadowed, when
977         -- punning or wild-cards are on (cf Trac #2723)
978     is_shadowed_gre gre@(GRE { gre_par = ParentIs _ })
979         = do { dflags <- getDOpts
980              ; if (xopt Opt_RecordPuns dflags || xopt Opt_RecordWildCards dflags) 
981                then do { is_fld <- is_rec_fld gre; return (not is_fld) }
982                else return True }
983     is_shadowed_gre _other = return True
984
985     is_rec_fld gre      -- Return True for record selector ids
986         | isLocalGRE gre = do { RecFields _ fld_set <- getRecFieldEnv
987                               ; return (gre_name gre `elemNameSet` fld_set) }
988         | otherwise      = do { sel_id <- tcLookupField (gre_name gre)
989                               ; return (isRecordSelector sel_id) }
990 \end{code}
991
992
993 %************************************************************************
994 %*                                                                      *
995                What to do when a lookup fails
996 %*                                                                      *
997 %************************************************************************
998
999 \begin{code}
1000 data WhereLooking = WL_Any        -- Any binding
1001                   | WL_Global     -- Any top-level binding (local or imported)
1002                   | WL_LocalTop   -- Any top-level binding in this module
1003
1004 unboundName :: WhereLooking -> RdrName -> RnM Name
1005 unboundName where_look rdr_name
1006   = do  { show_helpful_errors <- doptM Opt_HelpfulErrors
1007         ; let err = unknownNameErr rdr_name
1008         ; if not show_helpful_errors
1009           then addErr err
1010           else do { extra_err <- unknownNameSuggestErr where_look rdr_name
1011                   ; addErr (err $$ extra_err) }
1012
1013         ; env <- getGlobalRdrEnv;
1014         ; traceRn (vcat [unknownNameErr rdr_name, 
1015                          ptext (sLit "Global envt is:"),
1016                          nest 3 (pprGlobalRdrEnv env)])
1017
1018         ; return (mkUnboundName rdr_name) }
1019
1020 unknownNameErr :: RdrName -> SDoc
1021 unknownNameErr rdr_name
1022   = vcat [ hang (ptext (sLit "Not in scope:")) 
1023               2 (pprNonVarNameSpace (occNameSpace (rdrNameOcc rdr_name))
1024                           <+> quotes (ppr rdr_name))
1025          , extra ]
1026   where
1027     extra | rdr_name == forall_tv_RDR = perhapsForallMsg
1028           | otherwise                 = empty
1029
1030 type HowInScope = Either SrcSpan ImpDeclSpec
1031      -- Left loc    =>  locally bound at loc
1032      -- Right ispec =>  imported as specified by ispec
1033
1034 unknownNameSuggestErr :: WhereLooking -> RdrName -> RnM SDoc
1035 unknownNameSuggestErr where_look tried_rdr_name
1036   = do { local_env <- getLocalRdrEnv
1037        ; global_env <- getGlobalRdrEnv
1038
1039        ; let all_possibilities :: [(String, (RdrName, HowInScope))]
1040              all_possibilities
1041                 =  [ (showSDoc (ppr r), (r, Left loc))
1042                    | (r,loc) <- local_possibilities local_env ]
1043                 ++ [ (showSDoc (ppr r), rp) | (r,rp) <- global_possibilities global_env ]
1044
1045              suggest = fuzzyLookup (showSDoc (ppr tried_rdr_name)) all_possibilities
1046              perhaps = ptext (sLit "Perhaps you meant")
1047              extra_err = case suggest of
1048                            []  -> empty
1049                            [p] -> perhaps <+> pp_item p
1050                            ps  -> sep [ perhaps <+> ptext (sLit "one of these:")
1051                                       , nest 2 (pprWithCommas pp_item ps) ]
1052        ; return extra_err }
1053   where
1054     pp_item :: (RdrName, HowInScope) -> SDoc
1055     pp_item (rdr, Left loc) = quotes (ppr rdr) <+>   -- Locally defined
1056                               parens (ptext (sLit "line") <+> int (srcSpanStartLine loc))
1057     pp_item (rdr, Right is) = quotes (ppr rdr) <+>   -- Imported
1058                               parens (ptext (sLit "imported from") <+> ppr (is_mod is))
1059
1060     tried_occ     = rdrNameOcc tried_rdr_name
1061     tried_is_sym  = isSymOcc tried_occ
1062     tried_ns      = occNameSpace tried_occ
1063     tried_is_qual = isQual tried_rdr_name
1064
1065     correct_name_space occ =  occNameSpace occ == tried_ns
1066                            && isSymOcc occ == tried_is_sym
1067         -- Treat operator and non-operators as non-matching
1068         -- This heuristic avoids things like
1069         --      Not in scope 'f'; perhaps you meant '+' (from Prelude)
1070
1071     local_ok = case where_look of { WL_Any -> True; _ -> False }
1072     local_possibilities :: LocalRdrEnv -> [(RdrName, SrcSpan)]
1073     local_possibilities env
1074       | tried_is_qual = []
1075       | not local_ok  = []
1076       | otherwise     = [ (mkRdrUnqual occ, nameSrcSpan name)
1077                         | name <- occEnvElts env
1078                         , let occ = nameOccName name
1079                         , correct_name_space occ]
1080
1081     gre_ok :: GlobalRdrElt -> Bool
1082     gre_ok = case where_look of
1083                    WL_LocalTop -> isLocalGRE
1084                    _           -> \_ -> True
1085
1086     global_possibilities :: GlobalRdrEnv -> [(RdrName, (RdrName, HowInScope))]
1087     global_possibilities global_env
1088       | tried_is_qual = [ (rdr_qual, (rdr_qual, how))
1089                         | gre <- globalRdrEnvElts global_env
1090                         , gre_ok gre
1091                         , let name = gre_name gre
1092                               occ  = nameOccName name
1093                         , correct_name_space occ
1094                         , (mod, how) <- quals_in_scope name (gre_prov gre)
1095                         , let rdr_qual = mkRdrQual mod occ ]
1096
1097       | otherwise = [ (rdr_unqual, pair)
1098                     | gre <- globalRdrEnvElts global_env
1099                     , gre_ok gre
1100                     , let name = gre_name gre
1101                           prov = gre_prov gre
1102                           occ  = nameOccName name
1103                           rdr_unqual = mkRdrUnqual occ
1104                     , correct_name_space occ
1105                     , pair <- case (unquals_in_scope name prov, quals_only occ prov) of
1106                                 (how:_, _)    -> [ (rdr_unqual, how) ]
1107                                 ([],    pr:_) -> [ pr ]  -- See Note [Only-quals]
1108                                 ([],    [])   -> [] ]
1109
1110               -- Note [Only-quals]
1111               -- The second alternative returns those names with the same
1112               -- OccName as the one we tried, but live in *qualified* imports
1113               -- e.g. if you have:
1114               --
1115               -- > import qualified Data.Map as Map
1116               -- > foo :: Map
1117               --
1118               -- then we suggest @Map.Map@.
1119
1120     --------------------
1121     unquals_in_scope :: Name -> Provenance -> [HowInScope]
1122     unquals_in_scope n LocalDef      = [ Left (nameSrcSpan n) ]
1123     unquals_in_scope _ (Imported is) = [ Right ispec
1124                                        | i <- is, let ispec = is_decl i
1125                                        , not (is_qual ispec) ]
1126
1127     --------------------
1128     quals_in_scope :: Name -> Provenance -> [(ModuleName, HowInScope)]
1129     -- Ones for which the qualified version is in scope
1130     quals_in_scope n LocalDef      = case nameModule_maybe n of
1131                                        Nothing -> []
1132                                        Just m  -> [(moduleName m, Left (nameSrcSpan n))]
1133     quals_in_scope _ (Imported is) = [ (is_as ispec, Right ispec)
1134                                      | i <- is, let ispec = is_decl i ]
1135
1136     --------------------
1137     quals_only :: OccName -> Provenance -> [(RdrName, HowInScope)]
1138     -- Ones for which *only* the qualified version is in scope
1139     quals_only _   LocalDef      = []
1140     quals_only occ (Imported is) = [ (mkRdrQual (is_as ispec) occ, Right ispec)
1141                                    | i <- is, let ispec = is_decl i, is_qual ispec ]
1142 \end{code}
1143
1144 %************************************************************************
1145 %*                                                                      *
1146 \subsection{Free variable manipulation}
1147 %*                                                                      *
1148 %************************************************************************
1149
1150 \begin{code}
1151 -- A useful utility
1152 addFvRn :: FreeVars -> RnM (thing, FreeVars) -> RnM (thing, FreeVars)
1153 addFvRn fvs1 thing_inside = do { (res, fvs2) <- thing_inside
1154                                ; return (res, fvs1 `plusFV` fvs2) }
1155
1156 mapFvRn :: (a -> RnM (b, FreeVars)) -> [a] -> RnM ([b], FreeVars)
1157 mapFvRn f xs = do stuff <- mapM f xs
1158                   case unzip stuff of
1159                       (ys, fvs_s) -> return (ys, plusFVs fvs_s)
1160
1161 mapMaybeFvRn :: (a -> RnM (b, FreeVars)) -> Maybe a -> RnM (Maybe b, FreeVars)
1162 mapMaybeFvRn _ Nothing = return (Nothing, emptyFVs)
1163 mapMaybeFvRn f (Just x) = do { (y, fvs) <- f x; return (Just y, fvs) }
1164
1165 -- because some of the rename functions are CPSed:
1166 -- maps the function across the list from left to right; 
1167 -- collects all the free vars into one set
1168 mapFvRnCPS :: (a  -> (b   -> RnM c) -> RnM c) 
1169            -> [a] -> ([b] -> RnM c) -> RnM c
1170
1171 mapFvRnCPS _ []     cont = cont []
1172 mapFvRnCPS f (x:xs) cont = f x             $ \ x' -> 
1173                            mapFvRnCPS f xs $ \ xs' ->
1174                            cont (x':xs')
1175 \end{code}
1176
1177
1178 %************************************************************************
1179 %*                                                                      *
1180 \subsection{Envt utility functions}
1181 %*                                                                      *
1182 %************************************************************************
1183
1184 \begin{code}
1185 warnUnusedTopBinds :: [GlobalRdrElt] -> RnM ()
1186 warnUnusedTopBinds gres
1187     = ifDOptM Opt_WarnUnusedBinds
1188     $ do isBoot <- tcIsHsBoot
1189          let noParent gre = case gre_par gre of
1190                             NoParent -> True
1191                             ParentIs _ -> False
1192              -- Don't warn about unused bindings with parents in
1193              -- .hs-boot files, as you are sometimes required to give
1194              -- unused bindings (trac #3449).
1195              gres' = if isBoot then filter noParent gres
1196                                else                 gres
1197          warnUnusedGREs gres'
1198
1199 warnUnusedLocalBinds, warnUnusedMatches :: [Name] -> FreeVars -> RnM ()
1200 warnUnusedLocalBinds = check_unused Opt_WarnUnusedBinds
1201 warnUnusedMatches    = check_unused Opt_WarnUnusedMatches
1202
1203 check_unused :: DynFlag -> [Name] -> FreeVars -> RnM ()
1204 check_unused flag bound_names used_names
1205  = ifDOptM flag (warnUnusedLocals (filterOut (`elemNameSet` used_names) bound_names))
1206
1207 -------------------------
1208 --      Helpers
1209 warnUnusedGREs :: [GlobalRdrElt] -> RnM ()
1210 warnUnusedGREs gres 
1211  = warnUnusedBinds [(n,p) | GRE {gre_name = n, gre_prov = p} <- gres]
1212
1213 warnUnusedLocals :: [Name] -> RnM ()
1214 warnUnusedLocals names
1215  = warnUnusedBinds [(n,LocalDef) | n<-names]
1216
1217 warnUnusedBinds :: [(Name,Provenance)] -> RnM ()
1218 warnUnusedBinds names  = mapM_ warnUnusedName (filter reportable names)
1219  where reportable (name,_) 
1220         | isWiredInName name = False    -- Don't report unused wired-in names
1221                                         -- Otherwise we get a zillion warnings
1222                                         -- from Data.Tuple
1223         | otherwise = not (startsWithUnderscore (nameOccName name))
1224
1225 -------------------------
1226
1227 warnUnusedName :: (Name, Provenance) -> RnM ()
1228 warnUnusedName (name, LocalDef)
1229   = addUnusedWarning name (nameSrcSpan name)
1230                      (ptext (sLit "Defined but not used"))
1231
1232 warnUnusedName (name, Imported is)
1233   = mapM_ warn is
1234   where
1235     warn spec = addUnusedWarning name span msg
1236         where
1237            span = importSpecLoc spec
1238            pp_mod = quotes (ppr (importSpecModule spec))
1239            msg = ptext (sLit "Imported from") <+> pp_mod <+> ptext (sLit "but not used")
1240
1241 addUnusedWarning :: Name -> SrcSpan -> SDoc -> RnM ()
1242 addUnusedWarning name span msg
1243   = addWarnAt span $
1244     sep [msg <> colon, 
1245          nest 2 $ pprNonVarNameSpace (occNameSpace (nameOccName name))
1246                         <+> quotes (ppr name)]
1247 \end{code}
1248
1249 \begin{code}
1250 addNameClashErrRn :: RdrName -> [GlobalRdrElt] -> RnM ()
1251 addNameClashErrRn rdr_name names
1252   = addErr (vcat [ptext (sLit "Ambiguous occurrence") <+> quotes (ppr rdr_name),
1253                   ptext (sLit "It could refer to") <+> vcat (msg1 : msgs)])
1254   where
1255     (np1:nps) = names
1256     msg1 = ptext  (sLit "either") <+> mk_ref np1
1257     msgs = [ptext (sLit "    or") <+> mk_ref np | np <- nps]
1258     mk_ref gre = sep [quotes (ppr (gre_name gre)) <> comma, pprNameProvenance gre]
1259
1260 shadowedNameWarn :: OccName -> [SDoc] -> SDoc
1261 shadowedNameWarn occ shadowed_locs
1262   = sep [ptext (sLit "This binding for") <+> quotes (ppr occ)
1263             <+> ptext (sLit "shadows the existing binding") <> plural shadowed_locs,
1264          nest 2 (vcat shadowed_locs)]
1265
1266 perhapsForallMsg :: SDoc
1267 perhapsForallMsg 
1268   = vcat [ ptext (sLit "Perhaps you intended to use -XExplicitForAll or similar flag")
1269          , ptext (sLit "to enable explicit-forall syntax: forall <tvs>. <type>")]
1270
1271 unknownSubordinateErr :: SDoc -> RdrName -> SDoc
1272 unknownSubordinateErr doc op    -- Doc is "method of class" or 
1273                                 -- "field of constructor"
1274   = quotes (ppr op) <+> ptext (sLit "is not a (visible)") <+> doc
1275
1276 badOrigBinding :: RdrName -> SDoc
1277 badOrigBinding name
1278   = ptext (sLit "Illegal binding of built-in syntax:") <+> ppr (rdrNameOcc name)
1279         -- The rdrNameOcc is because we don't want to print Prelude.(,)
1280
1281 dupNamesErr :: Outputable n => (n -> SrcSpan) -> [n] -> RnM ()
1282 dupNamesErr get_loc names
1283   = addErrAt big_loc $
1284     vcat [ptext (sLit "Conflicting definitions for") <+> quotes (ppr (head names)),
1285           locations]
1286   where
1287     locs      = map get_loc names
1288     big_loc   = foldr1 combineSrcSpans locs
1289     locations = ptext (sLit "Bound at:") <+> vcat (map ppr (sortLe (<=) locs))
1290
1291 kindSigErr :: Outputable a => a -> SDoc
1292 kindSigErr thing
1293   = hang (ptext (sLit "Illegal kind signature for") <+> quotes (ppr thing))
1294        2 (ptext (sLit "Perhaps you intended to use -XKindSignatures"))
1295
1296
1297 badQualBndrErr :: RdrName -> SDoc
1298 badQualBndrErr rdr_name
1299   = ptext (sLit "Qualified name in binding position:") <+> ppr rdr_name
1300
1301 opDeclErr :: RdrName -> SDoc
1302 opDeclErr n 
1303   = hang (ptext (sLit "Illegal declaration of a type or class operator") <+> quotes (ppr n))
1304        2 (ptext (sLit "Use -XTypeOperators to declare operators in type and declarations"))
1305 \end{code}