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