[project @ 2002-12-10 15:27:58 by simonpj]
[ghc-hetmet.git] / ghc / compiler / rename / RnEnv.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section[RnEnv]{Environment manipulation for the renamer monad}
5
6 \begin{code}
7 module RnEnv where              -- Export everything
8
9 #include "HsVersions.h"
10
11 import {-# SOURCE #-} RnHiFiles( loadInterface )
12
13 import FlattenInfo      ( namesNeededForFlattening )
14 import HsSyn
15 import RdrHsSyn         ( RdrNameHsType, RdrNameFixitySig, extractHsTyRdrTyVars )
16 import RdrName          ( RdrName, rdrNameModule, rdrNameOcc, isQual, isUnqual, isOrig,
17                           mkRdrUnqual, mkRdrQual, setRdrNameSpace, rdrNameOcc,
18                           lookupRdrEnv, rdrEnvToList, elemRdrEnv, 
19                           extendRdrEnv, addListToRdrEnv, emptyRdrEnv,
20                           isExact_maybe, unqualifyRdrName
21                         )
22 import HsTypes          ( hsTyVarName, replaceTyVarName )
23 import HscTypes         ( Provenance(..), pprNameProvenance, hasBetterProv,
24                           ImportReason(..), GlobalRdrEnv, GlobalRdrElt(..), 
25                           GenAvailInfo(..), AvailInfo, Avails, 
26                           ModIface(..), NameCache(..), OrigNameCache,
27                           Deprecations(..), lookupDeprec, isLocalGRE,
28                           extendLocalRdrEnv, availName, availNames,
29                           lookupFixity
30                         )
31 import TcRnMonad
32 import Name             ( Name, getName, getSrcLoc, nameIsLocalOrFrom, isWiredInName,
33                           mkInternalName, mkExternalName, mkIPName, nameSrcLoc,
34                           nameOccName, setNameSrcLoc, nameModule        )
35 import NameSet
36 import OccName          ( OccName, tcName, isDataOcc, occNameUserString, occNameFlavour )
37 import Module           ( Module, ModuleName, moduleName, mkHomeModule,
38                           lookupModuleEnv, lookupModuleEnvByName, extendModuleEnv_C )
39 import PrelNames        ( mkUnboundName, intTyConName, 
40                           boolTyConName, funTyConName,
41                           unpackCStringName, unpackCStringFoldrName, unpackCStringUtf8Name,
42                           eqStringName, printName, 
43                           bindIOName, returnIOName, failIOName, thenIOName
44                         )
45 #ifdef GHCI     
46 import DsMeta           ( templateHaskellNames, qTyConName )
47 #endif
48 import TysWiredIn       ( unitTyCon )   -- A little odd
49 import Finder           ( findModule )
50 import FiniteMap
51 import UniqSupply
52 import SrcLoc           ( SrcLoc, noSrcLoc, importedSrcLoc )
53 import Outputable
54 import ListSetOps       ( removeDups, equivClasses )
55 import BasicTypes       ( mapIPName, FixitySig(..) )
56 import List             ( nub )
57 import CmdLineOpts
58 import FastString       ( FastString )
59 \end{code}
60
61 %*********************************************************
62 %*                                                      *
63 \subsection{Making new names}
64 %*                                                      *
65 %*********************************************************
66
67 \begin{code}
68 newTopBinder :: Module -> RdrName -> SrcLoc -> TcRn m Name
69 newTopBinder mod rdr_name loc
70   | Just name <- isExact_maybe rdr_name
71   = returnM name
72
73   | otherwise
74   = newGlobalName mod (rdrNameOcc rdr_name) loc
75
76 newGlobalName :: Module -> OccName -> SrcLoc -> TcRn m Name
77 newGlobalName mod occ loc
78   =     -- First check the cache
79     getNameCache                `thenM` \ name_supply -> 
80     case lookupOrigNameCache (nsNames name_supply) mod occ of
81
82         -- A hit in the cache!  We are at the binding site of the name.
83         -- This is the moment when we know the defining SrcLoc
84         -- of the Name, so we set the SrcLoc of the name we return.
85         --
86         -- Main reason: then (bogus) multiple bindings of the same Name
87         --              get different SrcLocs can can be reported as such.
88         --
89         -- Possible other reason: it might be in the cache because we
90         --      encountered an occurrence before the binding site for an
91         --      implicitly-imported Name.  Perhaps the current SrcLoc is
92         --      better... but not really: it'll still just say 'imported'
93         --
94         -- IMPORTANT: Don't mess with wired-in names.  
95         --            Their wired-in-ness is in the SrcLoc
96
97         Just name | isWiredInName name -> returnM name
98                   | otherwise          -> returnM (setNameSrcLoc name loc)
99                      
100         -- Miss in the cache!
101         -- Build a completely new Name, and put it in the cache
102         Nothing -> addNewName name_supply mod occ loc
103
104 -- Look up a "system name" in the name cache.
105 -- This is done by the type checker... 
106 lookupSysName :: Name                   -- Base name
107               -> (OccName -> OccName)   -- Occurrence name modifier
108               -> TcRn m Name            -- System name
109 lookupSysName base_name mk_sys_occ
110   = newGlobalName (nameModule base_name)
111                   (mk_sys_occ (nameOccName base_name))
112                   (nameSrcLoc base_name)    
113
114
115 newGlobalNameFromRdrName rdr_name               -- Qualified original name
116  = newGlobalName2 (rdrNameModule rdr_name) (rdrNameOcc rdr_name)
117
118 newGlobalName2 :: ModuleName -> OccName -> TcRn m Name
119   -- This one starts with a ModuleName, not a Module, because 
120   -- we may be simply looking at an occurrence M.x in an interface file.
121   --
122   -- Used for *occurrences*.  Even if we get a miss in the
123   -- original-name cache, we make a new External Name.
124   -- We get its Module either from the OrigNameCache, or (if this
125   -- is the first Name from that module) from the Finder
126   --
127   -- In the case of a miss, we have to make up the SrcLoc, but that's
128   -- OK: it must be an implicitly-imported Name, and that never occurs
129   -- in an error message.
130
131 newGlobalName2 mod_name occ
132   = getNameCache                `thenM` \ name_supply ->
133     let
134         new_name mod = addNewName name_supply mod occ importedSrcLoc
135     in
136     case lookupModuleEnvByName (nsNames name_supply) mod_name of
137       Just (mod, occ_env) ->    
138         -- There are some names from this module already
139         -- Next, look up in the OccNameEnv
140         case lookupFM occ_env occ of
141              Just name -> returnM name
142              Nothing   -> new_name mod
143
144       Nothing   ->      -- No names from this module yet
145         ioToTcRn (findModule mod_name)          `thenM` \ mb_loc ->
146         case mb_loc of
147             Just (mod, _) -> new_name mod
148             Nothing       -> addErr (noModule mod_name) `thenM_`
149                                 -- Things have really gone wrong at this point,
150                                 -- so having the wrong package info in the 
151                                 -- Module is the least of our worries.
152                              new_name (mkHomeModule mod_name)
153   where
154     noModule mod_name = ptext SLIT("Can't find interface for module") <+> ppr mod_name
155
156
157 newIPName rdr_name_ip
158   = getNameCache                `thenM` \ name_supply ->
159     let
160         ipcache = nsIPs name_supply
161     in
162     case lookupFM ipcache key of
163         Just name_ip -> returnM name_ip
164         Nothing      -> setNameCache new_ns     `thenM_`
165                         returnM name_ip
166                   where
167                      (us', us1)  = splitUniqSupply (nsUniqs name_supply)
168                      uniq        = uniqFromSupply us1
169                      name_ip     = mapIPName mk_name rdr_name_ip
170                      mk_name rdr_name = mkIPName uniq (rdrNameOcc rdr_name)
171                      new_ipcache = addToFM ipcache key name_ip
172                      new_ns      = name_supply {nsUniqs = us', nsIPs = new_ipcache}
173     where 
174         key = rdr_name_ip       -- Ensures that ?x and %x get distinct Names
175
176 -- A local helper function
177 addNewName name_supply mod occ loc
178   = setNameCache new_name_supply        `thenM_`
179     returnM name
180   where
181     (new_name_supply, name) = newExternalName name_supply mod occ loc
182
183
184 newExternalName :: NameCache -> Module -> OccName -> SrcLoc 
185                   -> (NameCache,Name)
186 -- Allocate a new unique, manufacture a new External Name,
187 -- put it in the cache, and return the two
188 newExternalName name_supply mod occ loc
189   = (new_name_supply, name)
190   where
191      (us', us1)      = splitUniqSupply (nsUniqs name_supply)
192      uniq            = uniqFromSupply us1
193      name            = mkExternalName uniq mod occ loc
194      new_cache       = extend_name_cache (nsNames name_supply) mod occ name
195      new_name_supply = name_supply {nsUniqs = us', nsNames = new_cache}
196
197 lookupOrigNameCache :: OrigNameCache -> Module -> OccName -> Maybe Name
198 lookupOrigNameCache nc mod occ
199   = case lookupModuleEnv nc mod of
200         Nothing           -> Nothing
201         Just (_, occ_env) -> lookupFM occ_env occ
202
203 extendOrigNameCache :: OrigNameCache -> Name -> OrigNameCache
204 extendOrigNameCache nc name 
205   = extend_name_cache nc (nameModule name) (nameOccName name) name
206
207 extend_name_cache :: OrigNameCache -> Module -> OccName -> Name -> OrigNameCache
208 extend_name_cache nc mod occ name
209   = extendModuleEnv_C combine nc mod (mod, unitFM occ name)
210   where
211     combine (mod, occ_env) _ = (mod, addToFM occ_env occ name)
212 \end{code}
213
214 %*********************************************************
215 %*                                                      *
216 \subsection{Looking up names}
217 %*                                                      *
218 %*********************************************************
219
220 Looking up a name in the RnEnv.
221
222 \begin{code}
223 lookupBndrRn rdr_name
224   = getLocalRdrEnv              `thenM` \ local_env ->
225     case lookupRdrEnv local_env rdr_name of 
226           Just name -> returnM name
227           Nothing   -> lookupTopBndrRn rdr_name
228
229 lookupTopBndrRn rdr_name
230 -- Look up a top-level local binder.   We may be looking up an unqualified 'f',
231 -- and there may be several imported 'f's too, which must not confuse us.
232 -- So we have to filter out the non-local ones.
233 -- A separate function (importsFromLocalDecls) reports duplicate top level
234 -- decls, so here it's safe just to choose an arbitrary one.
235
236         -- There should never be a qualified name in a binding position 
237         -- The parser could check this, but doesn't (yet)
238   | isQual rdr_name
239   = getSrcLocM                                                  `thenM` \ loc ->
240     qualNameErr (text "In its declaration") (rdr_name,loc)      `thenM_`
241     returnM (mkUnboundName rdr_name)
242
243   | otherwise
244   = ASSERT( not (isOrig rdr_name) )
245         -- Original names are used only for occurrences, 
246         -- not binding sites
247
248     getModeRn                   `thenM` \ mode ->
249     case mode of
250         InterfaceMode mod -> 
251             getSrcLocM          `thenM` \ loc ->
252             newTopBinder mod rdr_name loc
253
254         other -> lookupTopSrcBndr rdr_name
255
256 lookupTopSrcBndr :: RdrName -> TcRn m Name
257 lookupTopSrcBndr rdr_name
258   = lookupTopSrcBndr_maybe rdr_name     `thenM` \ maybe_name ->
259     case maybe_name of
260         Just name -> returnM name
261         Nothing   -> unboundName rdr_name
262                                 
263
264 lookupTopSrcBndr_maybe :: RdrName -> TcRn m (Maybe Name)
265 -- Look up a source-code binder 
266
267 -- Ignores imported names; for example, this is OK:
268 --      import Foo( f )
269 --      infix 9 f       -- The 'f' here does not need to be qualified
270 --      f x = x         -- Nor here, of course
271
272 lookupTopSrcBndr_maybe rdr_name
273   | Just name <- isExact_maybe rdr_name
274         -- This is here just to catch the PrelBase defn of (say) [] and similar
275         -- The parser reads the special syntax and returns an Exact RdrName
276         -- But the global_env contains only Qual RdrNames, so we won't
277         -- find it there; instead just get the name via the Orig route
278         --
279         -- We are at a binding site for the name, so check first that it 
280         -- the current module is the correct one; otherwise GHC can get
281         -- very confused indeed.  This test rejects code like
282         --      data T = (,) Int Int
283         -- unless we are in GHC.Tup
284   = getModule                           `thenM` \ mod -> 
285     checkErr (moduleName mod == moduleName (nameModule name))
286              (badOrigBinding rdr_name)  `thenM_`
287     returnM (Just name)
288
289   | otherwise
290   = getGlobalRdrEnv                     `thenM` \ global_env ->
291     case lookupRdrEnv global_env rdr_name of
292           Nothing   -> returnM Nothing
293           Just gres -> case [gre_name gre | gre <- gres, isLocalGRE gre] of
294                          []     -> returnM Nothing
295                          (n:ns) -> returnM (Just n)
296               
297
298 -- lookupSigOccRn is used for type signatures and pragmas
299 -- Is this valid?
300 --   module A
301 --      import M( f )
302 --      f :: Int -> Int
303 --      f x = x
304 -- It's clear that the 'f' in the signature must refer to A.f
305 -- The Haskell98 report does not stipulate this, but it will!
306 -- So we must treat the 'f' in the signature in the same way
307 -- as the binding occurrence of 'f', using lookupBndrRn
308 lookupSigOccRn :: RdrName -> RnM Name
309 lookupSigOccRn = lookupBndrRn
310
311 -- lookupInstDeclBndr is used for the binders in an 
312 -- instance declaration.   Here we use the class name to
313 -- disambiguate.  
314
315 lookupInstDeclBndr :: Name -> RdrName -> RnM Name
316         -- We use the selector name as the binder
317 lookupInstDeclBndr cls_name rdr_name
318   | isUnqual rdr_name
319   =     -- Find all the things the class op name maps to
320         -- and pick the one with the right parent name
321     getGblEnv                           `thenM` \ gbl_env ->
322     let
323         avail_env = imp_env (tcg_imports gbl_env)
324     in
325     case lookupAvailEnv avail_env cls_name of
326         Nothing -> 
327             -- If the class itself isn't in scope, then cls_name will
328             -- be unboundName, and there'll already be an error for
329             -- that in the error list.  Example:
330             -- e.g.   import Prelude hiding( Ord )
331             --      instance Ord T where ...
332             -- The program is wrong, but that should not cause a crash.
333                 returnM (mkUnboundName rdr_name)
334
335         Just (AvailTC _ ns) -> case [n | n <- ns, nameOccName n == occ] of
336                                 (n:ns)-> ASSERT( null ns ) returnM n
337                                 []    -> unboundName rdr_name
338
339         other               -> pprPanic "lookupInstDeclBndr" (ppr cls_name)
340
341   | isQual rdr_name     -- Should never have a qualified name in a binding position
342   = getSrcLocM                                                  `thenM` \ loc ->
343     qualNameErr (text "In an instance method") (rdr_name,loc)   `thenM_`
344     returnM (mkUnboundName rdr_name)
345         
346   | otherwise           -- Occurs in derived instances, where we just
347                         -- refer directly to the right method, and avail_env
348                         -- isn't available
349   = ASSERT2( not (isQual rdr_name), ppr rdr_name )
350     lookupOrigName rdr_name
351
352   where
353     occ = rdrNameOcc rdr_name
354
355 lookupSysBndr :: RdrName -> RnM Name
356 -- Used for the 'system binders' in a data type or class declaration
357 -- Do *not* look up in the RdrEnv; these system binders are never in scope
358 -- Instead, get the module from the monad... but remember that
359 -- where the module is depends on whether we are renaming source or 
360 -- interface file stuff
361 lookupSysBndr rdr_name
362   = getSrcLocM          `thenM` \ loc ->
363     getModeRn           `thenM` \ mode ->
364     case mode of
365         InterfaceMode mod -> newTopBinder mod rdr_name loc
366         other             -> getModule  `thenM` \ mod ->
367                              newTopBinder mod rdr_name loc
368
369 -- lookupOccRn looks up an occurrence of a RdrName
370 lookupOccRn :: RdrName -> RnM Name
371 lookupOccRn rdr_name
372   = getLocalRdrEnv                      `thenM` \ local_env ->
373     case lookupRdrEnv local_env rdr_name of
374           Just name -> returnM name
375           Nothing   -> lookupGlobalOccRn rdr_name
376
377 -- lookupGlobalOccRn is like lookupOccRn, except that it looks in the global 
378 -- environment.  It's used only for
379 --      record field names
380 --      class op names in class and instance decls
381
382 lookupGlobalOccRn rdr_name
383   = getModeRn           `thenM` \ mode ->
384     case mode of
385         InterfaceMode mod -> lookupIfaceName mod rdr_name 
386         SourceMode        -> lookupSrcName       rdr_name 
387
388         CmdLineMode 
389          | not (isQual rdr_name) -> 
390                 lookupSrcName rdr_name
391
392                 -- We allow qualified names on the command line to refer to 
393                 -- *any* name exported by any module in scope, just as if 
394                 -- there was an "import qualified M" declaration for every 
395                 -- module.
396                 --
397                 -- First look up the name in the normal environment.  If
398                 -- it isn't there, we manufacture a new occurrence of an
399                 -- original name.
400          | otherwise -> 
401                 lookupSrcName_maybe rdr_name    `thenM` \ mb_name ->
402                 case mb_name of
403                   Just name -> returnM name
404                   Nothing   -> lookupQualifiedName rdr_name
405
406 -- A qualified name on the command line can refer to any module at all: we
407 -- try to load the interface if we don't already have it.
408 lookupQualifiedName :: RdrName -> TcRn m Name
409 lookupQualifiedName rdr_name
410  = let 
411        mod = rdrNameModule rdr_name
412        occ = rdrNameOcc rdr_name
413    in
414    loadInterface (ppr rdr_name) mod (ImportByUser False) `thenM` \ iface ->
415    case  [ name | (_,avails) <- mi_exports iface,
416            avail             <- avails,
417            name              <- availNames avail,
418            nameOccName name == occ ] of
419       (n:ns) -> ASSERT (null ns) returnM n
420       _      -> unboundName rdr_name
421
422 lookupSrcName :: RdrName -> TcRn m Name
423 lookupSrcName rdr_name
424   = lookupSrcName_maybe rdr_name        `thenM` \ mb_name ->
425     case mb_name of
426         Nothing   -> unboundName rdr_name
427         Just name -> returnM name
428                         
429 lookupSrcName_maybe :: RdrName -> TcRn m (Maybe Name)
430 lookupSrcName_maybe rdr_name
431   | Just name <- isExact_maybe rdr_name -- Can occur in source code too
432   = returnM (Just name)
433
434   | isOrig rdr_name                     -- An original name
435   = newGlobalNameFromRdrName rdr_name   `thenM` \ name ->
436     returnM (Just name)
437
438   | otherwise
439   = lookupGRE rdr_name  `thenM` \ mb_gre ->
440     case mb_gre of
441         Nothing  -> returnM Nothing
442         Just gre -> returnM (Just (gre_name gre))
443
444 lookupGRE :: RdrName -> TcRn m (Maybe GlobalRdrElt)
445 lookupGRE rdr_name
446   = getGlobalRdrEnv                     `thenM` \ global_env ->
447     case lookupRdrEnv global_env rdr_name of
448         Just [gre] -> case gre_deprec gre of
449                         Nothing -> returnM (Just gre)
450                         Just _  -> warnDeprec gre       `thenM_`
451                                    returnM (Just gre)
452         Just stuff@(gre : _) -> addNameClashErrRn rdr_name stuff        `thenM_`
453                                 returnM (Just gre)
454         Nothing              -> return Nothing
455                         
456 lookupIfaceName :: Module -> RdrName -> TcRn m Name
457         -- An Unqual is allowed; interface files contain 
458         -- unqualified names for locally-defined things, such as
459         -- constructors of a data type.
460 lookupIfaceName mod rdr_name
461   | isUnqual rdr_name = newGlobalName mod (rdrNameOcc rdr_name) importedSrcLoc
462   | otherwise         = lookupOrigName rdr_name
463
464 lookupOrigName :: RdrName -> TcRn m Name
465         -- Just for original or exact names
466 lookupOrigName rdr_name
467   | Just n <- isExact_maybe rdr_name 
468         -- This happens in derived code, which we 
469         -- rename in InterfaceMode
470   = returnM n
471
472   | otherwise   -- Usually Orig, but can be a Qual when 
473                 -- we are reading a .hi-boot file
474   = newGlobalNameFromRdrName rdr_name
475
476
477 dataTcOccs :: RdrName -> [RdrName]
478 -- If the input is a data constructor, return both it and a type
479 -- constructor.  This is useful when we aren't sure which we are
480 -- looking at
481 dataTcOccs rdr_name
482   | isDataOcc occ = [rdr_name, rdr_name_tc]
483   | otherwise     = [rdr_name]
484   where    
485     occ         = rdrNameOcc rdr_name
486     rdr_name_tc = setRdrNameSpace rdr_name tcName
487 \end{code}
488
489 \begin{code}
490 unboundName rdr_name = addErr (unknownNameErr rdr_name) `thenM_`
491                        returnM (mkUnboundName rdr_name)
492 \end{code}
493
494 %*********************************************************
495 %*                                                      *
496                 Fixities
497 %*                                                      *
498 %*********************************************************
499
500 \begin{code}
501 --------------------------------
502 bindLocalFixities :: [RdrNameFixitySig] -> RnM a -> RnM a
503 -- Used for nested fixity decls
504 -- No need to worry about type constructors here,
505 -- Should check for duplicates but we don't
506 bindLocalFixities fixes thing_inside
507   | null fixes = thing_inside
508   | otherwise  = mappM rn_sig fixes     `thenM` \ new_bit ->
509                  extendFixityEnv new_bit thing_inside
510   where
511     rn_sig (FixitySig v fix src_loc)
512         = addSrcLoc src_loc $
513           lookupSigOccRn v              `thenM` \ new_v ->
514           returnM (new_v, FixitySig new_v fix src_loc)
515 \end{code}
516
517 --------------------------------
518 lookupFixity is a bit strange.  
519
520 * Nested local fixity decls are put in the local fixity env, which we
521   find with getFixtyEnv
522
523 * Imported fixities are found in the HIT or PIT
524
525 * Top-level fixity decls in this module may be for Names that are
526     either  Global         (constructors, class operations)
527     or      Local/Exported (everything else)
528   (See notes with RnNames.getLocalDeclBinders for why we have this split.)
529   We put them all in the local fixity environment
530
531 \begin{code}
532 lookupFixityRn :: Name -> RnM Fixity
533 lookupFixityRn name
534   = getModule                           `thenM` \ this_mod ->
535     if nameIsLocalOrFrom this_mod name
536     then        -- It's defined in this module
537         getFixityEnv            `thenM` \ local_fix_env ->
538         returnM (lookupFixity local_fix_env name)
539
540     else        -- It's imported
541       -- For imported names, we have to get their fixities by doing a
542       -- loadHomeInterface, and consulting the Ifaces that comes back
543       -- from that, because the interface file for the Name might not
544       -- have been loaded yet.  Why not?  Suppose you import module A,
545       -- which exports a function 'f', thus;
546       --        module CurrentModule where
547       --          import A( f )
548       --        module A( f ) where
549       --          import B( f )
550       -- Then B isn't loaded right away (after all, it's possible that
551       -- nothing from B will be used).  When we come across a use of
552       -- 'f', we need to know its fixity, and it's then, and only
553       -- then, that we load B.hi.  That is what's happening here.
554         loadInterface doc name_mod ImportBySystem       `thenM` \ iface ->
555         returnM (lookupFixity (mi_fixities iface) name)
556   where
557     doc      = ptext SLIT("Checking fixity for") <+> ppr name
558     name_mod = moduleName (nameModule name)
559 \end{code}
560
561
562 %*********************************************************
563 %*                                                      *
564 \subsection{Implicit free vars and sugar names}
565 %*                                                      *
566 %*********************************************************
567
568 @getXImplicitFVs@ forces the renamer to slurp in some things which aren't
569 mentioned explicitly, but which might be needed by the type checker.
570
571 \begin{code}
572 implicitStmtFVs source_fvs      -- Compiling a statement
573   = stmt_fvs `plusFV` implicitModuleFVs source_fvs
574   where
575     stmt_fvs = mkFVs [printName, bindIOName, thenIOName, returnIOName, failIOName]
576                 -- These are all needed implicitly when compiling a statement
577                 -- See TcModule.tc_stmts
578
579 implicitModuleFVs source_fvs
580   = mkTemplateHaskellFVs source_fvs     `plusFV` 
581     namesNeededForFlattening            `plusFV`
582     ubiquitousNames
583
584
585 thProxyName :: NameSet
586 mkTemplateHaskellFVs :: NameSet -> NameSet
587         -- This is a bit of a hack.  When we see the Template-Haskell construct
588         --      [| expr |]
589         -- we are going to need lots of the ``smart constructors'' defined in
590         -- the main Template Haskell data type module.  Rather than treat them
591         -- all as free vars at every occurrence site, we just make the Q type
592         -- consructor a free var.... and then use that here to haul in the others
593
594 #ifdef GHCI
595 --------------- Template Haskell enabled --------------
596 thProxyName = unitFV qTyConName
597
598 mkTemplateHaskellFVs source_fvs
599   | qTyConName `elemNameSet` source_fvs = templateHaskellNames
600   | otherwise                           = emptyFVs
601
602 #else
603 --------------- Template Haskell disabled --------------
604
605 thProxyName                     = emptyFVs
606 mkTemplateHaskellFVs source_fvs = emptyFVs
607 #endif
608 --------------------------------------------------------
609
610 -- ubiquitous_names are loaded regardless, because 
611 -- they are needed in virtually every program
612 ubiquitousNames 
613   = mkFVs [unpackCStringName, unpackCStringFoldrName, 
614            unpackCStringUtf8Name, eqStringName,
615                 -- Virtually every program has error messages in it somewhere
616            getName unitTyCon, funTyConName, boolTyConName, intTyConName]
617                 -- Add occurrences for very frequently used types.
618                 --       (e.g. we don't want to be bothered with making 
619                 --        funTyCon a free var at every function application!)
620 \end{code}
621
622 %************************************************************************
623 %*                                                                      *
624 \subsection{Re-bindable desugaring names}
625 %*                                                                      *
626 %************************************************************************
627
628 Haskell 98 says that when you say "3" you get the "fromInteger" from the
629 Standard Prelude, regardless of what is in scope.   However, to experiment
630 with having a language that is less coupled to the standard prelude, we're
631 trying a non-standard extension that instead gives you whatever "Prelude.fromInteger"
632 happens to be in scope.  Then you can
633         import Prelude ()
634         import MyPrelude as Prelude
635 to get the desired effect.
636
637 At the moment this just happens for
638   * fromInteger, fromRational on literals (in expressions and patterns)
639   * negate (in expressions)
640   * minus  (arising from n+k patterns)
641   * "do" notation
642
643 We store the relevant Name in the HsSyn tree, in 
644   * HsIntegral/HsFractional     
645   * NegApp
646   * NPlusKPatIn
647   * HsDo
648 respectively.  Initially, we just store the "standard" name (PrelNames.fromIntegralName,
649 fromRationalName etc), but the renamer changes this to the appropriate user
650 name if Opt_NoImplicitPrelude is on.  That is what lookupSyntaxName does.
651
652 We treat the orignal (standard) names as free-vars too, because the type checker
653 checks the type of the user thing against the type of the standard thing.
654
655 \begin{code}
656 lookupSyntaxName :: Name                        -- The standard name
657                  -> RnM (Name, FreeVars)        -- Possibly a non-standard name
658 lookupSyntaxName std_name
659   = getModeRn                           `thenM` \ mode ->
660     if isInterfaceMode mode then
661         returnM (std_name, unitFV std_name)
662                                 -- Happens for 'derived' code
663                                 -- where we don't want to rebind
664     else
665
666     doptM Opt_NoImplicitPrelude         `thenM` \ no_prelude -> 
667     if not no_prelude then
668         returnM (std_name, unitFV std_name)     -- Normal case
669
670     else
671         -- Get the similarly named thing from the local environment
672     lookupOccRn (mkRdrUnqual (nameOccName std_name)) `thenM` \ usr_name ->
673     returnM (usr_name, mkFVs [usr_name, std_name])
674 \end{code}
675
676
677 %*********************************************************
678 %*                                                      *
679 \subsection{Binding}
680 %*                                                      *
681 %*********************************************************
682
683 \begin{code}
684 newLocalsRn :: [(RdrName,SrcLoc)]
685             -> RnM [Name]
686 newLocalsRn rdr_names_w_loc
687  =  newUniqueSupply             `thenM` \ us ->
688     let
689         uniqs      = uniqsFromSupply us
690         names      = [ mkInternalName uniq (rdrNameOcc rdr_name) loc
691                      | ((rdr_name,loc), uniq) <- rdr_names_w_loc `zip` uniqs
692                      ]
693     in
694     returnM names
695
696
697 bindLocatedLocalsRn :: SDoc     -- Documentation string for error message
698                     -> [(RdrName,SrcLoc)]
699                     -> ([Name] -> RnM a)
700                     -> RnM a
701 bindLocatedLocalsRn doc_str rdr_names_w_loc enclosed_scope
702   = getModeRn                   `thenM` \ mode ->
703     getLocalRdrEnv              `thenM` \ local_env ->
704     getGlobalRdrEnv             `thenM` \ global_env ->
705
706         -- Check for duplicate names
707     checkDupOrQualNames doc_str rdr_names_w_loc `thenM_`
708
709         -- Warn about shadowing, but only in source modules
710     let
711       check_shadow (rdr_name,loc)
712         |  rdr_name `elemRdrEnv` local_env 
713         || rdr_name `elemRdrEnv` global_env 
714         = addSrcLoc loc $ addWarn (shadowedNameWarn rdr_name)
715         | otherwise 
716         = returnM ()
717     in
718
719     (case mode of
720         SourceMode -> ifOptM Opt_WarnNameShadowing      $
721                       mappM_ check_shadow rdr_names_w_loc
722         other      -> returnM ()
723     )                                   `thenM_`
724
725     newLocalsRn rdr_names_w_loc         `thenM` \ names ->
726     let
727         new_local_env = addListToRdrEnv local_env (map fst rdr_names_w_loc `zip` names)
728     in
729     setLocalRdrEnv new_local_env (enclosed_scope names)
730
731 bindCoreLocalRn :: RdrName -> (Name -> RnM a) -> RnM a
732   -- A specialised variant when renaming stuff from interface
733   -- files (of which there is a lot)
734   --    * one at a time
735   --    * no checks for shadowing
736   --    * always imported
737   --    * deal with free vars
738 bindCoreLocalRn rdr_name enclosed_scope
739   = getSrcLocM          `thenM` \ loc ->
740     getLocalRdrEnv              `thenM` \ name_env ->
741     newUnique                   `thenM` \ uniq ->
742     let
743         name         = mkInternalName uniq (rdrNameOcc rdr_name) loc
744         new_name_env = extendRdrEnv name_env rdr_name name
745     in
746     setLocalRdrEnv new_name_env (enclosed_scope name)
747
748 bindCoreLocalsRn []     thing_inside = thing_inside []
749 bindCoreLocalsRn (b:bs) thing_inside = bindCoreLocalRn b        $ \ name' ->
750                                        bindCoreLocalsRn bs      $ \ names' ->
751                                        thing_inside (name':names')
752
753 bindLocalNames names enclosed_scope
754   = getLocalRdrEnv              `thenM` \ name_env ->
755     setLocalRdrEnv (extendLocalRdrEnv name_env names)
756                     enclosed_scope
757
758 bindLocalNamesFV names enclosed_scope
759   = bindLocalNames names $
760     enclosed_scope `thenM` \ (thing, fvs) ->
761     returnM (thing, delListFromNameSet fvs names)
762
763
764 -------------------------------------
765 bindLocalRn doc rdr_name enclosed_scope
766   = getSrcLocM                          `thenM` \ loc ->
767     bindLocatedLocalsRn doc [(rdr_name,loc)]    $ \ (n:ns) ->
768     ASSERT( null ns )
769     enclosed_scope n
770
771 bindLocalsRn doc rdr_names enclosed_scope
772   = getSrcLocM          `thenM` \ loc ->
773     bindLocatedLocalsRn doc
774                         (rdr_names `zip` repeat loc)
775                         enclosed_scope
776
777         -- binLocalsFVRn is the same as bindLocalsRn
778         -- except that it deals with free vars
779 bindLocalsFVRn doc rdr_names enclosed_scope
780   = bindLocalsRn doc rdr_names          $ \ names ->
781     enclosed_scope names                `thenM` \ (thing, fvs) ->
782     returnM (thing, delListFromNameSet fvs names)
783
784 -------------------------------------
785 extendTyVarEnvFVRn :: [Name] -> RnM (a, FreeVars) -> RnM (a, FreeVars)
786         -- This tiresome function is used only in rnSourceDecl on InstDecl
787 extendTyVarEnvFVRn tyvars enclosed_scope
788   = bindLocalNames tyvars enclosed_scope        `thenM` \ (thing, fvs) -> 
789     returnM (thing, delListFromNameSet fvs tyvars)
790
791 bindTyVarsRn :: SDoc -> [HsTyVarBndr RdrName]
792               -> ([HsTyVarBndr Name] -> RnM a)
793               -> RnM a
794 bindTyVarsRn doc_str tyvar_names enclosed_scope
795   = getSrcLocM                                  `thenM` \ loc ->
796     let
797         located_tyvars = [(hsTyVarName tv, loc) | tv <- tyvar_names] 
798     in
799     bindLocatedLocalsRn doc_str located_tyvars  $ \ names ->
800     enclosed_scope (zipWith replaceTyVarName tyvar_names names)
801
802 bindPatSigTyVars :: [RdrNameHsType]
803                  -> RnM (a, FreeVars)
804                  -> RnM (a, FreeVars)
805   -- Find the type variables in the pattern type 
806   -- signatures that must be brought into scope
807
808 bindPatSigTyVars tys enclosed_scope
809   = getLocalRdrEnv              `thenM` \ name_env ->
810     getSrcLocM                  `thenM` \ loc ->
811     let
812         forall_tyvars  = nub [ tv | ty <- tys,
813                                     tv <- extractHsTyRdrTyVars ty, 
814                                     not (tv `elemFM` name_env)
815                          ]
816                 -- The 'nub' is important.  For example:
817                 --      f (x :: t) (y :: t) = ....
818                 -- We don't want to complain about binding t twice!
819
820         located_tyvars = [(tv, loc) | tv <- forall_tyvars] 
821         doc_sig        = text "In a pattern type-signature"
822     in
823     bindLocatedLocalsRn doc_sig located_tyvars  $ \ names ->
824     enclosed_scope                              `thenM` \ (thing, fvs) ->
825     returnM (thing, delListFromNameSet fvs names)
826
827
828 -------------------------------------
829 checkDupOrQualNames, checkDupNames :: SDoc
830                                    -> [(RdrName, SrcLoc)]
831                                    -> TcRn m ()
832         -- Works in any variant of the renamer monad
833
834 checkDupOrQualNames doc_str rdr_names_w_loc
835   =     -- Check for use of qualified names
836     mappM_ (qualNameErr doc_str) quals  `thenM_`
837     checkDupNames doc_str rdr_names_w_loc
838   where
839     quals = filter (isQual . fst) rdr_names_w_loc
840     
841 checkDupNames doc_str rdr_names_w_loc
842   =     -- Check for duplicated names in a binding group
843     mappM_ (dupNamesErr doc_str) dups
844   where
845     (_, dups) = removeDups (\(n1,l1) (n2,l2) -> n1 `compare` n2) rdr_names_w_loc
846 \end{code}
847
848
849 %************************************************************************
850 %*                                                                      *
851 \subsection{GlobalRdrEnv}
852 %*                                                                      *
853 %************************************************************************
854
855 \begin{code}
856 mkGlobalRdrEnv :: ModuleName            -- Imported module (after doing the "as M" name change)
857                -> Bool                  -- True <=> want unqualified import
858                -> (Name -> Provenance)
859                -> Avails                -- Whats imported
860                -> Deprecations
861                -> GlobalRdrEnv
862
863 mkGlobalRdrEnv this_mod unqual_imp mk_provenance avails deprecs
864   = gbl_env2
865   where
866         -- Make the name environment.  We're talking about a 
867         -- single module here, so there must be no name clashes.
868         -- In practice there only ever will be if it's the module
869         -- being compiled.
870
871         -- Add qualified names for the things that are available
872         -- (Qualified names are always imported)
873     gbl_env1 = foldl add_avail emptyRdrEnv avails
874
875         -- Add unqualified names
876     gbl_env2 | unqual_imp = foldl add_unqual gbl_env1 (rdrEnvToList gbl_env1)
877              | otherwise  = gbl_env1
878
879     add_unqual env (qual_name, elts)
880         = foldl add_one env elts
881         where
882           add_one env elt = addOneToGlobalRdrEnv env unqual_name elt
883           unqual_name     = unqualifyRdrName qual_name
884         -- The qualified import should only have added one 
885         -- binding for each qualified name!  But if there's an error in
886         -- the module (multiple bindings for the same name) we may get
887         -- duplicates.  So the simple thing is to do the fold.
888
889     add_avail :: GlobalRdrEnv -> AvailInfo -> GlobalRdrEnv
890     add_avail env avail = foldl (add_name (availName avail)) env (availNames avail)
891
892     add_name parent env name    -- Add qualified name only
893         = addOneToGlobalRdrEnv env (mkRdrQual this_mod occ) elt
894         where
895           occ  = nameOccName name
896           elt  = GRE {gre_name   = name,
897                       gre_parent = parent, 
898                       gre_prov   = mk_provenance name, 
899                       gre_deprec = lookupDeprec deprecs name}
900                       
901 \end{code}
902
903 \begin{code}
904 plusGlobalRdrEnv :: GlobalRdrEnv -> GlobalRdrEnv -> GlobalRdrEnv
905 plusGlobalRdrEnv env1 env2 = plusFM_C combine_globals env1 env2
906
907 addOneToGlobalRdrEnv :: GlobalRdrEnv -> RdrName -> GlobalRdrElt -> GlobalRdrEnv
908 addOneToGlobalRdrEnv env rdr_name name = addToFM_C combine_globals env rdr_name [name]
909
910 delOneFromGlobalRdrEnv :: GlobalRdrEnv -> RdrName -> GlobalRdrEnv 
911 delOneFromGlobalRdrEnv env rdr_name = delFromFM env rdr_name
912
913 combine_globals :: [GlobalRdrElt]       -- Old
914                 -> [GlobalRdrElt]       -- New
915                 -> [GlobalRdrElt]
916 combine_globals ns_old ns_new   -- ns_new is often short
917   = foldr add ns_old ns_new
918   where
919     add n ns | any (is_duplicate n) ns_old = map (choose n) ns  -- Eliminate duplicates
920              | otherwise                   = n:ns
921
922     choose n m | n `beats` m = n
923                | otherwise   = m
924
925     g1 `beats` g2 = gre_name g1 == gre_name g2 && 
926                     gre_prov g1 `hasBetterProv` gre_prov g2
927
928     is_duplicate :: GlobalRdrElt -> GlobalRdrElt -> Bool
929     is_duplicate g1 g2 | isLocalGRE g1 && isLocalGRE g2 = False
930     is_duplicate g1 g2 = gre_name g1 == gre_name g2
931 \end{code}
932
933 We treat two bindings of a locally-defined name as a duplicate,
934 because they might be two separate, local defns and we want to report
935 and error for that, {\em not} eliminate a duplicate.
936
937 On the other hand, if you import the same name from two different
938 import statements, we {\em do} want to eliminate the duplicate, not report
939 an error.
940
941 If a module imports itself then there might be a local defn and an imported
942 defn of the same name; in this case the names will compare as equal, but
943 will still have different provenances.
944
945
946 %************************************************************************
947 %*                                                                      *
948 \subsection{Free variable manipulation}
949 %*                                                                      *
950 %************************************************************************
951
952 \begin{code}
953 -- A useful utility
954 mapFvRn f xs = mappM f xs       `thenM` \ stuff ->
955                let
956                   (ys, fvs_s) = unzip stuff
957                in
958                returnM (ys, plusFVs fvs_s)
959 \end{code}
960
961
962 %************************************************************************
963 %*                                                                      *
964 \subsection{Envt utility functions}
965 %*                                                                      *
966 %************************************************************************
967
968 \begin{code}
969 warnUnusedModules :: [ModuleName] -> TcRn m ()
970 warnUnusedModules mods
971   = ifOptM Opt_WarnUnusedImports (mappM_ (addWarn . unused_mod) mods)
972   where
973     unused_mod m = vcat [ptext SLIT("Module") <+> quotes (ppr m) <+> 
974                            text "is imported, but nothing from it is used",
975                          parens (ptext SLIT("except perhaps instances visible in") <+>
976                                    quotes (ppr m))]
977
978 warnUnusedImports, warnUnusedTopBinds :: [GlobalRdrElt] -> TcRn m ()
979 warnUnusedImports gres  = ifOptM Opt_WarnUnusedImports (warnUnusedGREs gres)
980 warnUnusedTopBinds gres = ifOptM Opt_WarnUnusedBinds   (warnUnusedGREs gres)
981
982 warnUnusedLocalBinds, warnUnusedMatches :: [Name] -> TcRn m ()
983 warnUnusedLocalBinds names = ifOptM Opt_WarnUnusedBinds   (warnUnusedLocals names)
984 warnUnusedMatches    names = ifOptM Opt_WarnUnusedMatches (warnUnusedLocals names)
985
986 -------------------------
987 --      Helpers
988 warnUnusedGREs   gres  = warnUnusedBinds [(n,p) | GRE {gre_name = n, gre_prov = p} <- gres]
989 warnUnusedLocals names = warnUnusedBinds [(n,LocalDef) | n<-names]
990
991 warnUnusedBinds :: [(Name,Provenance)] -> TcRn m ()
992 warnUnusedBinds names
993   = mappM_ warnUnusedGroup  groups
994   where
995         -- Group by provenance
996    groups = equivClasses cmp names
997    (_,prov1) `cmp` (_,prov2) = prov1 `compare` prov2
998  
999
1000 -------------------------
1001
1002 warnUnusedGroup :: [(Name,Provenance)] -> TcRn m ()
1003 warnUnusedGroup names
1004   | null filtered_names  = returnM ()
1005   | not is_local         = returnM ()
1006   | otherwise
1007   = addSrcLoc def_loc   $
1008     addWarn                     $
1009     sep [msg <> colon, nest 4 (fsep (punctuate comma (map (ppr.fst) filtered_names)))]
1010   where
1011     filtered_names = filter reportable names
1012     (name1, prov1) = head filtered_names
1013     (is_local, def_loc, msg)
1014         = case prov1 of
1015                 LocalDef -> (True, getSrcLoc name1, text "Defined but not used")
1016
1017                 NonLocalDef (UserImport mod loc _)
1018                         -> (True, loc, text "Imported from" <+> quotes (ppr mod) <+> text "but not used")
1019
1020     reportable (name,_) = case occNameUserString (nameOccName name) of
1021                                 ('_' : _) -> False
1022                                 zz_other  -> True
1023         -- Haskell 98 encourages compilers to suppress warnings about
1024         -- unused names in a pattern if they start with "_".
1025 \end{code}
1026
1027 \begin{code}
1028 addNameClashErrRn rdr_name (np1:nps)
1029   = addErr (vcat [ptext SLIT("Ambiguous occurrence") <+> quotes (ppr rdr_name),
1030                     ptext SLIT("It could refer to") <+> vcat (msg1 : msgs)])
1031   where
1032     msg1 = ptext  SLIT("either") <+> mk_ref np1
1033     msgs = [ptext SLIT("    or") <+> mk_ref np | np <- nps]
1034     mk_ref gre = quotes (ppr (gre_name gre)) <> comma <+> pprNameProvenance gre
1035
1036 shadowedNameWarn shadow
1037   = hsep [ptext SLIT("This binding for"), 
1038                quotes (ppr shadow),
1039                ptext SLIT("shadows an existing binding")]
1040
1041 unknownNameErr name
1042   = sep [text flavour, ptext SLIT("not in scope:"), quotes (ppr name)]
1043   where
1044     flavour = occNameFlavour (rdrNameOcc name)
1045
1046 badOrigBinding name
1047   = ptext SLIT("Illegal binding of built-in syntax:") <+> ppr (rdrNameOcc name)
1048         -- The rdrNameOcc is because we don't want to print Prelude.(,)
1049
1050 qualNameErr descriptor (name,loc)
1051   = addSrcLoc loc $
1052     addErr (vcat [ ptext SLIT("Invalid use of qualified name") <+> quotes (ppr name),
1053                      descriptor])
1054
1055 dupNamesErr descriptor ((name,loc) : dup_things)
1056   = addSrcLoc loc $
1057     addErr ((ptext SLIT("Conflicting definitions for") <+> quotes (ppr name))
1058               $$ 
1059               descriptor)
1060
1061 warnDeprec :: GlobalRdrElt -> TcRn m ()
1062 warnDeprec (GRE {gre_name = name, gre_deprec = Just txt})
1063   = ifOptM Opt_WarnDeprecations $
1064     addWarn (sep [ text (occNameFlavour (nameOccName name)) <+> 
1065                      quotes (ppr name) <+> text "is deprecated:", 
1066                      nest 4 (ppr txt) ])
1067 \end{code}
1068