99d6a3414c32fc88a9cd63e32a06f1a8e2c1a80f
[ghc-hetmet.git] / ghc / compiler / rename / RnEnv.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section[RnEnv]{Environment manipulation for the renamer monad}
5
6 \begin{code}
7 module RnEnv ( 
8         newTopSrcBinder, 
9         lookupLocatedBndrRn, lookupBndrRn, 
10         lookupLocatedTopBndrRn, lookupTopBndrRn,
11         lookupLocatedOccRn, lookupOccRn, 
12         lookupLocatedGlobalOccRn, lookupGlobalOccRn,
13         lookupLocalDataTcNames, lookupSrcOcc_maybe,
14         lookupFixityRn, lookupTyFixityRn, lookupLocatedSigOccRn, 
15         lookupLocatedInstDeclBndr,
16         lookupSyntaxName, lookupSyntaxTable, lookupImportedName,
17
18         newLocalsRn, newIPNameRn,
19         bindLocalNames, bindLocalNamesFV,
20         bindLocatedLocalsFV, bindLocatedLocalsRn,
21         bindSigTyVarsFV, bindPatSigTyVars, bindPatSigTyVarsFV,
22         bindTyVarsRn, extendTyVarEnvFVRn,
23         bindLocalFixities,
24
25         checkDupNames, mapFvRn,
26         warnUnusedMatches, warnUnusedModules, warnUnusedImports, 
27         warnUnusedTopBinds, warnUnusedLocalBinds,
28         dataTcOccs, unknownNameErr,
29     ) where
30
31 #include "HsVersions.h"
32
33 import LoadIface        ( loadHomeInterface, loadSrcInterface )
34 import IfaceEnv         ( lookupOrig, newGlobalBinder, newIPName )
35 import HsSyn            ( FixitySig(..), HsExpr(..), SyntaxExpr, SyntaxTable,
36                           LHsTyVarBndr, LHsType, 
37                           Fixity, hsLTyVarLocNames, replaceTyVarName )
38 import RdrHsSyn         ( extractHsTyRdrTyVars )
39 import RdrName          ( RdrName, rdrNameModule, isQual, isUnqual, isOrig,
40                           mkRdrUnqual, setRdrNameSpace, rdrNameOcc,
41                           pprGlobalRdrEnv, lookupGRE_RdrName, 
42                           isExact_maybe, isSrcRdrName,
43                           GlobalRdrElt(..), GlobalRdrEnv, lookupGlobalRdrEnv, 
44                           isLocalGRE, extendLocalRdrEnv, elemLocalRdrEnv, lookupLocalRdrEnv,
45                           Provenance(..), pprNameProvenance,
46                           importSpecLoc, importSpecModule
47                         )
48 import HscTypes         ( availNames, ModIface(..), FixItem(..), lookupFixity )
49 import TcRnMonad
50 import Name             ( Name, nameIsLocalOrFrom, mkInternalName, isWiredInName,
51                           nameSrcLoc, nameOccName, nameModule, nameParent, isExternalName )
52 import NameSet
53 import OccName          ( tcName, isDataOcc, occNameFlavour, reportIfUnused )
54 import Module           ( Module )
55 import PrelNames        ( mkUnboundName, rOOT_MAIN, iNTERACTIVE, consDataConKey, hasKey )
56 import UniqSupply
57 import BasicTypes       ( IPName, mapIPName )
58 import SrcLoc           ( SrcSpan, srcSpanStart, Located(..), eqLocated, unLoc,
59                           srcLocSpan, getLoc, combineSrcSpans, srcSpanStartLine, srcSpanEndLine )
60 import Outputable
61 import Util             ( sortLe )
62 import ListSetOps       ( removeDups )
63 import List             ( nubBy )
64 import Monad            ( when )
65 import DynFlags
66 \end{code}
67
68 %*********************************************************
69 %*                                                      *
70                 Source-code binders
71 %*                                                      *
72 %*********************************************************
73
74 \begin{code}
75 newTopSrcBinder :: Module -> Maybe Name -> Located RdrName -> RnM Name
76 newTopSrcBinder this_mod mb_parent (L loc rdr_name)
77   | Just name <- isExact_maybe rdr_name
78   =     -- This is here to catch 
79         --   (a) Exact-name binders created by Template Haskell
80         --   (b) The PrelBase defn of (say) [] and similar, for which
81         --       the parser reads the special syntax and returns an Exact RdrName
82         -- We are at a binding site for the name, so check first that it 
83         -- the current module is the correct one; otherwise GHC can get
84         -- very confused indeed. This test rejects code like
85         --      data T = (,) Int Int
86         -- unless we are in GHC.Tup
87     ASSERT2( isExternalName name,  ppr name )
88     do  checkErr (this_mod == nameModule name)
89                  (badOrigBinding rdr_name)
90         returnM name
91
92
93   | isOrig rdr_name
94   = do  checkErr (rdr_mod == this_mod || rdr_mod == rOOT_MAIN)
95                  (badOrigBinding rdr_name)
96         -- When reading External Core we get Orig names as binders, 
97         -- but they should agree with the module gotten from the monad
98         --
99         -- We can get built-in syntax showing up here too, sadly.  If you type
100         --      data T = (,,,)
101         -- the constructor is parsed as a type, and then RdrHsSyn.tyConToDataCon 
102         -- uses setRdrNameSpace to make it into a data constructors.  At that point
103         -- the nice Exact name for the TyCon gets swizzled to an Orig name.
104         -- Hence the badOrigBinding error message.
105         --
106         -- Except for the ":Main.main = ..." definition inserted into 
107         -- the Main module; ugh!
108
109         -- Because of this latter case, we call newGlobalBinder with a module from 
110         -- the RdrName, not from the environment.  In principle, it'd be fine to 
111         -- have an arbitrary mixture of external core definitions in a single module,
112         -- (apart from module-initialisation issues, perhaps).
113         newGlobalBinder rdr_mod (rdrNameOcc rdr_name) mb_parent 
114                         (srcSpanStart loc) --TODO, should pass the whole span
115
116   | otherwise
117   = newGlobalBinder this_mod (rdrNameOcc rdr_name) mb_parent (srcSpanStart loc)
118   where
119     rdr_mod  = rdrNameModule rdr_name
120 \end{code}
121
122 %*********************************************************
123 %*                                                      *
124         Source code occurrences
125 %*                                                      *
126 %*********************************************************
127
128 Looking up a name in the RnEnv.
129
130 \begin{code}
131 lookupLocatedBndrRn :: Located RdrName -> RnM (Located Name)
132 lookupLocatedBndrRn = wrapLocM lookupBndrRn
133
134 lookupBndrRn :: RdrName -> RnM Name
135 -- NOTE: assumes that the SrcSpan of the binder has already been setSrcSpan'd
136 lookupBndrRn rdr_name
137   = getLocalRdrEnv              `thenM` \ local_env ->
138     case lookupLocalRdrEnv local_env rdr_name of 
139           Just name -> returnM name
140           Nothing   -> lookupTopBndrRn rdr_name
141
142 lookupLocatedTopBndrRn :: Located RdrName -> RnM (Located Name)
143 lookupLocatedTopBndrRn = wrapLocM lookupTopBndrRn
144
145 lookupTopBndrRn :: RdrName -> RnM Name
146 -- Look up a top-level source-code binder.   We may be looking up an unqualified 'f',
147 -- and there may be several imported 'f's too, which must not confuse us.
148 -- For example, this is OK:
149 --      import Foo( f )
150 --      infix 9 f       -- The 'f' here does not need to be qualified
151 --      f x = x         -- Nor here, of course
152 -- So we have to filter out the non-local ones.
153 --
154 -- A separate function (importsFromLocalDecls) reports duplicate top level
155 -- decls, so here it's safe just to choose an arbitrary one.
156 --
157 -- There should never be a qualified name in a binding position in Haskell,
158 -- but there can be if we have read in an external-Core file.
159 -- The Haskell parser checks for the illegal qualified name in Haskell 
160 -- source files, so we don't need to do so here.
161
162 lookupTopBndrRn rdr_name
163   | Just name <- isExact_maybe rdr_name
164   = returnM name
165
166   | isOrig rdr_name     
167         -- This deals with the case of derived bindings, where
168         -- we don't bother to call newTopSrcBinder first
169         -- We assume there is no "parent" name
170   = do  { loc <- getSrcSpanM
171         ; newGlobalBinder (rdrNameModule rdr_name)
172                           (rdrNameOcc rdr_name) Nothing (srcSpanStart loc) }
173
174   | otherwise
175   = do  { mb_gre <- lookupGreLocalRn rdr_name
176         ; case mb_gre of
177                 Nothing  -> unboundName rdr_name
178                 Just gre -> returnM (gre_name gre) }
179               
180 -- lookupLocatedSigOccRn is used for type signatures and pragmas
181 -- Is this valid?
182 --   module A
183 --      import M( f )
184 --      f :: Int -> Int
185 --      f x = x
186 -- It's clear that the 'f' in the signature must refer to A.f
187 -- The Haskell98 report does not stipulate this, but it will!
188 -- So we must treat the 'f' in the signature in the same way
189 -- as the binding occurrence of 'f', using lookupBndrRn
190 lookupLocatedSigOccRn :: Located RdrName -> RnM (Located Name)
191 lookupLocatedSigOccRn = lookupLocatedBndrRn
192
193 -- lookupInstDeclBndr is used for the binders in an 
194 -- instance declaration.   Here we use the class name to
195 -- disambiguate.  
196
197 lookupLocatedInstDeclBndr :: Name -> Located RdrName -> RnM (Located Name)
198 lookupLocatedInstDeclBndr cls = wrapLocM (lookupInstDeclBndr cls)
199
200 lookupInstDeclBndr :: Name -> RdrName -> RnM Name
201 lookupInstDeclBndr cls_name rdr_name
202   | isUnqual rdr_name   -- Find all the things the rdr-name maps to
203   = do  {               -- and pick the one with the right parent name
204           let { is_op gre     = cls_name == nameParent (gre_name gre)
205               ; occ           = rdrNameOcc rdr_name
206               ; lookup_fn env = filter is_op (lookupGlobalRdrEnv env occ) }
207         ; mb_gre <- lookupGreRn_help rdr_name lookup_fn
208         ; case mb_gre of
209             Just gre -> return (gre_name gre)
210             Nothing  -> do { addErr (unknownInstBndrErr cls_name rdr_name)
211                            ; return (mkUnboundName rdr_name) } }
212
213   | otherwise   -- Occurs in derived instances, where we just
214                 -- refer directly to the right method
215   = ASSERT2( not (isQual rdr_name), ppr rdr_name )
216           -- NB: qualified names are rejected by the parser
217     lookupImportedName rdr_name
218
219 newIPNameRn :: IPName RdrName -> TcRnIf m n (IPName Name)
220 newIPNameRn ip_rdr = newIPName (mapIPName rdrNameOcc ip_rdr)
221
222 --------------------------------------------------
223 --              Occurrences
224 --------------------------------------------------
225
226 lookupLocatedOccRn :: Located RdrName -> RnM (Located Name)
227 lookupLocatedOccRn = wrapLocM lookupOccRn
228
229 -- lookupOccRn looks up an occurrence of a RdrName
230 lookupOccRn :: RdrName -> RnM Name
231 lookupOccRn rdr_name
232   = getLocalRdrEnv                      `thenM` \ local_env ->
233     case lookupLocalRdrEnv local_env rdr_name of
234           Just name -> returnM name
235           Nothing   -> lookupGlobalOccRn rdr_name
236
237 lookupLocatedGlobalOccRn :: Located RdrName -> RnM (Located Name)
238 lookupLocatedGlobalOccRn = wrapLocM lookupGlobalOccRn
239
240 lookupGlobalOccRn :: RdrName -> RnM Name
241 -- lookupGlobalOccRn is like lookupOccRn, except that it looks in the global 
242 -- environment.  It's used only for
243 --      record field names
244 --      class op names in class and instance decls
245
246 lookupGlobalOccRn rdr_name
247   | not (isSrcRdrName rdr_name)
248   = lookupImportedName rdr_name 
249
250   | otherwise
251   =     -- First look up the name in the normal environment.
252    lookupGreRn rdr_name                 `thenM` \ mb_gre ->
253    case mb_gre of {
254         Just gre -> returnM (gre_name gre) ;
255         Nothing   -> 
256
257         -- We allow qualified names on the command line to refer to 
258         --  *any* name exported by any module in scope, just as if 
259         -- there was an "import qualified M" declaration for every 
260         -- module.
261    getModule            `thenM` \ mod ->
262    if isQual rdr_name && mod == iNTERACTIVE then        
263                                         -- This test is not expensive,
264         lookupQualifiedName rdr_name    -- and only happens for failed lookups
265    else 
266         unboundName rdr_name }
267
268 lookupImportedName :: RdrName -> TcRnIf m n Name
269 -- Lookup the occurrence of an imported name
270 -- The RdrName is *always* qualified or Exact
271 -- Treat it as an original name, and conjure up the Name
272 -- Usually it's Exact or Orig, but it can be Qual if it
273 --      comes from an hi-boot file.  (This minor infelicity is 
274 --      just to reduce duplication in the parser.)
275 lookupImportedName rdr_name
276   | Just n <- isExact_maybe rdr_name 
277         -- This happens in derived code
278   = returnM n
279
280   | otherwise   -- Always Orig, even when reading a .hi-boot file
281   = ASSERT( not (isUnqual rdr_name) )
282     lookupOrig (rdrNameModule rdr_name) (rdrNameOcc rdr_name)
283
284 unboundName :: RdrName -> RnM Name
285 unboundName rdr_name 
286   = do  { addErr (unknownNameErr rdr_name)
287         ; env <- getGlobalRdrEnv;
288         ; traceRn (vcat [unknownNameErr rdr_name, 
289                          ptext SLIT("Global envt is:"),
290                          nest 3 (pprGlobalRdrEnv env)])
291         ; returnM (mkUnboundName rdr_name) }
292
293 --------------------------------------------------
294 --      Lookup in the Global RdrEnv of the module
295 --------------------------------------------------
296
297 lookupSrcOcc_maybe :: RdrName -> RnM (Maybe Name)
298 -- No filter function; does not report an error on failure
299 lookupSrcOcc_maybe rdr_name
300   = do  { mb_gre <- lookupGreRn rdr_name
301         ; case mb_gre of
302                 Nothing  -> returnM Nothing
303                 Just gre -> returnM (Just (gre_name gre)) }
304         
305 -------------------------
306 lookupGreRn :: RdrName -> RnM (Maybe GlobalRdrElt)
307 -- Just look up the RdrName in the GlobalRdrEnv
308 lookupGreRn rdr_name 
309   = lookupGreRn_help rdr_name (lookupGRE_RdrName rdr_name)
310
311 lookupGreLocalRn :: RdrName -> RnM (Maybe GlobalRdrElt)
312 -- Similar, but restricted to locally-defined things
313 lookupGreLocalRn rdr_name 
314   = lookupGreRn_help rdr_name lookup_fn
315   where
316     lookup_fn env = filter isLocalGRE (lookupGRE_RdrName rdr_name env)
317
318 lookupGreRn_help :: RdrName                     -- Only used in error message
319                  -> (GlobalRdrEnv -> [GlobalRdrElt])    -- Lookup function
320                  -> RnM (Maybe GlobalRdrElt)
321 -- Checks for exactly one match; reports deprecations
322 -- Returns Nothing, without error, if too few
323 lookupGreRn_help rdr_name lookup 
324   = do  { env <- getGlobalRdrEnv
325         ; case lookup env of
326             []    -> returnM Nothing
327             [gre] -> returnM (Just gre)
328             gres  -> do { addNameClashErrRn rdr_name gres
329                         ; returnM (Just (head gres)) } }
330
331 ------------------------------
332 --      GHCi support
333 ------------------------------
334
335 -- A qualified name on the command line can refer to any module at all: we
336 -- try to load the interface if we don't already have it.
337 lookupQualifiedName :: RdrName -> RnM Name
338 lookupQualifiedName rdr_name
339  = let 
340        mod = rdrNameModule rdr_name
341        occ = rdrNameOcc rdr_name
342    in
343    -- Note: we want to behave as we would for a source file import here,
344    -- and respect hiddenness of modules/packages, hence loadSrcInterface.
345    loadSrcInterface doc mod False       `thenM` \ iface ->
346
347    case  [ (mod,occ) | 
348            (mod,avails) <- mi_exports iface,
349            avail        <- avails,
350            name         <- availNames avail,
351            name == occ ] of
352       ((mod,occ):ns) -> ASSERT (null ns) 
353                         lookupOrig mod occ
354       _ -> unboundName rdr_name
355   where
356     doc = ptext SLIT("Need to find") <+> ppr rdr_name
357 \end{code}
358
359 %*********************************************************
360 %*                                                      *
361                 Fixities
362 %*                                                      *
363 %*********************************************************
364
365 \begin{code}
366 lookupLocalDataTcNames :: RdrName -> RnM [Name]
367 -- GHC extension: look up both the tycon and data con 
368 -- for con-like things
369 -- Complain if neither is in scope
370 lookupLocalDataTcNames rdr_name
371   | Just n <- isExact_maybe rdr_name    
372         -- Special case for (:), which doesn't get into the GlobalRdrEnv
373   = return [n]  -- For this we don't need to try the tycon too
374   | otherwise
375   = do  { mb_gres <- mapM lookupGreLocalRn (dataTcOccs rdr_name)
376         ; case [gre_name gre | Just gre <- mb_gres] of
377             [] -> do { addErr (unknownNameErr rdr_name)
378                      ; return [] }
379             names -> return names
380     }
381
382 --------------------------------
383 bindLocalFixities :: [FixitySig RdrName] -> RnM a -> RnM a
384 -- Used for nested fixity decls
385 -- No need to worry about type constructors here,
386 -- Should check for duplicates but we don't
387 bindLocalFixities fixes thing_inside
388   | null fixes = thing_inside
389   | otherwise  = mappM rn_sig fixes     `thenM` \ new_bit ->
390                  extendFixityEnv new_bit thing_inside
391   where
392     rn_sig (FixitySig lv@(L loc v) fix)
393         = addLocM lookupBndrRn lv       `thenM` \ new_v ->
394           returnM (new_v, (FixItem (rdrNameOcc v) fix loc))
395 \end{code}
396
397 --------------------------------
398 lookupFixity is a bit strange.  
399
400 * Nested local fixity decls are put in the local fixity env, which we
401   find with getFixtyEnv
402
403 * Imported fixities are found in the HIT or PIT
404
405 * Top-level fixity decls in this module may be for Names that are
406     either  Global         (constructors, class operations)
407     or      Local/Exported (everything else)
408   (See notes with RnNames.getLocalDeclBinders for why we have this split.)
409   We put them all in the local fixity environment
410
411 \begin{code}
412 lookupFixityRn :: Name -> RnM Fixity
413 lookupFixityRn name
414   = getModule                           `thenM` \ this_mod ->
415     if nameIsLocalOrFrom this_mod name
416     then        -- It's defined in this module
417         getFixityEnv            `thenM` \ local_fix_env ->
418         traceRn (text "lookupFixityRn" <+> (ppr name $$ ppr local_fix_env)) `thenM_`
419         returnM (lookupFixity local_fix_env name)
420
421     else        -- It's imported
422       -- For imported names, we have to get their fixities by doing a
423       -- loadHomeInterface, and consulting the Ifaces that comes back
424       -- from that, because the interface file for the Name might not
425       -- have been loaded yet.  Why not?  Suppose you import module A,
426       -- which exports a function 'f', thus;
427       --        module CurrentModule where
428       --          import A( f )
429       --        module A( f ) where
430       --          import B( f )
431       -- Then B isn't loaded right away (after all, it's possible that
432       -- nothing from B will be used).  When we come across a use of
433       -- 'f', we need to know its fixity, and it's then, and only
434       -- then, that we load B.hi.  That is what's happening here.
435       --
436       -- loadHomeInterface will find B.hi even if B is a hidden module,
437       -- and that's what we want.
438         loadHomeInterface doc name      `thenM` \ iface ->
439         returnM (mi_fix_fn iface (nameOccName name))
440   where
441     doc = ptext SLIT("Checking fixity for") <+> ppr name
442
443 ---------------
444 lookupTyFixityRn :: Located Name -> RnM Fixity
445 lookupTyFixityRn (L loc n)
446   = doptM Opt_GlasgowExts                       `thenM` \ glaExts ->
447     when (not glaExts) 
448          (setSrcSpan loc $ addWarn (infixTyConWarn n))  `thenM_`
449     lookupFixityRn n
450
451 ---------------
452 dataTcOccs :: RdrName -> [RdrName]
453 -- If the input is a data constructor, return both it and a type
454 -- constructor.  This is useful when we aren't sure which we are
455 -- looking at.
456 dataTcOccs rdr_name
457   | Just n <- isExact_maybe rdr_name            -- Ghastly special case
458   , n `hasKey` consDataConKey = [rdr_name]      -- see note below
459   | isDataOcc occ             = [rdr_name_tc, rdr_name]
460   | otherwise                 = [rdr_name]
461   where    
462     occ         = rdrNameOcc rdr_name
463     rdr_name_tc = setRdrNameSpace rdr_name tcName
464
465 -- If the user typed "[]" or "(,,)", we'll generate an Exact RdrName,
466 -- and setRdrNameSpace generates an Orig, which is fine
467 -- But it's not fine for (:), because there *is* no corresponding type
468 -- constructor.  If we generate an Orig tycon for GHC.Base.(:), it'll
469 -- appear to be in scope (because Orig's simply allocate a new name-cache
470 -- entry) and then we get an error when we use dataTcOccs in 
471 -- TcRnDriver.tcRnGetInfo.  Large sigh.
472 \end{code}
473
474 %************************************************************************
475 %*                                                                      *
476                         Rebindable names
477         Dealing with rebindable syntax is driven by the 
478         Opt_NoImplicitPrelude dynamic flag.
479
480         In "deriving" code we don't want to use rebindable syntax
481         so we switch off the flag locally
482
483 %*                                                                      *
484 %************************************************************************
485
486 Haskell 98 says that when you say "3" you get the "fromInteger" from the
487 Standard Prelude, regardless of what is in scope.   However, to experiment
488 with having a language that is less coupled to the standard prelude, we're
489 trying a non-standard extension that instead gives you whatever "Prelude.fromInteger"
490 happens to be in scope.  Then you can
491         import Prelude ()
492         import MyPrelude as Prelude
493 to get the desired effect.
494
495 At the moment this just happens for
496   * fromInteger, fromRational on literals (in expressions and patterns)
497   * negate (in expressions)
498   * minus  (arising from n+k patterns)
499   * "do" notation
500
501 We store the relevant Name in the HsSyn tree, in 
502   * HsIntegral/HsFractional     
503   * NegApp
504   * NPlusKPat
505   * HsDo
506 respectively.  Initially, we just store the "standard" name (PrelNames.fromIntegralName,
507 fromRationalName etc), but the renamer changes this to the appropriate user
508 name if Opt_NoImplicitPrelude is on.  That is what lookupSyntaxName does.
509
510 We treat the orignal (standard) names as free-vars too, because the type checker
511 checks the type of the user thing against the type of the standard thing.
512
513 \begin{code}
514 lookupSyntaxName :: Name                                -- The standard name
515                  -> RnM (SyntaxExpr Name, FreeVars)     -- Possibly a non-standard name
516 lookupSyntaxName std_name
517   = doptM Opt_ImplicitPrelude           `thenM` \ implicit_prelude -> 
518     if implicit_prelude then normal_case
519     else
520         -- Get the similarly named thing from the local environment
521     lookupOccRn (mkRdrUnqual (nameOccName std_name)) `thenM` \ usr_name ->
522     returnM (HsVar usr_name, unitFV usr_name)
523   where
524     normal_case = returnM (HsVar std_name, emptyFVs)
525
526 lookupSyntaxTable :: [Name]                             -- Standard names
527                   -> RnM (SyntaxTable Name, FreeVars)   -- See comments with HsExpr.ReboundNames
528 lookupSyntaxTable std_names
529   = doptM Opt_ImplicitPrelude           `thenM` \ implicit_prelude -> 
530     if implicit_prelude then normal_case 
531     else
532         -- Get the similarly named thing from the local environment
533     mappM (lookupOccRn . mkRdrUnqual . nameOccName) std_names   `thenM` \ usr_names ->
534
535     returnM (std_names `zip` map HsVar usr_names, mkFVs usr_names)
536   where
537     normal_case = returnM (std_names `zip` map HsVar std_names, emptyFVs)
538 \end{code}
539
540
541 %*********************************************************
542 %*                                                      *
543 \subsection{Binding}
544 %*                                                      *
545 %*********************************************************
546
547 \begin{code}
548 newLocalsRn :: [Located RdrName] -> RnM [Name]
549 newLocalsRn rdr_names_w_loc
550   = newUniqueSupply             `thenM` \ us ->
551     returnM (zipWith mk rdr_names_w_loc (uniqsFromSupply us))
552   where
553     mk (L loc rdr_name) uniq
554         | Just name <- isExact_maybe rdr_name = name
555                 -- This happens in code generated by Template Haskell 
556         | otherwise = ASSERT2( isUnqual rdr_name, ppr rdr_name )
557                         -- We only bind unqualified names here
558                         -- lookupRdrEnv doesn't even attempt to look up a qualified RdrName
559                       mkInternalName uniq (rdrNameOcc rdr_name) (srcSpanStart loc)
560
561 bindLocatedLocalsRn :: SDoc     -- Documentation string for error message
562                     -> [Located RdrName]
563                     -> ([Name] -> RnM a)
564                     -> RnM a
565 bindLocatedLocalsRn doc_str rdr_names_w_loc enclosed_scope
566   =     -- Check for duplicate names
567     checkDupNames doc_str rdr_names_w_loc       `thenM_`
568
569         -- Warn about shadowing, but only in source modules
570     ifOptM Opt_WarnNameShadowing 
571       (checkShadowing doc_str rdr_names_w_loc)  `thenM_`
572
573         -- Make fresh Names and extend the environment
574     newLocalsRn rdr_names_w_loc         `thenM` \ names ->
575     getLocalRdrEnv                      `thenM` \ local_env ->
576     setLocalRdrEnv (extendLocalRdrEnv local_env names)
577                    (enclosed_scope names)
578
579
580 bindLocalNames :: [Name] -> RnM a -> RnM a
581 bindLocalNames names enclosed_scope
582   = getLocalRdrEnv              `thenM` \ name_env ->
583     setLocalRdrEnv (extendLocalRdrEnv name_env names)
584                     enclosed_scope
585
586 bindLocalNamesFV :: [Name] -> RnM (a, FreeVars) -> RnM (a, FreeVars)
587 bindLocalNamesFV names enclosed_scope
588   = do  { (result, fvs) <- bindLocalNames names enclosed_scope
589         ; returnM (result, delListFromNameSet fvs names) }
590
591
592 -------------------------------------
593         -- binLocalsFVRn is the same as bindLocalsRn
594         -- except that it deals with free vars
595 bindLocatedLocalsFV :: SDoc -> [Located RdrName] -> ([Name] -> RnM (a,FreeVars))
596   -> RnM (a, FreeVars)
597 bindLocatedLocalsFV doc rdr_names enclosed_scope
598   = bindLocatedLocalsRn doc rdr_names   $ \ names ->
599     enclosed_scope names                `thenM` \ (thing, fvs) ->
600     returnM (thing, delListFromNameSet fvs names)
601
602 -------------------------------------
603 bindTyVarsRn :: SDoc -> [LHsTyVarBndr RdrName]
604               -> ([LHsTyVarBndr Name] -> RnM a)
605               -> RnM a
606 -- Haskell-98 binding of type variables; e.g. within a data type decl
607 bindTyVarsRn doc_str tyvar_names enclosed_scope
608   = let
609         located_tyvars = hsLTyVarLocNames tyvar_names
610     in
611     bindLocatedLocalsRn doc_str located_tyvars  $ \ names ->
612     enclosed_scope (zipWith replace tyvar_names names)
613     where 
614         replace (L loc n1) n2 = L loc (replaceTyVarName n1 n2)
615
616 bindPatSigTyVars :: [LHsType RdrName] -> ([Name] -> RnM a) -> RnM a
617   -- Find the type variables in the pattern type 
618   -- signatures that must be brought into scope
619 bindPatSigTyVars tys thing_inside
620   = do  { scoped_tyvars <- doptM Opt_ScopedTypeVariables
621         ; if not scoped_tyvars then 
622                 thing_inside []
623           else 
624     do  { name_env <- getLocalRdrEnv
625         ; let locd_tvs  = [ tv | ty <- tys
626                                , tv <- extractHsTyRdrTyVars ty
627                                , not (unLoc tv `elemLocalRdrEnv` name_env) ]
628               nubbed_tvs = nubBy eqLocated locd_tvs
629                 -- The 'nub' is important.  For example:
630                 --      f (x :: t) (y :: t) = ....
631                 -- We don't want to complain about binding t twice!
632
633         ; bindLocatedLocalsRn doc_sig nubbed_tvs thing_inside }}
634   where
635     doc_sig = text "In a pattern type-signature"
636
637 bindPatSigTyVarsFV :: [LHsType RdrName]
638                    -> RnM (a, FreeVars)
639                    -> RnM (a, FreeVars)
640 bindPatSigTyVarsFV tys thing_inside
641   = bindPatSigTyVars tys        $ \ tvs ->
642     thing_inside                `thenM` \ (result,fvs) ->
643     returnM (result, fvs `delListFromNameSet` tvs)
644
645 bindSigTyVarsFV :: [Name]
646                 -> RnM (a, FreeVars)
647                 -> RnM (a, FreeVars)
648 bindSigTyVarsFV tvs thing_inside
649   = do  { scoped_tyvars <- doptM Opt_ScopedTypeVariables
650         ; if not scoped_tyvars then 
651                 thing_inside 
652           else
653                 bindLocalNamesFV tvs thing_inside }
654
655 extendTyVarEnvFVRn :: [Name] -> RnM (a, FreeVars) -> RnM (a, FreeVars)
656         -- This function is used only in rnSourceDecl on InstDecl
657 extendTyVarEnvFVRn tyvars thing_inside = bindLocalNamesFV tyvars thing_inside
658
659 -------------------------------------
660 checkDupNames :: SDoc
661               -> [Located RdrName]
662               -> RnM ()
663 checkDupNames doc_str rdr_names_w_loc
664   =     -- Check for duplicated names in a binding group
665     mappM_ (dupNamesErr doc_str) dups
666   where
667     (_, dups) = removeDups (\n1 n2 -> unLoc n1 `compare` unLoc n2) rdr_names_w_loc
668
669 -------------------------------------
670 checkShadowing doc_str loc_rdr_names
671   = getLocalRdrEnv              `thenM` \ local_env ->
672     getGlobalRdrEnv             `thenM` \ global_env ->
673     let
674       check_shadow (L loc rdr_name)
675         |  rdr_name `elemLocalRdrEnv` local_env 
676         || not (null (lookupGRE_RdrName rdr_name global_env ))
677         = setSrcSpan loc $ addWarn (shadowedNameWarn doc_str rdr_name)
678         | otherwise = returnM ()
679     in
680     mappM_ check_shadow loc_rdr_names
681 \end{code}
682
683
684 %************************************************************************
685 %*                                                                      *
686 \subsection{Free variable manipulation}
687 %*                                                                      *
688 %************************************************************************
689
690 \begin{code}
691 -- A useful utility
692 mapFvRn f xs = mappM f xs       `thenM` \ stuff ->
693                let
694                   (ys, fvs_s) = unzip stuff
695                in
696                returnM (ys, plusFVs fvs_s)
697 \end{code}
698
699
700 %************************************************************************
701 %*                                                                      *
702 \subsection{Envt utility functions}
703 %*                                                                      *
704 %************************************************************************
705
706 \begin{code}
707 warnUnusedModules :: [(Module,SrcSpan)] -> RnM ()
708 warnUnusedModules mods
709   = ifOptM Opt_WarnUnusedImports (mappM_ bleat mods)
710   where
711     bleat (mod,loc) = setSrcSpan loc $ addWarn (mk_warn mod)
712     mk_warn m = vcat [ptext SLIT("Module") <+> quotes (ppr m)
713                         <+> text "is imported, but nothing from it is used,",
714                       nest 2 (ptext SLIT("except perhaps instances visible in") 
715                         <+> quotes (ppr m)),
716                       ptext SLIT("To suppress this warning, use:") 
717                         <+> ptext SLIT("import") <+> ppr m <> parens empty ]
718
719
720 warnUnusedImports, warnUnusedTopBinds :: [GlobalRdrElt] -> RnM ()
721 warnUnusedImports gres  = ifOptM Opt_WarnUnusedImports (warnUnusedGREs gres)
722 warnUnusedTopBinds gres = ifOptM Opt_WarnUnusedBinds   (warnUnusedGREs gres)
723
724 warnUnusedLocalBinds, warnUnusedMatches :: [Name] -> RnM ()
725 warnUnusedLocalBinds names = ifOptM Opt_WarnUnusedBinds   (warnUnusedLocals names)
726 warnUnusedMatches    names = ifOptM Opt_WarnUnusedMatches (warnUnusedLocals names)
727
728 -------------------------
729 --      Helpers
730 warnUnusedGREs gres 
731  = warnUnusedBinds [(n,Just p) | GRE {gre_name = n, gre_prov = p} <- gres]
732
733 warnUnusedLocals names
734  = warnUnusedBinds [(n,Nothing) | n<-names]
735
736 warnUnusedBinds :: [(Name,Maybe Provenance)] -> RnM ()
737 warnUnusedBinds names  = mappM_ warnUnusedName (filter reportable names)
738  where reportable (name,_) 
739         | isWiredInName name = False    -- Don't report unused wired-in names
740                                         -- Otherwise we get a zillion warnings
741                                         -- from Data.Tuple
742         | otherwise = reportIfUnused (nameOccName name)
743
744 -------------------------
745
746 warnUnusedName :: (Name, Maybe Provenance) -> RnM ()
747 warnUnusedName (name, prov)
748   = addWarnAt loc $
749     sep [msg <> colon, 
750          nest 2 $ occNameFlavour (nameOccName name) <+> quotes (ppr name)]
751         -- TODO should be a proper span
752   where
753     (loc,msg) = case prov of
754                   Just (Imported is)
755                         -> (importSpecLoc imp_spec, imp_from (importSpecModule imp_spec))
756                         where
757                           imp_spec = head is
758                   other -> (srcLocSpan (nameSrcLoc name), unused_msg)
759
760     unused_msg   = text "Defined but not used"
761     imp_from mod = text "Imported from" <+> quotes (ppr mod) <+> text "but not used"
762 \end{code}
763
764 \begin{code}
765 addNameClashErrRn rdr_name (np1:nps)
766   = addErr (vcat [ptext SLIT("Ambiguous occurrence") <+> quotes (ppr rdr_name),
767                   ptext SLIT("It could refer to") <+> vcat (msg1 : msgs)])
768   where
769     msg1 = ptext  SLIT("either") <+> mk_ref np1
770     msgs = [ptext SLIT("    or") <+> mk_ref np | np <- nps]
771     mk_ref gre = quotes (ppr (gre_name gre)) <> comma <+> pprNameProvenance gre
772
773 shadowedNameWarn doc shadow
774   = hsep [ptext SLIT("This binding for"), 
775                quotes (ppr shadow),
776                ptext SLIT("shadows an existing binding")]
777     $$ doc
778
779 unknownNameErr rdr_name
780   = sep [ptext SLIT("Not in scope:"), 
781          nest 2 $ occNameFlavour (rdrNameOcc rdr_name) <+> quotes (ppr rdr_name)]
782
783 unknownInstBndrErr cls op
784   = quotes (ppr op) <+> ptext SLIT("is not a (visible) method of class") <+> quotes (ppr cls)
785
786 badOrigBinding name
787   = ptext SLIT("Illegal binding of built-in syntax:") <+> ppr (rdrNameOcc name)
788         -- The rdrNameOcc is because we don't want to print Prelude.(,)
789
790 dupNamesErr :: SDoc -> [Located RdrName] -> RnM ()
791 dupNamesErr descriptor located_names
792   = setSrcSpan big_loc $
793     addErr (vcat [ptext SLIT("Conflicting definitions for") <+> quotes (ppr name1),
794                   locations,
795                   descriptor])
796   where
797     L _ name1 = head located_names
798     locs      = map getLoc located_names
799     big_loc   = foldr1 combineSrcSpans locs
800     one_line  = srcSpanStartLine big_loc == srcSpanEndLine big_loc
801     locations | one_line  = empty 
802               | otherwise = ptext SLIT("Bound at:") <+> 
803                             vcat (map ppr (sortLe (<=) locs))
804
805 infixTyConWarn op
806   = vcat [ftext FSLIT("Accepting non-standard infix type constructor") <+> quotes (ppr op),
807           ftext FSLIT("Use -fglasgow-exts to avoid this warning")]
808 \end{code}