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