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