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