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