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