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