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