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