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