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