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