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