Fix Trac #3955: renamer and type variables
[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         lookupLocatedGlobalOccRn, 
12         lookupGlobalOccRn, lookupGlobalOccRn_maybe,
13         lookupLocalDataTcNames, lookupSigOccRn,
14         lookupFixityRn, lookupTyFixityRn, 
15         lookupInstDeclBndr, lookupSubBndr, lookupConstructorFields,
16         lookupSyntaxName, lookupSyntaxTable, 
17         lookupGreRn, lookupGreLocalRn, lookupGreRn_maybe,
18         getLookupOccRn, addUsedRdrNames,
19
20         newLocalBndrRn, newLocalBndrsRn, newIPNameRn,
21         bindLocalName, bindLocalNames, bindLocalNamesFV, 
22         MiniFixityEnv, emptyFsEnv, extendFsEnv, lookupFsEnv,
23         addLocalFixities,
24         bindLocatedLocalsFV, bindLocatedLocalsRn,
25         bindSigTyVarsFV, bindPatSigTyVars, bindPatSigTyVarsFV,
26         bindTyVarsRn, bindTyVarsFV, extendTyVarEnvFVRn,
27
28         checkDupRdrNames, checkDupAndShadowedRdrNames,
29         checkDupNames, checkDupAndShadowedNames, 
30         addFvRn, mapFvRn, mapMaybeFvRn, mapFvRnCPS,
31         warnUnusedMatches, warnUnusedModules, warnUnusedImports, 
32         warnUnusedTopBinds, warnUnusedLocalBinds,
33         dataTcOccs, unknownNameErr, kindSigErr, perhapsForallMsg
34     ) where
35
36 #include "HsVersions.h"
37
38 import LoadIface        ( loadInterfaceForName, loadSrcInterface )
39 import IfaceEnv         ( lookupOrig, newGlobalBinder, newIPName )
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             ( Name, nameIsLocalOrFrom, mkInternalName, isWiredInName,
48                           nameSrcLoc, nameSrcSpan, nameOccName, nameModule, isExternalName )
49 import NameSet
50 import NameEnv
51 import UniqFM
52 import DataCon          ( dataConFieldLabels )
53 import OccName
54 import Module           ( Module, ModuleName )
55 import PrelNames        ( mkUnboundName, rOOT_MAIN, iNTERACTIVE, 
56                           consDataConKey, forall_tv_RDR )
57 import Unique
58 import BasicTypes
59 import ErrUtils         ( Message )
60 import SrcLoc
61 import Outputable
62 import Util
63 import Maybes
64 import ListSetOps       ( removeDups )
65 import DynFlags
66 import FastString
67 import Control.Monad
68 import Data.List
69 import qualified Data.Set as Set
70 \end{code}
71
72 \begin{code}
73 -- XXX
74 thenM :: Monad a => a b -> (b -> a c) -> a c
75 thenM = (>>=)
76 \end{code}
77
78 %*********************************************************
79 %*                                                      *
80                 Source-code binders
81 %*                                                      *
82 %*********************************************************
83
84 \begin{code}
85 newTopSrcBinder :: Module -> Located RdrName -> RnM Name
86 newTopSrcBinder this_mod (L loc rdr_name)
87   | Just name <- isExact_maybe rdr_name
88   =     -- This is here to catch 
89         --   (a) Exact-name binders created by Template Haskell
90         --   (b) The PrelBase defn of (say) [] and similar, for which
91         --       the parser reads the special syntax and returns an Exact RdrName
92         -- We are at a binding site for the name, so check first that it 
93         -- the current module is the correct one; otherwise GHC can get
94         -- very confused indeed. This test rejects code like
95         --      data T = (,) Int Int
96         -- unless we are in GHC.Tup
97     ASSERT2( isExternalName name,  ppr name )
98     do  { unless (this_mod == nameModule name)
99                  (addErrAt loc (badOrigBinding rdr_name))
100         ; return name }
101
102
103   | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name
104   = do  { unless (rdr_mod == this_mod || rdr_mod == rOOT_MAIN)
105                  (addErrAt loc (badOrigBinding rdr_name))
106         -- When reading External Core we get Orig names as binders, 
107         -- but they should agree with the module gotten from the monad
108         --
109         -- We can get built-in syntax showing up here too, sadly.  If you type
110         --      data T = (,,,)
111         -- the constructor is parsed as a type, and then RdrHsSyn.tyConToDataCon 
112         -- uses setRdrNameSpace to make it into a data constructors.  At that point
113         -- the nice Exact name for the TyCon gets swizzled to an Orig name.
114         -- Hence the badOrigBinding error message.
115         --
116         -- Except for the ":Main.main = ..." definition inserted into 
117         -- the Main module; ugh!
118
119         -- Because of this latter case, we call newGlobalBinder with a module from 
120         -- the RdrName, not from the environment.  In principle, it'd be fine to 
121         -- have an arbitrary mixture of external core definitions in a single module,
122         -- (apart from module-initialisation issues, perhaps).
123         ; newGlobalBinder rdr_mod rdr_occ loc }
124                 --TODO, should pass the whole span
125
126   | otherwise
127   = do  { unless (not (isQual rdr_name))
128                  (addErrAt loc (badQualBndrErr rdr_name))
129                 -- Binders should not be qualified; if they are, and with a different
130                 -- module name, we we get a confusing "M.T is not in scope" error later
131
132         ; stage <- getStage
133         ; if isBrackStage stage then
134                 -- We are inside a TH bracket, so make an *Internal* name
135                 -- See Note [Top-level Names in Template Haskell decl quotes] in RnNames
136              do { uniq <- newUnique
137                 ; return (mkInternalName uniq (rdrNameOcc rdr_name) loc) } 
138           else  
139                 -- Normal case
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 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 <- doptM 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   = getLocalRdrEnv                      `thenM` \ local_env ->
363     case lookupLocalRdrEnv local_env rdr_name of
364           Just name -> return name
365           Nothing   -> lookupGlobalOccRn rdr_name
366
367 lookupLocatedGlobalOccRn :: Located RdrName -> RnM (Located Name)
368 lookupLocatedGlobalOccRn = wrapLocM lookupGlobalOccRn
369
370 lookupGlobalOccRn :: RdrName -> RnM Name
371 -- lookupGlobalOccRn is like lookupOccRn, except that it looks in the global 
372 -- environment.  Adds an error message if the RdrName is not in scope.
373 -- Also has a special case for GHCi.
374
375 lookupGlobalOccRn rdr_name
376   = do { -- First look up the name in the normal environment.
377          mb_name <- lookupGlobalOccRn_maybe rdr_name
378        ; case mb_name of {
379                 Just n  -> return n ;
380                 Nothing -> do
381
382        { -- We allow qualified names on the command line to refer to 
383          --  *any* name exported by any module in scope, just as if there
384          -- was an "import qualified M" declaration for every module.
385          allow_qual <- doptM Opt_ImplicitImportQualified
386        ; mod <- getModule
387                -- This test is not expensive,
388                -- and only happens for failed lookups
389        ; if isQual rdr_name && allow_qual && mod == iNTERACTIVE
390          then lookupQualifiedName rdr_name
391          else unboundName 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 unboundName :: RdrName -> RnM Name
411 unboundName rdr_name 
412   = do  { addErr (unknownNameErr rdr_name)
413         ; env <- getGlobalRdrEnv;
414         ; traceRn (vcat [unknownNameErr rdr_name, 
415                          ptext (sLit "Global envt is:"),
416                          nest 3 (pprGlobalRdrEnv env)])
417         ; return (mkUnboundName rdr_name) }
418
419 --------------------------------------------------
420 --      Lookup in the Global RdrEnv of the module
421 --------------------------------------------------
422
423 lookupGreRn_maybe :: RdrName -> RnM (Maybe GlobalRdrElt)
424 -- Just look up the RdrName in the GlobalRdrEnv
425 lookupGreRn_maybe rdr_name 
426   = lookupGreRn_help rdr_name (lookupGRE_RdrName rdr_name)
427
428 lookupGreRn :: RdrName -> RnM GlobalRdrElt
429 -- If not found, add error message, and return a fake GRE
430 lookupGreRn rdr_name 
431   = do  { mb_gre <- lookupGreRn_maybe rdr_name
432         ; case mb_gre of {
433             Just gre -> return gre ;
434             Nothing  -> do
435         { traceRn $ text "lookupGreRn"
436         ; name <- unboundName rdr_name
437         ; return (GRE { gre_name = name, gre_par = NoParent,
438                         gre_prov = LocalDef }) }}}
439
440 lookupGreLocalRn :: RdrName -> RnM (Maybe GlobalRdrElt)
441 -- Similar, but restricted to locally-defined things
442 lookupGreLocalRn rdr_name 
443   = lookupGreRn_help rdr_name lookup_fn
444   where
445     lookup_fn env = filter isLocalGRE (lookupGRE_RdrName rdr_name env)
446
447 lookupGreRn_help :: RdrName                     -- Only used in error message
448                  -> (GlobalRdrEnv -> [GlobalRdrElt])    -- Lookup function
449                  -> RnM (Maybe GlobalRdrElt)
450 -- Checks for exactly one match; reports deprecations
451 -- Returns Nothing, without error, if too few
452 lookupGreRn_help rdr_name lookup 
453   = do  { env <- getGlobalRdrEnv
454         ; case lookup env of
455             []    -> return Nothing
456             [gre] -> do { addUsedRdrName gre rdr_name
457                         ; return (Just gre) }
458             gres  -> do { addNameClashErrRn rdr_name gres
459                         ; return (Just (head gres)) } }
460
461 addUsedRdrName :: GlobalRdrElt -> RdrName -> RnM ()
462 -- Record usage of imported RdrNames
463 addUsedRdrName gre rdr
464   | isLocalGRE gre = return ()
465   | otherwise      = do { env <- getGblEnv
466                         ; updMutVar (tcg_used_rdrnames env)
467                                     (\s -> Set.insert rdr s) }
468
469 addUsedRdrNames :: [RdrName] -> RnM ()
470 -- Record used sub-binders
471 -- We don't check for imported-ness here, because it's inconvenient
472 -- and not stritly necessary.
473 addUsedRdrNames rdrs
474   = do { env <- getGblEnv
475        ; updMutVar (tcg_used_rdrnames env)
476                    (\s -> foldr Set.insert s rdrs) }
477
478 ------------------------------
479 --      GHCi support
480 ------------------------------
481
482 -- A qualified name on the command line can refer to any module at all: we
483 -- try to load the interface if we don't already have it.
484 lookupQualifiedName :: RdrName -> RnM Name
485 lookupQualifiedName rdr_name
486   | Just (mod,occ) <- isQual_maybe rdr_name
487    -- Note: we want to behave as we would for a source file import here,
488    -- and respect hiddenness of modules/packages, hence loadSrcInterface.
489    = loadSrcInterface doc mod False Nothing     `thenM` \ iface ->
490
491    case  [ (mod,occ) | 
492            (mod,avails) <- mi_exports iface,
493            avail        <- avails,
494            name         <- availNames avail,
495            name == occ ] of
496       ((mod,occ):ns) -> ASSERT (null ns) 
497                         lookupOrig mod occ
498       _ -> unboundName rdr_name
499
500   | otherwise
501   = pprPanic "RnEnv.lookupQualifiedName" (ppr rdr_name)
502   where
503     doc = ptext (sLit "Need to find") <+> ppr rdr_name
504 \end{code}
505
506 lookupSigOccRn is used for type signatures and pragmas
507 Is this valid?
508   module A
509         import M( f )
510         f :: Int -> Int
511         f x = x
512 It's clear that the 'f' in the signature must refer to A.f
513 The Haskell98 report does not stipulate this, but it will!
514 So we must treat the 'f' in the signature in the same way
515 as the binding occurrence of 'f', using lookupBndrRn
516
517 However, consider this case:
518         import M( f )
519         f :: Int -> Int
520         g x = x
521 We don't want to say 'f' is out of scope; instead, we want to
522 return the imported 'f', so that later on the reanamer will
523 correctly report "misplaced type sig".
524
525 \begin{code}
526 lookupSigOccRn :: Maybe NameSet    -- Just ns => source file; these are the binders
527                                    --            in the same group
528                                    -- Nothing => hs-boot file; signatures without 
529                                    --            binders are expected
530                -> Sig RdrName
531                -> Located RdrName -> RnM (Located Name)
532 lookupSigOccRn mb_bound_names sig
533   = wrapLocM $ \ rdr_name -> 
534     do { mb_name <- lookupBindGroupOcc mb_bound_names (hsSigDoc sig) rdr_name
535        ; case mb_name of
536            Left err   -> do { addErr err; return (mkUnboundName rdr_name) }
537            Right name -> return name }
538
539 lookupBindGroupOcc :: Maybe NameSet  -- Just ns => source file; these are the binders
540                                      --                  in the same group
541                                      -- Nothing => hs-boot file; signatures without 
542                                      --                  binders are expected
543                    -> SDoc
544                    -> RdrName -> RnM (Either Message Name)
545 -- Looks up the RdrName, expecting it to resolve to one of the 
546 -- bound names passed in.  If not, return an appropriate error message
547 lookupBindGroupOcc mb_bound_names what rdr_name
548   = do  { local_env <- getLocalRdrEnv
549         ; case lookupLocalRdrEnv local_env rdr_name of 
550             Just n  -> check_local_name n
551             Nothing -> do       -- Not defined in a nested scope
552
553         { env <- getGlobalRdrEnv 
554         ; let gres = lookupGlobalRdrEnv env (rdrNameOcc rdr_name)
555         ; case (filter isLocalGRE gres) of
556             (gre:_) -> check_local_name (gre_name gre)
557                         -- If there is more than one local GRE for the 
558                         -- same OccName, that will be reported separately
559             [] | null gres -> bale_out_with empty
560                | otherwise -> bale_out_with import_msg
561         }}
562     where
563       check_local_name name     -- The name is in scope, and not imported
564           = case mb_bound_names of
565                   Just bound_names | not (name `elemNameSet` bound_names)
566                                    -> bale_out_with local_msg
567                   _other -> return (Right name)
568
569       bale_out_with msg 
570         = return (Left (sep [ ptext (sLit "The") <+> what
571                                 <+> ptext (sLit "for") <+> quotes (ppr rdr_name)
572                            , nest 2 $ ptext (sLit "lacks an accompanying binding")]
573                        $$ nest 2 msg))
574
575       local_msg = parens $ ptext (sLit "The")  <+> what <+> ptext (sLit "must be given where")
576                            <+> quotes (ppr rdr_name) <+> ptext (sLit "is declared")
577
578       import_msg = parens $ ptext (sLit "You cannot give a") <+> what
579                           <+> ptext (sLit "for an imported value")
580
581 ---------------
582 lookupLocalDataTcNames :: NameSet -> SDoc -> RdrName -> RnM [Name]
583 -- GHC extension: look up both the tycon and data con 
584 -- for con-like things
585 -- Complain if neither is in scope
586 lookupLocalDataTcNames bound_names what rdr_name
587   | Just n <- isExact_maybe rdr_name    
588         -- Special case for (:), which doesn't get into the GlobalRdrEnv
589   = return [n]  -- For this we don't need to try the tycon too
590   | otherwise
591   = do  { mb_gres <- mapM (lookupBindGroupOcc (Just bound_names) what)
592                           (dataTcOccs rdr_name)
593         ; let (errs, names) = splitEithers mb_gres
594         ; when (null names) (addErr (head errs))        -- Bleat about one only
595         ; return names }
596
597 dataTcOccs :: RdrName -> [RdrName]
598 -- If the input is a data constructor, return both it and a type
599 -- constructor.  This is useful when we aren't sure which we are
600 -- looking at.
601 dataTcOccs rdr_name
602   | Just n <- isExact_maybe rdr_name            -- Ghastly special case
603   , n `hasKey` consDataConKey = [rdr_name]      -- see note below
604   | isDataOcc occ             = [rdr_name, rdr_name_tc]
605   | otherwise                 = [rdr_name]
606   where    
607     occ         = rdrNameOcc rdr_name
608     rdr_name_tc = setRdrNameSpace rdr_name tcName
609
610 -- If the user typed "[]" or "(,,)", we'll generate an Exact RdrName,
611 -- and setRdrNameSpace generates an Orig, which is fine
612 -- But it's not fine for (:), because there *is* no corresponding type
613 -- constructor.  If we generate an Orig tycon for GHC.Base.(:), it'll
614 -- appear to be in scope (because Orig's simply allocate a new name-cache
615 -- entry) and then we get an error when we use dataTcOccs in 
616 -- TcRnDriver.tcRnGetInfo.  Large sigh.
617 \end{code}
618
619
620 %*********************************************************
621 %*                                                      *
622                 Fixities
623 %*                                                      *
624 %*********************************************************
625
626 \begin{code}
627 --------------------------------
628 type FastStringEnv a = UniqFM a         -- Keyed by FastString
629
630
631 emptyFsEnv  :: FastStringEnv a
632 lookupFsEnv :: FastStringEnv a -> FastString -> Maybe a
633 extendFsEnv :: FastStringEnv a -> FastString -> a -> FastStringEnv a
634
635 emptyFsEnv  = emptyUFM
636 lookupFsEnv = lookupUFM
637 extendFsEnv = addToUFM
638
639 --------------------------------
640 type MiniFixityEnv = FastStringEnv (Located Fixity)
641         -- Mini fixity env for the names we're about 
642         -- to bind, in a single binding group
643         --
644         -- It is keyed by the *FastString*, not the *OccName*, because
645         -- the single fixity decl       infix 3 T
646         -- affects both the data constructor T and the type constrctor T
647         --
648         -- We keep the location so that if we find
649         -- a duplicate, we can report it sensibly
650
651 --------------------------------
652 -- Used for nested fixity decls to bind names along with their fixities.
653 -- the fixities are given as a UFM from an OccName's FastString to a fixity decl
654
655 addLocalFixities :: MiniFixityEnv -> [Name] -> RnM a -> RnM a
656 addLocalFixities mini_fix_env names thing_inside
657   = extendFixityEnv (mapCatMaybes find_fixity names) thing_inside
658   where
659     find_fixity name 
660       = case lookupFsEnv mini_fix_env (occNameFS occ) of
661           Just (L _ fix) -> Just (name, FixItem occ fix)
662           Nothing        -> Nothing
663       where
664         occ = nameOccName name
665 \end{code}
666
667 --------------------------------
668 lookupFixity is a bit strange.  
669
670 * Nested local fixity decls are put in the local fixity env, which we
671   find with getFixtyEnv
672
673 * Imported fixities are found in the HIT or PIT
674
675 * Top-level fixity decls in this module may be for Names that are
676     either  Global         (constructors, class operations)
677     or      Local/Exported (everything else)
678   (See notes with RnNames.getLocalDeclBinders for why we have this split.)
679   We put them all in the local fixity environment
680
681 \begin{code}
682 lookupFixityRn :: Name -> RnM Fixity
683 lookupFixityRn name
684   = getModule                           `thenM` \ this_mod -> 
685     if nameIsLocalOrFrom this_mod name
686     then do     -- It's defined in this module
687       local_fix_env <- getFixityEnv             
688       traceRn (text "lookupFixityRn: looking up name in local environment:" <+> 
689                vcat [ppr name, ppr local_fix_env])
690       return $ lookupFixity local_fix_env name
691     else        -- It's imported
692       -- For imported names, we have to get their fixities by doing a
693       -- loadInterfaceForName, and consulting the Ifaces that comes back
694       -- from that, because the interface file for the Name might not
695       -- have been loaded yet.  Why not?  Suppose you import module A,
696       -- which exports a function 'f', thus;
697       --        module CurrentModule where
698       --          import A( f )
699       --        module A( f ) where
700       --          import B( f )
701       -- Then B isn't loaded right away (after all, it's possible that
702       -- nothing from B will be used).  When we come across a use of
703       -- 'f', we need to know its fixity, and it's then, and only
704       -- then, that we load B.hi.  That is what's happening here.
705       --
706       -- loadInterfaceForName will find B.hi even if B is a hidden module,
707       -- and that's what we want.
708         loadInterfaceForName doc name   `thenM` \ iface -> do {
709           traceRn (text "lookupFixityRn: looking up name in iface cache and found:" <+> 
710                    vcat [ppr name, ppr $ mi_fix_fn iface (nameOccName name)]);
711            return (mi_fix_fn iface (nameOccName name))
712                                                            }
713   where
714     doc = ptext (sLit "Checking fixity for") <+> ppr name
715
716 ---------------
717 lookupTyFixityRn :: Located Name -> RnM Fixity
718 lookupTyFixityRn (L _ n) = lookupFixityRn n
719
720 \end{code}
721
722 %************************************************************************
723 %*                                                                      *
724                         Rebindable names
725         Dealing with rebindable syntax is driven by the 
726         Opt_NoImplicitPrelude dynamic flag.
727
728         In "deriving" code we don't want to use rebindable syntax
729         so we switch off the flag locally
730
731 %*                                                                      *
732 %************************************************************************
733
734 Haskell 98 says that when you say "3" you get the "fromInteger" from the
735 Standard Prelude, regardless of what is in scope.   However, to experiment
736 with having a language that is less coupled to the standard prelude, we're
737 trying a non-standard extension that instead gives you whatever "Prelude.fromInteger"
738 happens to be in scope.  Then you can
739         import Prelude ()
740         import MyPrelude as Prelude
741 to get the desired effect.
742
743 At the moment this just happens for
744   * fromInteger, fromRational on literals (in expressions and patterns)
745   * negate (in expressions)
746   * minus  (arising from n+k patterns)
747   * "do" notation
748
749 We store the relevant Name in the HsSyn tree, in 
750   * HsIntegral/HsFractional/HsIsString
751   * NegApp
752   * NPlusKPat
753   * HsDo
754 respectively.  Initially, we just store the "standard" name (PrelNames.fromIntegralName,
755 fromRationalName etc), but the renamer changes this to the appropriate user
756 name if Opt_NoImplicitPrelude is on.  That is what lookupSyntaxName does.
757
758 We treat the orignal (standard) names as free-vars too, because the type checker
759 checks the type of the user thing against the type of the standard thing.
760
761 \begin{code}
762 lookupSyntaxName :: Name                                -- The standard name
763                  -> RnM (SyntaxExpr Name, FreeVars)     -- Possibly a non-standard name
764 lookupSyntaxName std_name
765   = doptM Opt_ImplicitPrelude           `thenM` \ implicit_prelude -> 
766     if implicit_prelude then normal_case
767     else
768         -- Get the similarly named thing from the local environment
769     lookupOccRn (mkRdrUnqual (nameOccName std_name)) `thenM` \ usr_name ->
770     return (HsVar usr_name, unitFV usr_name)
771   where
772     normal_case = return (HsVar std_name, emptyFVs)
773
774 lookupSyntaxTable :: [Name]                             -- Standard names
775                   -> RnM (SyntaxTable Name, FreeVars)   -- See comments with HsExpr.ReboundNames
776 lookupSyntaxTable std_names
777   = doptM Opt_ImplicitPrelude           `thenM` \ implicit_prelude -> 
778     if implicit_prelude then normal_case 
779     else
780         -- Get the similarly named thing from the local environment
781     mapM (lookupOccRn . mkRdrUnqual . nameOccName) std_names    `thenM` \ usr_names ->
782
783     return (std_names `zip` map HsVar usr_names, mkFVs usr_names)
784   where
785     normal_case = return (std_names `zip` map HsVar std_names, emptyFVs)
786 \end{code}
787
788
789 %*********************************************************
790 %*                                                      *
791 \subsection{Binding}
792 %*                                                      *
793 %*********************************************************
794
795 \begin{code}
796 newLocalBndrRn :: Located RdrName -> RnM Name
797 -- Used for non-top-level binders.  These should
798 -- never be qualified.
799 newLocalBndrRn (L loc rdr_name)
800   | Just name <- isExact_maybe rdr_name 
801   = return name -- This happens in code generated by Template Haskell
802                 -- although I'm not sure why. Perhpas it's the call
803                 -- in RnPat.newName LetMk?
804   | otherwise
805   = do { unless (isUnqual rdr_name)
806                 (addErrAt loc (badQualBndrErr rdr_name))
807        ; uniq <- newUnique
808        ; return (mkInternalName uniq (rdrNameOcc rdr_name) loc) }
809
810 newLocalBndrsRn :: [Located RdrName] -> RnM [Name]
811 newLocalBndrsRn = mapM newLocalBndrRn
812
813 ---------------------
814 bindLocatedLocalsRn :: [Located RdrName]
815                     -> ([Name] -> RnM a)
816                     -> RnM a
817 bindLocatedLocalsRn rdr_names_w_loc enclosed_scope
818   = do { checkDupAndShadowedRdrNames rdr_names_w_loc
819
820         -- Make fresh Names and extend the environment
821        ; names <- newLocalBndrsRn rdr_names_w_loc
822        ; bindLocalNames names (enclosed_scope names) }
823
824 bindLocalNames :: [Name] -> RnM a -> RnM a
825 bindLocalNames names enclosed_scope
826   = do { name_env <- getLocalRdrEnv
827        ; setLocalRdrEnv (extendLocalRdrEnvList name_env names)
828                         enclosed_scope }
829
830 bindLocalName :: Name -> RnM a -> RnM a
831 bindLocalName name enclosed_scope
832   = do { name_env <- getLocalRdrEnv
833        ; setLocalRdrEnv (extendLocalRdrEnv name_env name)
834                         enclosed_scope }
835
836 bindLocalNamesFV :: [Name] -> RnM (a, FreeVars) -> RnM (a, FreeVars)
837 bindLocalNamesFV names enclosed_scope
838   = do  { (result, fvs) <- bindLocalNames names enclosed_scope
839         ; return (result, delFVs names fvs) }
840
841
842 -------------------------------------
843         -- binLocalsFVRn is the same as bindLocalsRn
844         -- except that it deals with free vars
845 bindLocatedLocalsFV :: [Located RdrName] 
846                     -> ([Name] -> RnM (a,FreeVars)) -> RnM (a, FreeVars)
847 bindLocatedLocalsFV rdr_names enclosed_scope
848   = bindLocatedLocalsRn rdr_names       $ \ names ->
849     enclosed_scope names                `thenM` \ (thing, fvs) ->
850     return (thing, delFVs names fvs)
851
852 -------------------------------------
853 bindTyVarsFV ::  [LHsTyVarBndr RdrName]
854               -> ([LHsTyVarBndr Name] -> RnM (a, FreeVars))
855               -> RnM (a, FreeVars)
856 bindTyVarsFV tyvars thing_inside
857   = bindTyVarsRn tyvars $ \ tyvars' ->
858     do { (res, fvs) <- thing_inside tyvars'
859        ; return (res, delFVs (map hsLTyVarName tyvars') fvs) }
860
861 bindTyVarsRn ::  [LHsTyVarBndr RdrName]
862               -> ([LHsTyVarBndr Name] -> RnM a)
863               -> RnM a
864 -- Haskell-98 binding of type variables; e.g. within a data type decl
865 bindTyVarsRn tyvar_names enclosed_scope
866   = bindLocatedLocalsRn located_tyvars  $ \ names ->
867     do { kind_sigs_ok <- doptM Opt_KindSignatures
868        ; unless (null kinded_tyvars || kind_sigs_ok) 
869                 (mapM_ (addErr . kindSigErr) kinded_tyvars)
870        ; enclosed_scope (zipWith replace tyvar_names names) }
871   where 
872     replace (L loc n1) n2 = L loc (replaceTyVarName n1 n2)
873     located_tyvars = hsLTyVarLocNames tyvar_names
874     kinded_tyvars  = [n | L _ (KindedTyVar n _) <- tyvar_names]
875
876 bindPatSigTyVars :: [LHsType RdrName] -> ([Name] -> RnM a) -> RnM a
877   -- Find the type variables in the pattern type 
878   -- signatures that must be brought into scope
879 bindPatSigTyVars tys thing_inside
880   = do  { scoped_tyvars <- doptM Opt_ScopedTypeVariables
881         ; if not scoped_tyvars then 
882                 thing_inside []
883           else 
884     do  { name_env <- getLocalRdrEnv
885         ; let locd_tvs  = [ tv | ty <- tys
886                                , tv <- extractHsTyRdrTyVars ty
887                                , not (unLoc tv `elemLocalRdrEnv` name_env) ]
888               nubbed_tvs = nubBy eqLocated locd_tvs
889                 -- The 'nub' is important.  For example:
890                 --      f (x :: t) (y :: t) = ....
891                 -- We don't want to complain about binding t twice!
892
893         ; bindLocatedLocalsRn nubbed_tvs thing_inside }}
894
895 bindPatSigTyVarsFV :: [LHsType RdrName]
896                    -> RnM (a, FreeVars)
897                    -> RnM (a, FreeVars)
898 bindPatSigTyVarsFV tys thing_inside
899   = bindPatSigTyVars tys        $ \ tvs ->
900     thing_inside                `thenM` \ (result,fvs) ->
901     return (result, fvs `delListFromNameSet` tvs)
902
903 bindSigTyVarsFV :: [Name]
904                 -> RnM (a, FreeVars)
905                 -> RnM (a, FreeVars)
906 bindSigTyVarsFV tvs thing_inside
907   = do  { scoped_tyvars <- doptM Opt_ScopedTypeVariables
908         ; if not scoped_tyvars then 
909                 thing_inside 
910           else
911                 bindLocalNamesFV tvs thing_inside }
912
913 extendTyVarEnvFVRn :: [Name] -> RnM (a, FreeVars) -> RnM (a, FreeVars)
914         -- This function is used only in rnSourceDecl on InstDecl
915 extendTyVarEnvFVRn tyvars thing_inside = bindLocalNamesFV tyvars thing_inside
916
917 -------------------------------------
918 checkDupRdrNames :: [Located RdrName] -> RnM ()
919 checkDupRdrNames rdr_names_w_loc
920   =     -- Check for duplicated names in a binding group
921     mapM_ (dupNamesErr getLoc) dups
922   where
923     (_, dups) = removeDups (\n1 n2 -> unLoc n1 `compare` unLoc n2) rdr_names_w_loc
924
925 checkDupNames :: [Name] -> RnM ()
926 checkDupNames names
927   =     -- Check for duplicated names in a binding group
928     mapM_ (dupNamesErr nameSrcSpan) dups
929   where
930     (_, dups) = removeDups (\n1 n2 -> nameOccName n1 `compare` nameOccName n2) names
931
932 ---------------------
933 checkDupAndShadowedRdrNames :: [Located RdrName] -> RnM ()
934 checkDupAndShadowedRdrNames loc_rdr_names
935   = do  { checkDupRdrNames loc_rdr_names
936         ; envs <- getRdrEnvs
937         ; checkShadowedOccs envs loc_occs }
938   where
939     loc_occs = [(loc,rdrNameOcc rdr) | L loc rdr <- loc_rdr_names]
940
941 checkDupAndShadowedNames :: (GlobalRdrEnv, LocalRdrEnv) -> [Name] -> RnM ()
942 checkDupAndShadowedNames envs names
943   = do { checkDupNames names
944        ; checkShadowedOccs envs loc_occs }
945   where
946     loc_occs = [(nameSrcSpan name, nameOccName name) | name <- names]
947
948 -------------------------------------
949 checkShadowedOccs :: (GlobalRdrEnv, LocalRdrEnv) -> [(SrcSpan,OccName)] -> RnM ()
950 checkShadowedOccs (global_env,local_env) loc_occs
951   = ifOptM Opt_WarnNameShadowing $ 
952     do  { traceRn (text "shadow" <+> ppr loc_occs)
953         ; mapM_ check_shadow loc_occs }
954   where
955     check_shadow (loc, occ)
956         | startsWithUnderscore occ = return ()  -- Do not report shadowing for "_x"
957                                                 -- See Trac #3262
958         | Just n <- mb_local = complain [ptext (sLit "bound at") <+> ppr (nameSrcLoc n)]
959         | otherwise = do { gres' <- filterM is_shadowed_gre gres
960                          ; complain (map pprNameProvenance gres') }
961         where
962           complain []      = return ()
963           complain pp_locs = addWarnAt loc (shadowedNameWarn occ pp_locs)
964           mb_local = lookupLocalRdrOcc local_env occ
965           gres     = lookupGRE_RdrName (mkRdrUnqual occ) global_env
966                 -- Make an Unqualified RdrName and look that up, so that
967                 -- we don't find any GREs that are in scope qualified-only
968
969     is_shadowed_gre :: GlobalRdrElt -> RnM Bool 
970         -- Returns False for record selectors that are shadowed, when
971         -- punning or wild-cards are on (cf Trac #2723)
972     is_shadowed_gre gre@(GRE { gre_par = ParentIs _ })
973         = do { dflags <- getDOpts
974              ; if (dopt Opt_RecordPuns dflags || dopt Opt_RecordWildCards dflags) 
975                then do { is_fld <- is_rec_fld gre; return (not is_fld) }
976                else return True }
977     is_shadowed_gre _other = return True
978
979     is_rec_fld gre      -- Return True for record selector ids
980         | isLocalGRE gre = do { RecFields _ fld_set <- getRecFieldEnv
981                               ; return (gre_name gre `elemNameSet` fld_set) }
982         | otherwise      = do { sel_id <- tcLookupField (gre_name gre)
983                               ; return (isRecordSelector sel_id) }
984 \end{code}
985
986
987 %************************************************************************
988 %*                                                                      *
989 \subsection{Free variable manipulation}
990 %*                                                                      *
991 %************************************************************************
992
993 \begin{code}
994 -- A useful utility
995 addFvRn :: FreeVars -> RnM (thing, FreeVars) -> RnM (thing, FreeVars)
996 addFvRn fvs1 thing_inside = do { (res, fvs2) <- thing_inside
997                                ; return (res, fvs1 `plusFV` fvs2) }
998
999 mapFvRn :: (a -> RnM (b, FreeVars)) -> [a] -> RnM ([b], FreeVars)
1000 mapFvRn f xs = do stuff <- mapM f xs
1001                   case unzip stuff of
1002                       (ys, fvs_s) -> return (ys, plusFVs fvs_s)
1003
1004 mapMaybeFvRn :: (a -> RnM (b, FreeVars)) -> Maybe a -> RnM (Maybe b, FreeVars)
1005 mapMaybeFvRn _ Nothing = return (Nothing, emptyFVs)
1006 mapMaybeFvRn f (Just x) = do { (y, fvs) <- f x; return (Just y, fvs) }
1007
1008 -- because some of the rename functions are CPSed:
1009 -- maps the function across the list from left to right; 
1010 -- collects all the free vars into one set
1011 mapFvRnCPS :: (a  -> (b   -> RnM c) -> RnM c) 
1012            -> [a] -> ([b] -> RnM c) -> RnM c
1013
1014 mapFvRnCPS _ []     cont = cont []
1015 mapFvRnCPS f (x:xs) cont = f x             $ \ x' -> 
1016                            mapFvRnCPS f xs $ \ xs' ->
1017                            cont (x':xs')
1018 \end{code}
1019
1020
1021 %************************************************************************
1022 %*                                                                      *
1023 \subsection{Envt utility functions}
1024 %*                                                                      *
1025 %************************************************************************
1026
1027 \begin{code}
1028 warnUnusedModules :: [(ModuleName,SrcSpan)] -> RnM ()
1029 warnUnusedModules mods
1030   = ifOptM Opt_WarnUnusedImports (mapM_ bleat mods)
1031   where
1032     bleat (mod,loc) = addWarnAt loc (mk_warn mod)
1033     mk_warn m = vcat [ptext (sLit "Module") <+> quotes (ppr m)
1034                         <+> text "is imported, but nothing from it is used,",
1035                       nest 2 (ptext (sLit "except perhaps instances visible in") 
1036                         <+> quotes (ppr m)),
1037                       ptext (sLit "To suppress this warning, use:") 
1038                         <+> ptext (sLit "import") <+> ppr m <> parens empty ]
1039
1040
1041 warnUnusedImports, warnUnusedTopBinds :: [GlobalRdrElt] -> RnM ()
1042 warnUnusedImports gres  = ifOptM Opt_WarnUnusedImports (warnUnusedGREs gres)
1043 warnUnusedTopBinds gres = ifOptM Opt_WarnUnusedBinds   (warnUnusedGREs gres)
1044
1045 warnUnusedLocalBinds, warnUnusedMatches :: [Name] -> FreeVars -> RnM ()
1046 warnUnusedLocalBinds = check_unused Opt_WarnUnusedBinds
1047 warnUnusedMatches    = check_unused Opt_WarnUnusedMatches
1048
1049 check_unused :: DynFlag -> [Name] -> FreeVars -> RnM ()
1050 check_unused flag bound_names used_names
1051  = ifOptM flag (warnUnusedLocals (filterOut (`elemNameSet` used_names) bound_names))
1052
1053 -------------------------
1054 --      Helpers
1055 warnUnusedGREs :: [GlobalRdrElt] -> RnM ()
1056 warnUnusedGREs gres 
1057  = warnUnusedBinds [(n,p) | GRE {gre_name = n, gre_prov = p} <- gres]
1058
1059 warnUnusedLocals :: [Name] -> RnM ()
1060 warnUnusedLocals names
1061  = warnUnusedBinds [(n,LocalDef) | n<-names]
1062
1063 warnUnusedBinds :: [(Name,Provenance)] -> RnM ()
1064 warnUnusedBinds names  = mapM_ warnUnusedName (filter reportable names)
1065  where reportable (name,_) 
1066         | isWiredInName name = False    -- Don't report unused wired-in names
1067                                         -- Otherwise we get a zillion warnings
1068                                         -- from Data.Tuple
1069         | otherwise = not (startsWithUnderscore (nameOccName name))
1070
1071 -------------------------
1072
1073 warnUnusedName :: (Name, Provenance) -> RnM ()
1074 warnUnusedName (name, LocalDef)
1075   = addUnusedWarning name (nameSrcSpan name)
1076                      (ptext (sLit "Defined but not used"))
1077
1078 warnUnusedName (name, Imported is)
1079   = mapM_ warn is
1080   where
1081     warn spec = addUnusedWarning name span msg
1082         where
1083            span = importSpecLoc spec
1084            pp_mod = quotes (ppr (importSpecModule spec))
1085            msg = ptext (sLit "Imported from") <+> pp_mod <+> ptext (sLit "but not used")
1086
1087 addUnusedWarning :: Name -> SrcSpan -> SDoc -> RnM ()
1088 addUnusedWarning name span msg
1089   = addWarnAt span $
1090     sep [msg <> colon, 
1091          nest 2 $ pprNonVarNameSpace (occNameSpace (nameOccName name))
1092                         <+> quotes (ppr name)]
1093 \end{code}
1094
1095 \begin{code}
1096 addNameClashErrRn :: RdrName -> [GlobalRdrElt] -> RnM ()
1097 addNameClashErrRn rdr_name names
1098   = addErr (vcat [ptext (sLit "Ambiguous occurrence") <+> quotes (ppr rdr_name),
1099                   ptext (sLit "It could refer to") <+> vcat (msg1 : msgs)])
1100   where
1101     (np1:nps) = names
1102     msg1 = ptext  (sLit "either") <+> mk_ref np1
1103     msgs = [ptext (sLit "    or") <+> mk_ref np | np <- nps]
1104     mk_ref gre = quotes (ppr (gre_name gre)) <> comma <+> pprNameProvenance gre
1105
1106 shadowedNameWarn :: OccName -> [SDoc] -> SDoc
1107 shadowedNameWarn occ shadowed_locs
1108   = sep [ptext (sLit "This binding for") <+> quotes (ppr occ)
1109             <+> ptext (sLit "shadows the existing binding") <> plural shadowed_locs,
1110          nest 2 (vcat shadowed_locs)]
1111
1112 unknownNameErr :: RdrName -> SDoc
1113 unknownNameErr rdr_name
1114   = vcat [ hang (ptext (sLit "Not in scope:")) 
1115               2 (pprNonVarNameSpace (occNameSpace (rdrNameOcc rdr_name))
1116                           <+> quotes (ppr rdr_name))
1117          , extra ]
1118   where
1119     extra | rdr_name == forall_tv_RDR = perhapsForallMsg
1120           | otherwise                 = empty
1121
1122 perhapsForallMsg :: SDoc
1123 perhapsForallMsg 
1124   = vcat [ ptext (sLit "Perhaps you intended to use -XExplicitForAll or similar flag")
1125          , ptext (sLit "to enable explicit-forall syntax: forall <tvs>. <type>")]
1126
1127 unknownSubordinateErr :: SDoc -> RdrName -> SDoc
1128 unknownSubordinateErr doc op    -- Doc is "method of class" or 
1129                                 -- "field of constructor"
1130   = quotes (ppr op) <+> ptext (sLit "is not a (visible)") <+> doc
1131
1132 badOrigBinding :: RdrName -> SDoc
1133 badOrigBinding name
1134   = ptext (sLit "Illegal binding of built-in syntax:") <+> ppr (rdrNameOcc name)
1135         -- The rdrNameOcc is because we don't want to print Prelude.(,)
1136
1137 dupNamesErr :: Outputable n => (n -> SrcSpan) -> [n] -> RnM ()
1138 dupNamesErr get_loc names
1139   = addErrAt big_loc $
1140     vcat [ptext (sLit "Conflicting definitions for") <+> quotes (ppr (head names)),
1141           locations]
1142   where
1143     locs      = map get_loc names
1144     big_loc   = foldr1 combineSrcSpans locs
1145     locations = ptext (sLit "Bound at:") <+> vcat (map ppr (sortLe (<=) locs))
1146
1147 kindSigErr :: Outputable a => a -> SDoc
1148 kindSigErr thing
1149   = hang (ptext (sLit "Illegal kind signature for") <+> quotes (ppr thing))
1150        2 (ptext (sLit "Perhaps you intended to use -XKindSignatures"))
1151
1152
1153 badQualBndrErr :: RdrName -> SDoc
1154 badQualBndrErr rdr_name
1155   = ptext (sLit "Qualified name in binding position:") <+> ppr rdr_name
1156
1157 opDeclErr :: RdrName -> SDoc
1158 opDeclErr n 
1159   = hang (ptext (sLit "Illegal declaration of a type or class operator") <+> quotes (ppr n))
1160        2 (ptext (sLit "Use -XTypeOperators to declare operators in type and declarations"))
1161 \end{code}