[project @ 2002-07-29 12:22:37 by simonpj]
[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 where              -- Export everything
8
9 #include "HsVersions.h"
10
11 import {-# SOURCE #-} RnHiFiles( loadInterface )
12
13 import FlattenInfo      ( namesNeededForFlattening )
14 import HsSyn
15 import RnHsSyn          ( RenamedFixitySig )
16 import RdrHsSyn         ( RdrNameIE, RdrNameHsType, RdrNameFixitySig, extractHsTyRdrTyVars )
17 import RdrName          ( RdrName, rdrNameModule, rdrNameOcc, isQual, isUnqual, isOrig,
18                           mkRdrUnqual, mkRdrQual, setRdrNameOcc,
19                           lookupRdrEnv, foldRdrEnv, rdrEnvToList, elemRdrEnv,
20                           unqualifyRdrName
21                         )
22 import HsTypes          ( hsTyVarName, replaceTyVarName )
23 import HscTypes         ( Provenance(..), pprNameProvenance, hasBetterProv,
24                           ImportReason(..), GlobalRdrEnv, GlobalRdrElt(..), AvailEnv,
25                           AvailInfo, Avails, GenAvailInfo(..), NameSupply(..), 
26                           ModIface(..), GhciMode(..),
27                           Deprecations(..), lookupDeprec,
28                           extendLocalRdrEnv, lookupFixity
29                         )
30 import RnMonad
31 import Name             ( Name, 
32                           getSrcLoc, nameIsLocalOrFrom,
33                           mkInternalName, mkExternalName,
34                           mkIPName, nameOccName, nameModule_maybe,
35                           setNameModuleAndLoc, nameModule
36                         )
37 import NameEnv
38 import NameSet
39 import OccName          ( OccName, occNameUserString, occNameFlavour, 
40                           isDataSymOcc, setOccNameSpace, tcName )
41 import Module           ( ModuleName, moduleName, mkVanillaModule, 
42                           mkSysModuleNameFS, moduleNameFS, WhereFrom(..) )
43 import PrelNames        ( mkUnboundName, 
44                           derivingOccurrences,
45                           mAIN_Name, main_RDR_Unqual,
46                           runIOName, intTyConName, 
47                           boolTyConName, funTyConName,
48                           unpackCStringName, unpackCStringFoldrName, unpackCStringUtf8Name,
49                           eqStringName, printName, 
50                           bindIOName, returnIOName, failIOName, thenIOName
51                         )
52 import TysWiredIn       ( unitTyCon )   -- A little odd
53 import FiniteMap
54 import UniqSupply
55 import SrcLoc           ( SrcLoc, noSrcLoc )
56 import Outputable
57 import ListSetOps       ( removeDups, equivClasses )
58 import Util             ( sortLt )
59 import BasicTypes       ( mapIPName, defaultFixity )
60 import List             ( nub )
61 import UniqFM           ( lookupWithDefaultUFM )
62 import Maybe            ( mapMaybe )
63 import Maybes           ( orElse, catMaybes )
64 import CmdLineOpts
65 import FastString       ( FastString )
66 \end{code}
67
68 %*********************************************************
69 %*                                                      *
70 \subsection{Making new names}
71 %*                                                      *
72 %*********************************************************
73
74 \begin{code}
75 newTopBinder :: Module -> RdrName -> SrcLoc -> RnM d Name
76         -- newTopBinder puts into the cache the binder with the
77         -- module information set correctly.  When the decl is later renamed,
78         -- the binding site will thereby get the correct module.
79         -- There maybe occurrences that don't have the correct Module, but
80         -- by the typechecker will propagate the binding definition to all 
81         -- the occurrences, so that doesn't matter
82
83 newTopBinder mod rdr_name loc
84   =     -- First check the cache
85
86         -- There should never be a qualified name in a binding position (except in instance decls)
87         -- The parser doesn't check this because the same parser parses instance decls
88     (if isQual rdr_name then
89         qualNameErr (text "In its declaration") (rdr_name,loc)
90      else
91         returnRn ()
92     )                           `thenRn_`
93
94     getNameSupplyRn             `thenRn` \ name_supply -> 
95     let 
96         occ = rdrNameOcc rdr_name
97         key = (moduleName mod, occ)
98         cache = nsNames name_supply
99     in
100     case lookupFM cache key of
101
102         -- A hit in the cache!  We are at the binding site of the name, and
103         -- this is the moment when we know all about 
104         --      a) the Name's host Module (in particular, which
105         --         package it comes from)
106         --      b) its defining SrcLoc
107         -- So we update this info
108
109         Just name -> let 
110                         new_name  = setNameModuleAndLoc name mod loc
111                         new_cache = addToFM cache key new_name
112                      in
113                      setNameSupplyRn (name_supply {nsNames = new_cache})        `thenRn_`
114 --                   traceRn (text "newTopBinder: overwrite" <+> ppr new_name) `thenRn_`
115                      returnRn new_name
116                      
117         -- Miss in the cache!
118         -- Build a completely new Name, and put it in the cache
119         -- Even for locally-defined names we use implicitImportProvenance; 
120         -- updateProvenances will set it to rights
121         Nothing -> let
122                         (us', us1) = splitUniqSupply (nsUniqs name_supply)
123                         uniq       = uniqFromSupply us1
124                         new_name   = mkExternalName uniq mod occ loc
125                         new_cache  = addToFM cache key new_name
126                    in
127                    setNameSupplyRn (name_supply {nsUniqs = us', nsNames = new_cache})   `thenRn_`
128 --                 traceRn (text "newTopBinder: new" <+> ppr new_name) `thenRn_`
129                    returnRn new_name
130
131
132 newGlobalName :: ModuleName -> OccName -> RnM d Name
133   -- Used for *occurrences*.  We make a place-holder Name, really just
134   -- to agree on its unique, which gets overwritten when we read in
135   -- the binding occurence later (newTopBinder)
136   -- The place-holder Name doesn't have the right SrcLoc, and its
137   -- Module won't have the right Package either.
138   --
139   -- (We have to pass a ModuleName, not a Module, because we may be
140   -- simply looking at an occurrence M.x in an interface file.)
141   --
142   -- This means that a renamed program may have incorrect info
143   -- on implicitly-imported occurrences, but the correct info on the 
144   -- *binding* declaration. It's the type checker that propagates the 
145   -- correct information to all the occurrences.
146   -- Since implicitly-imported names never occur in error messages,
147   -- it doesn't matter that we get the correct info in place till later,
148   -- (but since it affects DLL-ery it does matter that we get it right
149   --  in the end).
150 newGlobalName mod_name occ
151   = getNameSupplyRn             `thenRn` \ name_supply ->
152     let
153         key = (mod_name, occ)
154         cache = nsNames name_supply
155     in
156     case lookupFM cache key of
157         Just name -> -- traceRn (text "newGlobalName: hit" <+> ppr name) `thenRn_`
158                      returnRn name
159
160         Nothing   -> setNameSupplyRn (name_supply {nsUniqs = us', nsNames = new_cache})  `thenRn_`
161                      -- traceRn (text "newGlobalName: new" <+> ppr name)                  `thenRn_`
162                      returnRn name
163                   where
164                      (us', us1) = splitUniqSupply (nsUniqs name_supply)
165                      uniq       = uniqFromSupply us1
166                      mod        = mkVanillaModule mod_name
167                      name       = mkExternalName uniq mod occ noSrcLoc
168                      new_cache  = addToFM cache key name
169
170 newIPName rdr_name_ip
171   = getNameSupplyRn             `thenRn` \ name_supply ->
172     let
173         ipcache = nsIPs name_supply
174     in
175     case lookupFM ipcache key of
176         Just name_ip -> returnRn name_ip
177         Nothing      -> setNameSupplyRn new_ns  `thenRn_`
178                         returnRn name_ip
179                   where
180                      (us', us1)  = splitUniqSupply (nsUniqs name_supply)
181                      uniq        = uniqFromSupply us1
182                      name_ip     = mapIPName mk_name rdr_name_ip
183                      mk_name rdr_name = mkIPName uniq (rdrNameOcc rdr_name)
184                      new_ipcache = addToFM ipcache key name_ip
185                      new_ns      = name_supply {nsUniqs = us', nsIPs = new_ipcache}
186     where 
187         key = rdr_name_ip       -- Ensures that ?x and %x get distinct Names
188 \end{code}
189
190 %*********************************************************
191 %*                                                      *
192 \subsection{Looking up names}
193 %*                                                      *
194 %*********************************************************
195
196 Looking up a name in the RnEnv.
197
198 \begin{code}
199 lookupBndrRn rdr_name
200   = getLocalNameEnv             `thenRn` \ local_env ->
201     case lookupRdrEnv local_env rdr_name of 
202           Just name -> returnRn name
203           Nothing   -> lookupTopBndrRn rdr_name
204
205 lookupTopBndrRn rdr_name
206 -- Look up a top-level local binder.   We may be looking up an unqualified 'f',
207 -- and there may be several imported 'f's too, which must not confuse us.
208 -- So we have to filter out the non-local ones.
209 -- A separate function (importsFromLocalDecls) reports duplicate top level
210 -- decls, so here it's safe just to choose an arbitrary one.
211
212   | isOrig rdr_name
213         -- This is here just to catch the PrelBase defn of (say) [] and similar
214         -- The parser reads the special syntax and returns an Orig RdrName
215         -- But the global_env contains only Qual RdrNames, so we won't
216         -- find it there; instead just get the name via the Orig route
217         --
218   =     -- This is a binding site for the name, so check first that it 
219         -- the current module is the correct one; otherwise GHC can get
220         -- very confused indeed.  This test rejects code like
221         --      data T = (,) Int Int
222         -- unless we are in GHC.Tup
223     getModuleRn                         `thenRn` \ mod -> 
224     checkRn (moduleName mod == rdrNameModule rdr_name)
225             (badOrigBinding rdr_name)   `thenRn_`
226     lookupOrigName rdr_name
227
228   | otherwise
229   = getModeRn   `thenRn` \ mode ->
230     if isInterfaceMode mode
231         then lookupSysBinder rdr_name   
232                 -- lookupSysBinder uses the Module in the monad to set
233                 -- the correct module for the binder.  This is important because
234                 -- when GHCi is reading in an old interface, it just sucks it
235                 -- in entire (Rename.loadHomeDecls) which uses lookupTopBndrRn
236                 -- rather than via the iface file cache which uses newTopBndrRn
237                 -- We must get the correct Module into the thing.
238
239     else 
240     getModuleRn         `thenRn` \ mod ->
241     getGlobalNameEnv    `thenRn` \ global_env ->
242     case lookup_local mod global_env rdr_name of
243         Just name -> returnRn name
244         Nothing   -> failWithRn (mkUnboundName rdr_name)
245                                 (unknownNameErr rdr_name)
246
247 lookup_local mod global_env rdr_name
248   = case lookupRdrEnv global_env rdr_name of
249           Nothing   -> Nothing
250           Just gres -> case [n | GRE n _ _ <- gres, nameIsLocalOrFrom mod n] of
251                          []     -> Nothing
252                          (n:ns) -> Just n
253               
254
255 -- lookupSigOccRn is used for type signatures and pragmas
256 -- Is this valid?
257 --   module A
258 --      import M( f )
259 --      f :: Int -> Int
260 --      f x = x
261 -- It's clear that the 'f' in the signature must refer to A.f
262 -- The Haskell98 report does not stipulate this, but it will!
263 -- So we must treat the 'f' in the signature in the same way
264 -- as the binding occurrence of 'f', using lookupBndrRn
265 lookupSigOccRn :: RdrName -> RnMS Name
266 lookupSigOccRn = lookupBndrRn
267
268 -- lookupInstDeclBndr is used for the binders in an 
269 -- instance declaration.   Here we use the class name to
270 -- disambiguate.  
271
272 lookupInstDeclBndr :: Name -> RdrName -> RnMS Name
273         -- We use the selector name as the binder
274 lookupInstDeclBndr cls_name rdr_name
275   | isOrig rdr_name     -- Occurs in derived instances, where we just
276                         -- refer diectly to the right method
277   = lookupOrigName rdr_name
278
279   | otherwise   
280   = getGlobalAvails     `thenRn` \ avail_env ->
281     case lookupNameEnv avail_env cls_name of
282           -- The class itself isn't in scope, so cls_name is unboundName
283           -- e.g.   import Prelude hiding( Ord )
284           --        instance Ord T where ...
285           -- The program is wrong, but that should not cause a crash.
286         Nothing -> returnRn (mkUnboundName rdr_name)
287         Just (AvailTC _ ns) -> case [n | n <- ns, nameOccName n == occ] of
288                                 (n:ns)-> ASSERT( null ns ) returnRn n
289                                 []    -> failWithRn (mkUnboundName rdr_name)
290                                                     (unknownNameErr rdr_name)
291         other               -> pprPanic "lookupInstDeclBndr" (ppr cls_name)
292   where
293     occ = rdrNameOcc rdr_name
294
295 -- lookupOccRn looks up an occurrence of a RdrName
296 lookupOccRn :: RdrName -> RnMS Name
297 lookupOccRn rdr_name
298   = getLocalNameEnv                     `thenRn` \ local_env ->
299     case lookupRdrEnv local_env rdr_name of
300           Just name -> returnRn name
301           Nothing   -> lookupGlobalOccRn rdr_name
302
303 -- lookupGlobalOccRn is like lookupOccRn, except that it looks in the global 
304 -- environment.  It's used only for
305 --      record field names
306 --      class op names in class and instance decls
307
308 lookupGlobalOccRn rdr_name
309   = getModeRn           `thenRn` \ mode ->
310     if (isInterfaceMode mode)
311         then lookupIfaceName rdr_name
312         else 
313
314     getGlobalNameEnv    `thenRn` \ global_env ->
315     case mode of 
316         SourceMode -> lookupSrcName global_env rdr_name
317
318         CmdLineMode
319          | not (isQual rdr_name) -> 
320                 lookupSrcName global_env rdr_name
321
322                 -- We allow qualified names on the command line to refer to 
323                 -- *any* name exported by any module in scope, just as if 
324                 -- there was an "import qualified M" declaration for every 
325                 -- module.
326                 --
327                 -- First look up the name in the normal environment.  If
328                 -- it isn't there, we manufacture a new occurrence of an
329                 -- original name.
330          | otherwise -> 
331                 case lookupRdrEnv global_env rdr_name of
332                        Just _  -> lookupSrcName global_env rdr_name
333                        Nothing -> lookupQualifiedName rdr_name
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 d Name
338 lookupQualifiedName rdr_name
339  = let 
340        mod = rdrNameModule rdr_name
341        occ = rdrNameOcc rdr_name
342    in
343    loadInterface (ppr rdr_name) mod ImportByUser `thenRn` \ iface ->
344    case  [ name | (_,avails) <- mi_exports iface,
345            avail             <- avails,
346            name              <- availNames avail,
347            nameOccName name == occ ] of
348       (n:ns) -> ASSERT (null ns) returnRn n
349       _      -> failWithRn (mkUnboundName rdr_name) (unknownNameErr rdr_name)
350
351 lookupSrcName :: GlobalRdrEnv -> RdrName -> RnM d Name
352 -- NB: passed GlobalEnv explicitly, not necessarily in RnMS monad
353 lookupSrcName global_env rdr_name
354   | isOrig rdr_name     -- Can occur in source code too
355   = lookupOrigName rdr_name
356
357   | otherwise
358   = case lookupRdrEnv global_env rdr_name of
359         Just [GRE name _ Nothing]       -> returnRn name
360         Just [GRE name _ (Just deprec)] -> warnDeprec name deprec       `thenRn_`
361                                            returnRn name
362         Just stuff@(GRE name _ _ : _)   -> addNameClashErrRn rdr_name stuff     `thenRn_`
363                                            returnRn name
364         Nothing                         -> failWithRn (mkUnboundName rdr_name)
365                                                       (unknownNameErr rdr_name)
366
367 lookupOrigName :: RdrName -> RnM d Name 
368 lookupOrigName rdr_name
369   = -- NO: ASSERT( isOrig rdr_name )
370     -- Now that .hi-boot files are read by the main parser, they contain
371     -- ordinary qualified names (which we treat as Orig names here).
372     newGlobalName (rdrNameModule rdr_name) (rdrNameOcc rdr_name)
373
374 lookupIfaceUnqual :: RdrName -> RnM d Name
375 lookupIfaceUnqual rdr_name
376   = ASSERT( isUnqual rdr_name )
377         -- An Unqual is allowed; interface files contain 
378         -- unqualified names for locally-defined things, such as
379         -- constructors of a data type.
380     getModuleRn                         `thenRn ` \ mod ->
381     newGlobalName (moduleName mod) (rdrNameOcc rdr_name)
382
383 lookupIfaceName :: RdrName -> RnM d Name
384 lookupIfaceName rdr_name
385   | isUnqual rdr_name = lookupIfaceUnqual rdr_name
386   | otherwise         = lookupOrigName rdr_name
387 \end{code}
388
389 @lookupOrigName@ takes an RdrName representing an {\em original}
390 name, and adds it to the occurrence pool so that it'll be loaded
391 later.  This is used when language constructs (such as monad
392 comprehensions, overloaded literals, or deriving clauses) require some
393 stuff to be loaded that isn't explicitly mentioned in the code.
394
395 This doesn't apply in interface mode, where everything is explicit,
396 but we don't check for this case: it does no harm to record an
397 ``extra'' occurrence and @lookupOrigNames@ isn't used much in
398 interface mode (it's only the @Nothing@ clause of @rnDerivs@ that
399 calls it at all I think).
400
401   \fbox{{\em Jan 98: this comment is wrong: @rnHsType@ uses it quite a bit.}}
402
403 \begin{code}
404 lookupOrigNames :: [RdrName] -> RnM d NameSet
405 lookupOrigNames rdr_names
406   = mapRn lookupOrigName rdr_names      `thenRn` \ names ->
407     returnRn (mkNameSet names)
408 \end{code}
409
410 lookupSysBinder is used for the "system binders" of a type, class, or
411 instance decl.  It ensures that the module is set correctly in the
412 name cache, and sets the provenance on the returned name too.  The
413 returned name will end up actually in the type, class, or instance.
414
415 \begin{code}
416 lookupSysBinder rdr_name
417   = ASSERT( isUnqual rdr_name )
418     getModuleRn                         `thenRn` \ mod ->
419     getSrcLocRn                         `thenRn` \ loc ->
420     newTopBinder mod rdr_name loc
421 \end{code}
422
423
424 %*********************************************************
425 %*                                                      *
426 \subsection{Looking up fixities}
427 %*                                                      *
428 %*********************************************************
429
430 lookupFixity is a bit strange.  
431
432 * Nested local fixity decls are put in the local fixity env, which we
433   find with getFixtyEnv
434
435 * Imported fixities are found in the HIT or PIT
436
437 * Top-level fixity decls in this module may be for Names that are
438     either  Global         (constructors, class operations)
439     or      Local/Exported (everything else)
440   (See notes with RnNames.getLocalDeclBinders for why we have this split.)
441   We put them all in the local fixity environment
442
443 \begin{code}
444 lookupFixityRn :: Name -> RnMS Fixity
445 lookupFixityRn name
446   = getModuleRn                         `thenRn` \ this_mod ->
447     if nameIsLocalOrFrom this_mod name
448     then        -- It's defined in this module
449         getFixityEnv                    `thenRn` \ local_fix_env ->
450         returnRn (lookupLocalFixity local_fix_env name)
451
452     else        -- It's imported
453       -- For imported names, we have to get their fixities by doing a
454       -- loadHomeInterface, and consulting the Ifaces that comes back
455       -- from that, because the interface file for the Name might not
456       -- have been loaded yet.  Why not?  Suppose you import module A,
457       -- which exports a function 'f', thus;
458       --        module CurrentModule where
459       --          import A( f )
460       --        module A( f ) where
461       --          import B( f )
462       -- Then B isn't loaded right away (after all, it's possible that
463       -- nothing from B will be used).  When we come across a use of
464       -- 'f', we need to know its fixity, and it's then, and only
465       -- then, that we load B.hi.  That is what's happening here.
466         loadInterface doc name_mod ImportBySystem       `thenRn` \ iface ->
467         returnRn (lookupFixity (mi_fixities iface) name)
468   where
469     doc      = ptext SLIT("Checking fixity for") <+> ppr name
470     name_mod = moduleName (nameModule name)
471
472 --------------------------------
473 lookupLocalFixity :: LocalFixityEnv -> Name -> Fixity
474 lookupLocalFixity env name
475   = case lookupNameEnv env name of 
476         Just (FixitySig _ fix _) -> fix
477         Nothing                  -> defaultFixity
478
479 extendNestedFixityEnv :: [(Name, RenamedFixitySig)] -> RnMS a -> RnMS a
480 -- Used for nested fixity decls
481 -- No need to worry about type constructors here,
482 -- Should check for duplicates but we don't
483 extendNestedFixityEnv fixes enclosed_scope
484   = getFixityEnv        `thenRn` \ fix_env ->
485     let
486         new_fix_env = extendNameEnvList fix_env fixes
487     in
488     setFixityEnv new_fix_env enclosed_scope
489
490 mkTopFixityEnv :: GlobalRdrEnv -> [RdrNameFixitySig] -> RnMG LocalFixityEnv
491 mkTopFixityEnv gbl_env fix_sigs 
492   = getModuleRn                         `thenRn` \ mod -> 
493     let
494                 -- GHC extension: look up both the tycon and data con 
495                 -- for con-like things
496                 -- If neither are in scope, report an error; otherwise
497                 -- add both to the fixity env
498         go fix_env (FixitySig rdr_name fixity loc)
499           = case catMaybes (map (lookup_local mod gbl_env) rdr_names) of
500                   [] -> pushSrcLocRn loc                        $
501                         addErrRn (unknownNameErr rdr_name)      `thenRn_`
502                         returnRn fix_env
503                   ns -> foldlRn add fix_env ns
504
505           where
506             add fix_env name 
507               = case lookupNameEnv fix_env name of
508                   Just (FixitySig _ _ loc') -> addErrRn (dupFixityDecl rdr_name loc loc')       `thenRn_`
509                                                returnRn fix_env
510                   Nothing -> returnRn (extendNameEnv fix_env name (FixitySig name fixity loc))
511             
512             rdr_names | isDataSymOcc occ = [rdr_name, rdr_name_tc]
513                       | otherwise            = [rdr_name]
514
515             occ         = rdrNameOcc rdr_name
516             rdr_name_tc = setRdrNameOcc rdr_name (setOccNameSpace occ tcName)
517     in
518     foldlRn go emptyLocalFixityEnv fix_sigs
519 \end{code}
520
521
522 %*********************************************************
523 %*                                                      *
524 \subsection{Implicit free vars and sugar names}
525 %*                                                      *
526 %*********************************************************
527
528 @getXImplicitFVs@ forces the renamer to slurp in some things which aren't
529 mentioned explicitly, but which might be needed by the type checker.
530
531 \begin{code}
532 getImplicitStmtFVs      -- Compiling a statement
533   = returnRn (mkFVs [printName, bindIOName, thenIOName, 
534                      returnIOName, failIOName]
535               `plusFV` ubiquitousNames)
536                 -- These are all needed implicitly when compiling a statement
537                 -- See TcModule.tc_stmts
538
539 getImplicitModuleFVs decls      -- Compiling a module
540   = lookupOrigNames deriv_occs          `thenRn` \ deriving_names ->
541     returnRn (deriving_names `plusFV` ubiquitousNames)
542   where
543         -- deriv_classes is now a list of HsTypes, so a "normal" one
544         -- appears as a (HsClassP c []).  The non-normal ones for the new
545         -- newtype-deriving extension, and they don't require any
546         -- implicit names, so we can silently filter them out.
547         deriv_occs = [occ | TyClD (TyData {tcdDerivs = Just deriv_classes}) <- decls,
548                             HsClassP cls [] <- deriv_classes,
549                             occ <- lookupWithDefaultUFM derivingOccurrences [] cls ]
550
551 -- ubiquitous_names are loaded regardless, because 
552 -- they are needed in virtually every program
553 ubiquitousNames 
554   = mkFVs [unpackCStringName, unpackCStringFoldrName, 
555            unpackCStringUtf8Name, eqStringName]
556         -- Virtually every program has error messages in it somewhere
557
558   `plusFV`
559     mkFVs [getName unitTyCon, funTyConName, boolTyConName, intTyConName]
560         -- Add occurrences for very frequently used types.
561         --       (e.g. we don't want to be bothered with making funTyCon a
562         --        free var at every function application!)
563   `plusFV`
564     namesNeededForFlattening
565         -- this will be empty unless flattening is activated
566
567 checkMain ghci_mode mod_name gbl_env
568         -- LOOKUP main IF WE'RE IN MODULE Main
569         -- The main point of this is to drag in the declaration for 'main',
570         -- its in another module, and for the Prelude function 'runIO',
571         -- so that the type checker will find them
572         --
573         -- We have to return the main_name separately, because it's a
574         -- bona fide 'use', and should be recorded as such, but the others
575         -- aren't 
576   | mod_name /= mAIN_Name
577   = returnRn (Nothing, emptyFVs, emptyFVs)
578
579   | not (main_RDR_Unqual `elemRdrEnv` gbl_env)
580   = complain_no_main            `thenRn_`
581     returnRn (Nothing, emptyFVs, emptyFVs)
582
583   | otherwise
584   = lookupSrcName gbl_env main_RDR_Unqual       `thenRn` \ main_name ->
585     returnRn (Just main_name, unitFV main_name, unitFV runIOName)
586
587   where
588     complain_no_main | ghci_mode == Interactive = addWarnRn noMainMsg
589                      | otherwise                = addErrRn  noMainMsg
590                 -- In interactive mode, only warn about the absence of main
591 \end{code}
592
593 %************************************************************************
594 %*                                                                      *
595 \subsection{Re-bindable desugaring names}
596 %*                                                                      *
597 %************************************************************************
598
599 Haskell 98 says that when you say "3" you get the "fromInteger" from the
600 Standard Prelude, regardless of what is in scope.   However, to experiment
601 with having a language that is less coupled to the standard prelude, we're
602 trying a non-standard extension that instead gives you whatever "Prelude.fromInteger"
603 happens to be in scope.  Then you can
604         import Prelude ()
605         import MyPrelude as Prelude
606 to get the desired effect.
607
608 At the moment this just happens for
609   * fromInteger, fromRational on literals (in expressions and patterns)
610   * negate (in expressions)
611   * minus  (arising from n+k patterns)
612   * "do" notation
613
614 We store the relevant Name in the HsSyn tree, in 
615   * HsIntegral/HsFractional     
616   * NegApp
617   * NPlusKPatIn
618   * HsDo
619 respectively.  Initially, we just store the "standard" name (PrelNames.fromIntegralName,
620 fromRationalName etc), but the renamer changes this to the appropriate user
621 name if Opt_NoImplicitPrelude is on.  That is what lookupSyntaxName does.
622
623 We treat the orignal (standard) names as free-vars too, because the type checker
624 checks the type of the user thing against the type of the standard thing.
625
626 \begin{code}
627 lookupSyntaxName :: Name                        -- The standard name
628                  -> RnMS (Name, FreeVars)       -- Possibly a non-standard name
629 lookupSyntaxName std_name
630   = getModeRn                           `thenRn` \ mode ->
631     case mode of {
632         InterfaceMode -> returnRn (std_name, unitFV std_name) ;
633                                 -- Happens for 'derived' code
634                                 -- where we don't want to rebind
635         other ->
636
637     doptRn Opt_NoImplicitPrelude        `thenRn` \ no_prelude -> 
638     if not no_prelude then
639         returnRn (std_name, unitFV std_name)    -- Normal case
640     else
641         -- Get the similarly named thing from the local environment
642     lookupOccRn (mkRdrUnqual (nameOccName std_name)) `thenRn` \ usr_name ->
643     returnRn (usr_name, mkFVs [usr_name, std_name]) }
644 \end{code}
645
646
647 %*********************************************************
648 %*                                                      *
649 \subsection{Binding}
650 %*                                                      *
651 %*********************************************************
652
653 \begin{code}
654 newLocalsRn :: [(RdrName,SrcLoc)]
655             -> RnMS [Name]
656 newLocalsRn rdr_names_w_loc
657  =  getNameSupplyRn             `thenRn` \ name_supply ->
658     let
659         (us', us1) = splitUniqSupply (nsUniqs name_supply)
660         uniqs      = uniqsFromSupply us1
661         names      = [ mkInternalName uniq (rdrNameOcc rdr_name) loc
662                      | ((rdr_name,loc), uniq) <- rdr_names_w_loc `zip` uniqs
663                      ]
664     in
665     setNameSupplyRn (name_supply {nsUniqs = us'})       `thenRn_`
666     returnRn names
667
668
669 bindLocatedLocalsRn :: SDoc     -- Documentation string for error message
670                     -> [(RdrName,SrcLoc)]
671                     -> ([Name] -> RnMS a)
672                     -> RnMS a
673 bindLocatedLocalsRn doc_str rdr_names_w_loc enclosed_scope
674   = getModeRn                           `thenRn` \ mode ->
675     getLocalNameEnv                     `thenRn` \ local_env ->
676     getGlobalNameEnv                    `thenRn` \ global_env ->
677
678         -- Check for duplicate names
679     checkDupOrQualNames doc_str rdr_names_w_loc `thenRn_`
680
681         -- Warn about shadowing, but only in source modules
682     let
683       check_shadow (rdr_name,loc)
684         |  rdr_name `elemRdrEnv` local_env 
685         || rdr_name `elemRdrEnv` global_env 
686         = pushSrcLocRn loc $ addWarnRn (shadowedNameWarn rdr_name)
687         | otherwise 
688         = returnRn ()
689     in
690
691     (case mode of
692         SourceMode -> ifOptRn Opt_WarnNameShadowing     $
693                       mapRn_ check_shadow rdr_names_w_loc
694         other      -> returnRn ()
695     )                                   `thenRn_`
696
697     newLocalsRn rdr_names_w_loc         `thenRn` \ names ->
698     let
699         new_local_env = addListToRdrEnv local_env (map fst rdr_names_w_loc `zip` names)
700     in
701     setLocalNameEnv new_local_env (enclosed_scope names)
702
703 bindCoreLocalRn :: RdrName -> (Name -> RnMS a) -> RnMS a
704   -- A specialised variant when renaming stuff from interface
705   -- files (of which there is a lot)
706   --    * one at a time
707   --    * no checks for shadowing
708   --    * always imported
709   --    * deal with free vars
710 bindCoreLocalRn rdr_name enclosed_scope
711   = getSrcLocRn                 `thenRn` \ loc ->
712     getLocalNameEnv             `thenRn` \ name_env ->
713     getNameSupplyRn             `thenRn` \ name_supply ->
714     let
715         (us', us1) = splitUniqSupply (nsUniqs name_supply)
716         uniq       = uniqFromSupply us1
717         name       = mkInternalName uniq (rdrNameOcc rdr_name) loc
718     in
719     setNameSupplyRn (name_supply {nsUniqs = us'})       `thenRn_`
720     let
721         new_name_env = extendRdrEnv name_env rdr_name name
722     in
723     setLocalNameEnv new_name_env (enclosed_scope name)
724
725 bindCoreLocalsRn []     thing_inside = thing_inside []
726 bindCoreLocalsRn (b:bs) thing_inside = bindCoreLocalRn b        $ \ name' ->
727                                        bindCoreLocalsRn bs      $ \ names' ->
728                                        thing_inside (name':names')
729
730 bindLocalNames names enclosed_scope
731   = getLocalNameEnv             `thenRn` \ name_env ->
732     setLocalNameEnv (extendLocalRdrEnv name_env names)
733                     enclosed_scope
734
735 bindLocalNamesFV names enclosed_scope
736   = bindLocalNames names $
737     enclosed_scope `thenRn` \ (thing, fvs) ->
738     returnRn (thing, delListFromNameSet fvs names)
739
740
741 -------------------------------------
742 bindLocalRn doc rdr_name enclosed_scope
743   = getSrcLocRn                                 `thenRn` \ loc ->
744     bindLocatedLocalsRn doc [(rdr_name,loc)]    $ \ (n:ns) ->
745     ASSERT( null ns )
746     enclosed_scope n
747
748 bindLocalsRn doc rdr_names enclosed_scope
749   = getSrcLocRn         `thenRn` \ loc ->
750     bindLocatedLocalsRn doc
751                         (rdr_names `zip` repeat loc)
752                         enclosed_scope
753
754         -- binLocalsFVRn is the same as bindLocalsRn
755         -- except that it deals with free vars
756 bindLocalsFVRn doc rdr_names enclosed_scope
757   = bindLocalsRn doc rdr_names          $ \ names ->
758     enclosed_scope names                `thenRn` \ (thing, fvs) ->
759     returnRn (thing, delListFromNameSet fvs names)
760
761 -------------------------------------
762 extendTyVarEnvFVRn :: [Name] -> RnMS (a, FreeVars) -> RnMS (a, FreeVars)
763         -- This tiresome function is used only in rnSourceDecl on InstDecl
764 extendTyVarEnvFVRn tyvars enclosed_scope
765   = bindLocalNames tyvars enclosed_scope        `thenRn` \ (thing, fvs) -> 
766     returnRn (thing, delListFromNameSet fvs tyvars)
767
768 bindTyVarsRn :: SDoc -> [HsTyVarBndr RdrName]
769               -> ([HsTyVarBndr Name] -> RnMS a)
770               -> RnMS a
771 bindTyVarsRn doc_str tyvar_names enclosed_scope
772   = getSrcLocRn                                 `thenRn` \ loc ->
773     let
774         located_tyvars = [(hsTyVarName tv, loc) | tv <- tyvar_names] 
775     in
776     bindLocatedLocalsRn doc_str located_tyvars  $ \ names ->
777     enclosed_scope (zipWith replaceTyVarName tyvar_names names)
778
779 bindPatSigTyVars :: [RdrNameHsType]
780                  -> RnMS (a, FreeVars)
781                  -> RnMS (a, FreeVars)
782   -- Find the type variables in the pattern type 
783   -- signatures that must be brought into scope
784
785 bindPatSigTyVars tys enclosed_scope
786   = getLocalNameEnv                     `thenRn` \ name_env ->
787     getSrcLocRn                         `thenRn` \ loc ->
788     let
789         forall_tyvars  = nub [ tv | ty <- tys,
790                                     tv <- extractHsTyRdrTyVars ty, 
791                                     not (tv `elemFM` name_env)
792                          ]
793                 -- The 'nub' is important.  For example:
794                 --      f (x :: t) (y :: t) = ....
795                 -- We don't want to complain about binding t twice!
796
797         located_tyvars = [(tv, loc) | tv <- forall_tyvars] 
798         doc_sig        = text "In a pattern type-signature"
799     in
800     bindLocatedLocalsRn doc_sig located_tyvars  $ \ names ->
801     enclosed_scope                              `thenRn` \ (thing, fvs) ->
802     returnRn (thing, delListFromNameSet fvs names)
803
804
805 -------------------------------------
806 checkDupOrQualNames, checkDupNames :: SDoc
807                                    -> [(RdrName, SrcLoc)]
808                                    -> RnM d ()
809         -- Works in any variant of the renamer monad
810
811 checkDupOrQualNames doc_str rdr_names_w_loc
812   =     -- Check for use of qualified names
813     mapRn_ (qualNameErr doc_str) quals  `thenRn_`
814     checkDupNames doc_str rdr_names_w_loc
815   where
816     quals = filter (isQual . fst) rdr_names_w_loc
817     
818 checkDupNames doc_str rdr_names_w_loc
819   =     -- Check for duplicated names in a binding group
820     mapRn_ (dupNamesErr doc_str) dups
821   where
822     (_, dups) = removeDups (\(n1,l1) (n2,l2) -> n1 `compare` n2) rdr_names_w_loc
823 \end{code}
824
825
826 %************************************************************************
827 %*                                                                      *
828 \subsection{GlobalRdrEnv}
829 %*                                                                      *
830 %************************************************************************
831
832 \begin{code}
833 mkGlobalRdrEnv :: ModuleName            -- Imported module (after doing the "as M" name change)
834                -> Bool                  -- True <=> want unqualified import
835                -> (Name -> Provenance)
836                -> Avails                -- Whats imported
837                -> Deprecations
838                -> GlobalRdrEnv
839
840 mkGlobalRdrEnv this_mod unqual_imp mk_provenance avails deprecs
841   = gbl_env2
842   where
843         -- Make the name environment.  We're talking about a 
844         -- single module here, so there must be no name clashes.
845         -- In practice there only ever will be if it's the module
846         -- being compiled.
847
848         -- Add qualified names for the things that are available
849         -- (Qualified names are always imported)
850     gbl_env1 = foldl add_avail emptyRdrEnv avails
851
852         -- Add unqualified names
853     gbl_env2 | unqual_imp = foldl add_unqual gbl_env1 (rdrEnvToList gbl_env1)
854              | otherwise  = gbl_env1
855
856     add_unqual env (qual_name, elts)
857         = foldl add_one env elts
858         where
859           add_one env elt = addOneToGlobalRdrEnv env unqual_name elt
860           unqual_name     = unqualifyRdrName qual_name
861         -- The qualified import should only have added one 
862         -- binding for each qualified name!  But if there's an error in
863         -- the module (multiple bindings for the same name) we may get
864         -- duplicates.  So the simple thing is to do the fold.
865
866     add_avail :: GlobalRdrEnv -> AvailInfo -> GlobalRdrEnv
867     add_avail env avail = foldl add_name env (availNames avail)
868
869     add_name env name   -- Add qualified name only
870         = addOneToGlobalRdrEnv env  (mkRdrQual this_mod occ) elt
871         where
872           occ  = nameOccName name
873           elt  = GRE name (mk_provenance name) (lookupDeprec deprecs name)
874 \end{code}
875
876 \begin{code}
877 plusGlobalRdrEnv :: GlobalRdrEnv -> GlobalRdrEnv -> GlobalRdrEnv
878 plusGlobalRdrEnv env1 env2 = plusFM_C combine_globals env1 env2
879
880 addOneToGlobalRdrEnv :: GlobalRdrEnv -> RdrName -> GlobalRdrElt -> GlobalRdrEnv
881 addOneToGlobalRdrEnv env rdr_name name = addToFM_C combine_globals env rdr_name [name]
882
883 delOneFromGlobalRdrEnv :: GlobalRdrEnv -> RdrName -> GlobalRdrEnv 
884 delOneFromGlobalRdrEnv env rdr_name = delFromFM env rdr_name
885
886 combine_globals :: [GlobalRdrElt]       -- Old
887                 -> [GlobalRdrElt]       -- New
888                 -> [GlobalRdrElt]
889 combine_globals ns_old ns_new   -- ns_new is often short
890   = foldr add ns_old ns_new
891   where
892     add n ns | any (is_duplicate n) ns_old = map (choose n) ns  -- Eliminate duplicates
893              | otherwise                   = n:ns
894
895     choose n m | n `beats` m = n
896                | otherwise   = m
897
898     (GRE n pn _) `beats` (GRE m pm _) = n==m && pn `hasBetterProv` pm
899
900     is_duplicate :: GlobalRdrElt -> GlobalRdrElt -> Bool
901     is_duplicate (GRE n1 LocalDef _) (GRE n2 LocalDef _) = False
902     is_duplicate (GRE n1 _        _) (GRE n2 _        _) = n1 == n2
903 \end{code}
904
905 We treat two bindings of a locally-defined name as a duplicate,
906 because they might be two separate, local defns and we want to report
907 and error for that, {\em not} eliminate a duplicate.
908
909 On the other hand, if you import the same name from two different
910 import statements, we {\em do} want to eliminate the duplicate, not report
911 an error.
912
913 If a module imports itself then there might be a local defn and an imported
914 defn of the same name; in this case the names will compare as equal, but
915 will still have different provenances.
916
917
918 @unQualInScope@ returns a function that takes a @Name@ and tells whether
919 its unqualified name is in scope.  This is put as a boolean flag in
920 the @Name@'s provenance to guide whether or not to print the name qualified
921 in error messages.
922
923 \begin{code}
924 unQualInScope :: GlobalRdrEnv -> Name -> Bool
925 -- True if 'f' is in scope, and has only one binding,
926 -- and the thing it is bound to is the name we are looking for
927 -- (i.e. false if A.f and B.f are both in scope as unqualified 'f')
928 --
929 -- This fn is only efficient if the shared 
930 -- partial application is used a lot.
931 unQualInScope env
932   = (`elemNameSet` unqual_names)
933   where
934     unqual_names :: NameSet
935     unqual_names = foldRdrEnv add emptyNameSet env
936     add rdr_name [GRE name _ _] unquals | isUnqual rdr_name = addOneToNameSet unquals name
937     add _        _              unquals                     = unquals
938 \end{code}
939
940
941 %************************************************************************
942 %*                                                                      *
943 \subsection{Avails}
944 %*                                                                      *
945 %************************************************************************
946
947 \begin{code}
948 plusAvail (Avail n1)       (Avail n2)       = Avail n1
949 plusAvail (AvailTC n1 ns1) (AvailTC n2 ns2) = AvailTC n2 (nub (ns1 ++ ns2))
950 -- Added SOF 4/97
951 #ifdef DEBUG
952 plusAvail a1 a2 = pprPanic "RnEnv.plusAvail" (hsep [ppr a1,ppr a2])
953 #endif
954
955 addAvail :: AvailEnv -> AvailInfo -> AvailEnv
956 addAvail avails avail = extendNameEnv_C plusAvail avails (availName avail) avail
957
958 unitAvailEnv :: AvailInfo -> AvailEnv
959 unitAvailEnv a = unitNameEnv (availName a) a
960
961 plusAvailEnv :: AvailEnv -> AvailEnv -> AvailEnv
962 plusAvailEnv = plusNameEnv_C plusAvail
963
964 availEnvElts = nameEnvElts
965
966 addAvailToNameSet :: NameSet -> AvailInfo -> NameSet
967 addAvailToNameSet names avail = addListToNameSet names (availNames avail)
968
969 availsToNameSet :: [AvailInfo] -> NameSet
970 availsToNameSet avails = foldl addAvailToNameSet emptyNameSet avails
971
972 availName :: GenAvailInfo name -> name
973 availName (Avail n)     = n
974 availName (AvailTC n _) = n
975
976 availNames :: GenAvailInfo name -> [name]
977 availNames (Avail n)      = [n]
978 availNames (AvailTC n ns) = ns
979
980 -------------------------------------
981 filterAvail :: RdrNameIE        -- Wanted
982             -> AvailInfo        -- Available
983             -> Maybe AvailInfo  -- Resulting available; 
984                                 -- Nothing if (any of the) wanted stuff isn't there
985
986 filterAvail ie@(IEThingWith want wants) avail@(AvailTC n ns)
987   | sub_names_ok = Just (AvailTC n (filter is_wanted ns))
988   | otherwise    = Nothing
989   where
990     is_wanted name = nameOccName name `elem` wanted_occs
991     sub_names_ok   = all (`elem` avail_occs) wanted_occs
992     avail_occs     = map nameOccName ns
993     wanted_occs    = map rdrNameOcc (want:wants)
994
995 filterAvail (IEThingAbs _) (AvailTC n ns)       = ASSERT( n `elem` ns ) 
996                                                   Just (AvailTC n [n])
997
998 filterAvail (IEThingAbs _) avail@(Avail n)      = Just avail            -- Type synonyms
999
1000 filterAvail (IEVar _)      avail@(Avail n)      = Just avail
1001 filterAvail (IEVar v)      avail@(AvailTC n ns) = Just (AvailTC n (filter wanted ns))
1002                                                 where
1003                                                   wanted n = nameOccName n == occ
1004                                                   occ      = rdrNameOcc v
1005         -- The second equation happens if we import a class op, thus
1006         --      import A( op ) 
1007         -- where op is a class operation
1008
1009 filterAvail (IEThingAll _) avail@(AvailTC _ _)   = Just avail
1010         -- We don't complain even if the IE says T(..), but
1011         -- no constrs/class ops of T are available
1012         -- Instead that's caught with a warning by the caller
1013
1014 filterAvail ie avail = Nothing
1015
1016 -------------------------------------
1017 groupAvails :: Module -> Avails -> [(ModuleName, Avails)]
1018   -- Group by module and sort by occurrence
1019   -- This keeps the list in canonical order
1020 groupAvails this_mod avails 
1021   = [ (mkSysModuleNameFS fs, sortLt lt avails)
1022     | (fs,avails) <- fmToList groupFM
1023     ]
1024   where
1025     groupFM :: FiniteMap FastString Avails
1026         -- Deliberately use the FastString so we
1027         -- get a canonical ordering
1028     groupFM = foldl add emptyFM avails
1029
1030     add env avail = addToFM_C combine env mod_fs [avail']
1031                   where
1032                     mod_fs = moduleNameFS (moduleName avail_mod)
1033                     avail_mod = case nameModule_maybe (availName avail) of
1034                                           Just m  -> m
1035                                           Nothing -> this_mod
1036                     combine old _ = avail':old
1037                     avail'        = sortAvail avail
1038
1039     a1 `lt` a2 = occ1 < occ2
1040                where
1041                  occ1  = nameOccName (availName a1)
1042                  occ2  = nameOccName (availName a2)
1043
1044 sortAvail :: AvailInfo -> AvailInfo
1045 -- Sort the sub-names into canonical order.
1046 -- The canonical order has the "main name" at the beginning 
1047 -- (if it's there at all)
1048 sortAvail (Avail n) = Avail n
1049 sortAvail (AvailTC n ns) | n `elem` ns = AvailTC n (n : sortLt lt (filter (/= n) ns))
1050                          | otherwise   = AvailTC n (    sortLt lt ns)
1051                          where
1052                            n1 `lt` n2 = nameOccName n1 < nameOccName n2
1053 \end{code}
1054
1055 \begin{code}
1056 pruneAvails :: (Name -> Bool)   -- Keep if this is True
1057             -> [AvailInfo]
1058             -> [AvailInfo]
1059 pruneAvails keep avails
1060   = mapMaybe del avails
1061   where
1062     del :: AvailInfo -> Maybe AvailInfo -- Nothing => nothing left!
1063     del (Avail n) | keep n    = Just (Avail n)
1064                   | otherwise = Nothing
1065     del (AvailTC n ns) | null ns'  = Nothing
1066                        | otherwise = Just (AvailTC n ns')
1067                        where
1068                          ns' = filter keep ns
1069 \end{code}
1070
1071 %************************************************************************
1072 %*                                                                      *
1073 \subsection{Free variable manipulation}
1074 %*                                                                      *
1075 %************************************************************************
1076
1077 \begin{code}
1078 -- A useful utility
1079 mapFvRn f xs = mapRn f xs       `thenRn` \ stuff ->
1080                let
1081                   (ys, fvs_s) = unzip stuff
1082                in
1083                returnRn (ys, plusFVs fvs_s)
1084 \end{code}
1085
1086
1087 %************************************************************************
1088 %*                                                                      *
1089 \subsection{Envt utility functions}
1090 %*                                                                      *
1091 %************************************************************************
1092
1093 \begin{code}
1094 warnUnusedModules :: [ModuleName] -> RnM d ()
1095 warnUnusedModules mods
1096   = ifOptRn Opt_WarnUnusedImports (mapRn_ (addWarnRn . unused_mod) mods)
1097   where
1098     unused_mod m = vcat [ptext SLIT("Module") <+> quotes (ppr m) <+> 
1099                            text "is imported, but nothing from it is used",
1100                          parens (ptext SLIT("except perhaps to re-export instances visible in") <+>
1101                                    quotes (ppr m))]
1102
1103 warnUnusedImports :: [(Name,Provenance)] -> RnM d ()
1104 warnUnusedImports names
1105   = ifOptRn Opt_WarnUnusedImports (warnUnusedBinds names)
1106
1107 warnUnusedLocalBinds, warnUnusedMatches :: [Name] -> RnM d ()
1108 warnUnusedLocalBinds names
1109   = ifOptRn Opt_WarnUnusedBinds (warnUnusedBinds [(n,LocalDef) | n<-names])
1110
1111 warnUnusedMatches names
1112   = ifOptRn Opt_WarnUnusedMatches (warnUnusedGroup [(n,LocalDef) | n<-names])
1113
1114 -------------------------
1115
1116 warnUnusedBinds :: [(Name,Provenance)] -> RnM d ()
1117 warnUnusedBinds names
1118   = mapRn_ warnUnusedGroup  groups
1119   where
1120         -- Group by provenance
1121    groups = equivClasses cmp names
1122    (_,prov1) `cmp` (_,prov2) = prov1 `compare` prov2
1123  
1124
1125 -------------------------
1126
1127 warnUnusedGroup :: [(Name,Provenance)] -> RnM d ()
1128 warnUnusedGroup names
1129   | null filtered_names  = returnRn ()
1130   | not is_local         = returnRn ()
1131   | otherwise
1132   = pushSrcLocRn def_loc        $
1133     addWarnRn                   $
1134     sep [msg <> colon, nest 4 (fsep (punctuate comma (map (ppr.fst) filtered_names)))]
1135   where
1136     filtered_names = filter reportable names
1137     (name1, prov1) = head filtered_names
1138     (is_local, def_loc, msg)
1139         = case prov1 of
1140                 LocalDef -> (True, getSrcLoc name1, text "Defined but not used")
1141
1142                 NonLocalDef (UserImport mod loc _)
1143                         -> (True, loc, text "Imported from" <+> quotes (ppr mod) <+> text "but not used")
1144
1145     reportable (name,_) = case occNameUserString (nameOccName name) of
1146                                 ('_' : _) -> False
1147                                 zz_other  -> True
1148         -- Haskell 98 encourages compilers to suppress warnings about
1149         -- unused names in a pattern if they start with "_".
1150 \end{code}
1151
1152 \begin{code}
1153 addNameClashErrRn rdr_name (np1:nps)
1154   = addErrRn (vcat [ptext SLIT("Ambiguous occurrence") <+> quotes (ppr rdr_name),
1155                     ptext SLIT("It could refer to") <+> vcat (msg1 : msgs)])
1156   where
1157     msg1 = ptext  SLIT("either") <+> mk_ref np1
1158     msgs = [ptext SLIT("    or") <+> mk_ref np | np <- nps]
1159     mk_ref (GRE name prov _) = quotes (ppr name) <> comma <+> pprNameProvenance name prov
1160
1161 shadowedNameWarn shadow
1162   = hsep [ptext SLIT("This binding for"), 
1163                quotes (ppr shadow),
1164                ptext SLIT("shadows an existing binding")]
1165
1166 noMainMsg = ptext SLIT("No 'main' defined in module Main")
1167
1168 unknownNameErr name
1169   = sep [text flavour, ptext SLIT("not in scope:"), quotes (ppr name)]
1170   where
1171     flavour = occNameFlavour (rdrNameOcc name)
1172
1173 badOrigBinding name
1174   = ptext SLIT("Illegal binding of built-in syntax:") <+> ppr (rdrNameOcc name)
1175         -- The rdrNameOcc is because we don't want to print Prelude.(,)
1176
1177 qualNameErr descriptor (name,loc)
1178   = pushSrcLocRn loc $
1179     addErrRn (vcat [ ptext SLIT("Invalid use of qualified name") <+> quotes (ppr name),
1180                      descriptor])
1181
1182 dupNamesErr descriptor ((name,loc) : dup_things)
1183   = pushSrcLocRn loc $
1184     addErrRn ((ptext SLIT("Conflicting definitions for") <+> quotes (ppr name))
1185               $$ 
1186               descriptor)
1187
1188 warnDeprec :: Name -> DeprecTxt -> RnM d ()
1189 warnDeprec name txt
1190   = ifOptRn Opt_WarnDeprecations        $
1191     addWarnRn (sep [ text (occNameFlavour (nameOccName name)) <+> 
1192                      quotes (ppr name) <+> text "is deprecated:", 
1193                      nest 4 (ppr txt) ])
1194
1195 dupFixityDecl rdr_name loc1 loc2
1196   = vcat [ptext SLIT("Multiple fixity declarations for") <+> quotes (ppr rdr_name),
1197           ptext SLIT("at ") <+> ppr loc1,
1198           ptext SLIT("and") <+> ppr loc2]
1199 \end{code}
1200