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