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