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