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