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