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