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