[project @ 2003-07-09 11:06:31 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 dataTcOccs rdr_name
488   | isDataOcc occ = [rdr_name, rdr_name_tc]
489   | otherwise     = [rdr_name]
490   where    
491     occ         = rdrNameOcc rdr_name
492     rdr_name_tc = setRdrNameSpace rdr_name tcName
493 \end{code}
494
495 \begin{code}
496 unboundName rdr_name = addErr (unknownNameErr rdr_name) `thenM_`
497                        returnM (mkUnboundName rdr_name)
498 \end{code}
499
500 %*********************************************************
501 %*                                                      *
502                 Fixities
503 %*                                                      *
504 %*********************************************************
505
506 \begin{code}
507 --------------------------------
508 bindLocalFixities :: [RdrNameFixitySig] -> RnM a -> RnM a
509 -- Used for nested fixity decls
510 -- No need to worry about type constructors here,
511 -- Should check for duplicates but we don't
512 bindLocalFixities fixes thing_inside
513   | null fixes = thing_inside
514   | otherwise  = mappM rn_sig fixes     `thenM` \ new_bit ->
515                  extendFixityEnv new_bit thing_inside
516   where
517     rn_sig (FixitySig v fix src_loc)
518         = addSrcLoc src_loc $
519           lookupSigOccRn v              `thenM` \ new_v ->
520           returnM (new_v, FixitySig new_v fix src_loc)
521 \end{code}
522
523 --------------------------------
524 lookupFixity is a bit strange.  
525
526 * Nested local fixity decls are put in the local fixity env, which we
527   find with getFixtyEnv
528
529 * Imported fixities are found in the HIT or PIT
530
531 * Top-level fixity decls in this module may be for Names that are
532     either  Global         (constructors, class operations)
533     or      Local/Exported (everything else)
534   (See notes with RnNames.getLocalDeclBinders for why we have this split.)
535   We put them all in the local fixity environment
536
537 \begin{code}
538 lookupFixityRn :: Name -> RnM Fixity
539 lookupFixityRn name
540   = getModule                           `thenM` \ this_mod ->
541     if nameIsLocalOrFrom this_mod name
542     then        -- It's defined in this module
543         getFixityEnv            `thenM` \ local_fix_env ->
544         returnM (lookupFixity local_fix_env name)
545
546     else        -- It's imported
547       -- For imported names, we have to get their fixities by doing a
548       -- loadHomeInterface, and consulting the Ifaces that comes back
549       -- from that, because the interface file for the Name might not
550       -- have been loaded yet.  Why not?  Suppose you import module A,
551       -- which exports a function 'f', thus;
552       --        module CurrentModule where
553       --          import A( f )
554       --        module A( f ) where
555       --          import B( f )
556       -- Then B isn't loaded right away (after all, it's possible that
557       -- nothing from B will be used).  When we come across a use of
558       -- 'f', we need to know its fixity, and it's then, and only
559       -- then, that we load B.hi.  That is what's happening here.
560         loadInterface doc name_mod ImportBySystem       `thenM` \ iface ->
561         returnM (lookupFixity (mi_fixities iface) name)
562   where
563     doc      = ptext SLIT("Checking fixity for") <+> ppr name
564     name_mod = moduleName (nameModule name)
565 \end{code}
566
567
568 %*********************************************************
569 %*                                                      *
570 \subsection{Implicit free vars and sugar names}
571 %*                                                      *
572 %*********************************************************
573
574 @getXImplicitFVs@ forces the renamer to slurp in some things which aren't
575 mentioned explicitly, but which might be needed by the type checker.
576
577 \begin{code}
578 implicitStmtFVs source_fvs      -- Compiling a statement
579   = stmt_fvs `plusFV` implicitModuleFVs source_fvs
580   where
581     stmt_fvs = mkFVs [printName, bindIOName, thenIOName, returnIOName, failIOName, 
582                       integerTyConName]
583                 -- These are all needed implicitly when compiling a statement
584                 -- See TcModule.tc_stmts
585         -- Reason for integerTyConName: consider this in GHCi
586         --      ghci>  []
587         -- We get an ambigous constraint (Show a), which we now default just like
588         -- numeric types... but unless we have the instance decl for Integer we 
589         -- won't find a valid default!
590
591 implicitModuleFVs source_fvs
592   = mkTemplateHaskellFVs source_fvs     `plusFV` 
593     namesNeededForFlattening            `plusFV`
594     ubiquitousNames
595
596
597 thProxyName :: NameSet
598 mkTemplateHaskellFVs :: NameSet -> NameSet
599         -- This is a bit of a hack.  When we see the Template-Haskell construct
600         --      [| expr |]
601         -- we are going to need lots of the ``smart constructors'' defined in
602         -- the main Template Haskell data type module.  Rather than treat them
603         -- all as free vars at every occurrence site, we just make the Q type
604         -- consructor a free var.... and then use that here to haul in the others
605
606 #ifdef GHCI
607 --------------- Template Haskell enabled --------------
608 thProxyName = unitFV qTyConName
609
610 mkTemplateHaskellFVs source_fvs
611   | qTyConName `elemNameSet` source_fvs = templateHaskellNames
612   | otherwise                           = emptyFVs
613
614 #else
615 --------------- Template Haskell disabled --------------
616
617 thProxyName                     = emptyFVs
618 mkTemplateHaskellFVs source_fvs = emptyFVs
619 #endif
620 --------------------------------------------------------
621
622 -- ubiquitous_names are loaded regardless, because 
623 -- they are needed in virtually every program
624 ubiquitousNames 
625   = mkFVs [unpackCStringName, unpackCStringFoldrName, 
626            unpackCStringUtf8Name, eqStringName,
627                 -- Virtually every program has error messages in it somewhere
628            getName unitTyCon, funTyConName, boolTyConName, intTyConName]
629                 -- Add occurrences for very frequently used types.
630                 --       (e.g. we don't want to be bothered with making 
631                 --        funTyCon a free var at every function application!)
632 \end{code}
633
634 %************************************************************************
635 %*                                                                      *
636 \subsection{Re-bindable desugaring names}
637 %*                                                                      *
638 %************************************************************************
639
640 Haskell 98 says that when you say "3" you get the "fromInteger" from the
641 Standard Prelude, regardless of what is in scope.   However, to experiment
642 with having a language that is less coupled to the standard prelude, we're
643 trying a non-standard extension that instead gives you whatever "Prelude.fromInteger"
644 happens to be in scope.  Then you can
645         import Prelude ()
646         import MyPrelude as Prelude
647 to get the desired effect.
648
649 At the moment this just happens for
650   * fromInteger, fromRational on literals (in expressions and patterns)
651   * negate (in expressions)
652   * minus  (arising from n+k patterns)
653   * "do" notation
654
655 We store the relevant Name in the HsSyn tree, in 
656   * HsIntegral/HsFractional     
657   * NegApp
658   * NPlusKPatIn
659   * HsDo
660 respectively.  Initially, we just store the "standard" name (PrelNames.fromIntegralName,
661 fromRationalName etc), but the renamer changes this to the appropriate user
662 name if Opt_NoImplicitPrelude is on.  That is what lookupSyntaxName does.
663
664 We treat the orignal (standard) names as free-vars too, because the type checker
665 checks the type of the user thing against the type of the standard thing.
666
667 \begin{code}
668 lookupSyntaxName :: Name                        -- The standard name
669                  -> RnM (Name, FreeVars)        -- Possibly a non-standard name
670 lookupSyntaxName std_name
671   = doptM Opt_NoImplicitPrelude         `thenM` \ no_prelude -> 
672     if not no_prelude then normal_case
673     else
674     getModeRn                           `thenM` \ mode ->
675     if isInterfaceMode mode then normal_case
676         -- Happens for 'derived' code where we don't want to rebind
677     else
678         -- Get the similarly named thing from the local environment
679     lookupOccRn (mkRdrUnqual (nameOccName std_name)) `thenM` \ usr_name ->
680     returnM (usr_name, mkFVs [usr_name, std_name])
681   where
682     normal_case = returnM (std_name, unitFV std_name)
683
684 lookupSyntaxNames :: [Name]                             -- Standard names
685                   -> RnM (ReboundNames Name, FreeVars)  -- See comments with HsExpr.ReboundNames
686 lookupSyntaxNames std_names
687   = doptM Opt_NoImplicitPrelude         `thenM` \ no_prelude -> 
688     if not no_prelude then normal_case 
689     else
690     getModeRn                           `thenM` \ mode ->
691     if isInterfaceMode mode then normal_case
692     else
693         -- Get the similarly named thing from the local environment
694     mappM (lookupOccRn . mkRdrUnqual . nameOccName) std_names   `thenM` \ usr_names ->
695
696     returnM (std_names `zip` map HsVar usr_names, mkFVs std_names `plusFV` mkFVs usr_names)
697   where
698     normal_case = returnM (std_names `zip` map HsVar std_names, mkFVs std_names)
699 \end{code}
700
701
702 %*********************************************************
703 %*                                                      *
704 \subsection{Binding}
705 %*                                                      *
706 %*********************************************************
707
708 \begin{code}
709 newLocalsRn :: [(RdrName,SrcLoc)]
710             -> RnM [Name]
711 newLocalsRn rdr_names_w_loc
712  =  newUniqueSupply             `thenM` \ us ->
713     let
714         uniqs      = uniqsFromSupply us
715         names      = [ mkInternalName uniq (rdrNameOcc rdr_name) loc
716                      | ((rdr_name,loc), uniq) <- rdr_names_w_loc `zip` uniqs
717                      ]
718     in
719     returnM names
720
721
722 bindLocatedLocalsRn :: SDoc     -- Documentation string for error message
723                     -> [(RdrName,SrcLoc)]
724                     -> ([Name] -> RnM a)
725                     -> RnM a
726 bindLocatedLocalsRn doc_str rdr_names_w_loc enclosed_scope
727   = getModeRn                   `thenM` \ mode ->
728     getLocalRdrEnv              `thenM` \ local_env ->
729     getGlobalRdrEnv             `thenM` \ global_env ->
730
731         -- Check for duplicate names
732     checkDupOrQualNames doc_str rdr_names_w_loc `thenM_`
733
734         -- Warn about shadowing, but only in source modules
735     let
736       check_shadow (rdr_name,loc)
737         |  rdr_name `elemRdrEnv` local_env 
738         || rdr_name `elemRdrEnv` global_env 
739         = addSrcLoc loc $ addWarn (shadowedNameWarn rdr_name)
740         | otherwise 
741         = returnM ()
742     in
743
744     (case mode of
745         SourceMode -> ifOptM Opt_WarnNameShadowing      $
746                       mappM_ check_shadow rdr_names_w_loc
747         other      -> returnM ()
748     )                                   `thenM_`
749
750     newLocalsRn rdr_names_w_loc         `thenM` \ names ->
751     let
752         new_local_env = addListToRdrEnv local_env (map fst rdr_names_w_loc `zip` names)
753     in
754     setLocalRdrEnv new_local_env (enclosed_scope names)
755
756 bindCoreLocalRn :: RdrName -> (Name -> RnM a) -> RnM a
757   -- A specialised variant when renaming stuff from interface
758   -- files (of which there is a lot)
759   --    * one at a time
760   --    * no checks for shadowing
761   --    * always imported
762   --    * deal with free vars
763 bindCoreLocalRn rdr_name enclosed_scope
764   = getSrcLocM          `thenM` \ loc ->
765     getLocalRdrEnv              `thenM` \ name_env ->
766     newUnique                   `thenM` \ uniq ->
767     let
768         name         = mkInternalName uniq (rdrNameOcc rdr_name) loc
769         new_name_env = extendRdrEnv name_env rdr_name name
770     in
771     setLocalRdrEnv new_name_env (enclosed_scope name)
772
773 bindCoreLocalsRn []     thing_inside = thing_inside []
774 bindCoreLocalsRn (b:bs) thing_inside = bindCoreLocalRn b        $ \ name' ->
775                                        bindCoreLocalsRn bs      $ \ names' ->
776                                        thing_inside (name':names')
777
778 bindLocalNames names enclosed_scope
779   = getLocalRdrEnv              `thenM` \ name_env ->
780     setLocalRdrEnv (extendLocalRdrEnv name_env names)
781                     enclosed_scope
782
783 bindLocalNamesFV names enclosed_scope
784   = bindLocalNames names $
785     enclosed_scope `thenM` \ (thing, fvs) ->
786     returnM (thing, delListFromNameSet fvs names)
787
788
789 -------------------------------------
790 bindLocalRn doc rdr_name enclosed_scope
791   = getSrcLocM                          `thenM` \ loc ->
792     bindLocatedLocalsRn doc [(rdr_name,loc)]    $ \ (n:ns) ->
793     ASSERT( null ns )
794     enclosed_scope n
795
796 bindLocalsRn doc rdr_names enclosed_scope
797   = getSrcLocM          `thenM` \ loc ->
798     bindLocatedLocalsRn doc
799                         (rdr_names `zip` repeat loc)
800                         enclosed_scope
801
802         -- binLocalsFVRn is the same as bindLocalsRn
803         -- except that it deals with free vars
804 bindLocalsFV doc rdr_names enclosed_scope
805   = bindLocalsRn doc rdr_names          $ \ names ->
806     enclosed_scope names                `thenM` \ (thing, fvs) ->
807     returnM (thing, delListFromNameSet fvs names)
808
809 -------------------------------------
810 extendTyVarEnvFVRn :: [Name] -> RnM (a, FreeVars) -> RnM (a, FreeVars)
811         -- This tiresome function is used only in rnSourceDecl on InstDecl
812 extendTyVarEnvFVRn tyvars enclosed_scope
813   = bindLocalNames tyvars enclosed_scope        `thenM` \ (thing, fvs) -> 
814     returnM (thing, delListFromNameSet fvs tyvars)
815
816 bindTyVarsRn :: SDoc -> [HsTyVarBndr RdrName]
817               -> ([HsTyVarBndr Name] -> RnM a)
818               -> RnM a
819 bindTyVarsRn doc_str tyvar_names enclosed_scope
820   = getSrcLocM                                  `thenM` \ loc ->
821     let
822         located_tyvars = [(hsTyVarName tv, loc) | tv <- tyvar_names] 
823     in
824     bindLocatedLocalsRn doc_str located_tyvars  $ \ names ->
825     enclosed_scope (zipWith replaceTyVarName tyvar_names names)
826
827 bindPatSigTyVars :: [RdrNameHsType] -> ([Name] -> RnM a) -> RnM a
828   -- Find the type variables in the pattern type 
829   -- signatures that must be brought into scope
830
831 bindPatSigTyVars tys thing_inside
832   = getLocalRdrEnv              `thenM` \ name_env ->
833     getSrcLocM                  `thenM` \ loc ->
834     let
835         forall_tyvars  = nub [ tv | ty <- tys,
836                                     tv <- extractHsTyRdrTyVars ty, 
837                                     not (tv `elemFM` name_env)
838                          ]
839                 -- The 'nub' is important.  For example:
840                 --      f (x :: t) (y :: t) = ....
841                 -- We don't want to complain about binding t twice!
842
843         located_tyvars = [(tv, loc) | tv <- forall_tyvars] 
844         doc_sig        = text "In a pattern type-signature"
845     in
846     bindLocatedLocalsRn doc_sig located_tyvars thing_inside
847
848 bindPatSigTyVarsFV :: [RdrNameHsType]
849                    -> RnM (a, FreeVars)
850                    -> RnM (a, FreeVars)
851 bindPatSigTyVarsFV tys thing_inside
852   = bindPatSigTyVars tys        $ \ tvs ->
853     thing_inside                `thenM` \ (result,fvs) ->
854     returnM (result, fvs `delListFromNameSet` tvs)
855
856 -------------------------------------
857 checkDupOrQualNames, checkDupNames :: SDoc
858                                    -> [(RdrName, SrcLoc)]
859                                    -> TcRn m ()
860         -- Works in any variant of the renamer monad
861
862 checkDupOrQualNames doc_str rdr_names_w_loc
863   =     -- Qualified names in patterns are now rejected by the parser
864         -- but I'm not 100% certain that it finds all cases, so I've left
865         -- this check in for now.  Should go eventually.
866         --      Hmm.  Sooner rather than later.. data type decls
867 --     mappM_ (qualNameErr doc_str) quals       `thenM_`
868     checkDupNames doc_str rdr_names_w_loc
869   where
870     quals = filter (isQual . fst) rdr_names_w_loc
871     
872 checkDupNames doc_str rdr_names_w_loc
873   =     -- Check for duplicated names in a binding group
874     mappM_ (dupNamesErr doc_str) dups
875   where
876     (_, dups) = removeDups (\(n1,l1) (n2,l2) -> n1 `compare` n2) rdr_names_w_loc
877 \end{code}
878
879
880 %************************************************************************
881 %*                                                                      *
882 \subsection{GlobalRdrEnv}
883 %*                                                                      *
884 %************************************************************************
885
886 \begin{code}
887 mkGlobalRdrEnv :: ModuleName            -- Imported module (after doing the "as M" name change)
888                -> Bool                  -- True <=> want unqualified import
889                -> (Name -> Provenance)
890                -> Avails                -- Whats imported
891                -> Deprecations
892                -> GlobalRdrEnv
893
894 mkGlobalRdrEnv this_mod unqual_imp mk_provenance avails deprecs
895   = gbl_env2
896   where
897         -- Make the name environment.  We're talking about a 
898         -- single module here, so there must be no name clashes.
899         -- In practice there only ever will be if it's the module
900         -- being compiled.
901
902         -- Add qualified names for the things that are available
903         -- (Qualified names are always imported)
904     gbl_env1 = foldl add_avail emptyRdrEnv avails
905
906         -- Add unqualified names
907     gbl_env2 | unqual_imp = foldl add_unqual gbl_env1 (rdrEnvToList gbl_env1)
908              | otherwise  = gbl_env1
909
910     add_unqual env (qual_name, elts)
911         = foldl add_one env elts
912         where
913           add_one env elt = addOneToGlobalRdrEnv env unqual_name elt
914           unqual_name     = unqualifyRdrName qual_name
915         -- The qualified import should only have added one 
916         -- binding for each qualified name!  But if there's an error in
917         -- the module (multiple bindings for the same name) we may get
918         -- duplicates.  So the simple thing is to do the fold.
919
920     add_avail :: GlobalRdrEnv -> AvailInfo -> GlobalRdrEnv
921     add_avail env avail = foldl (add_name (availName avail)) env (availNames avail)
922
923     add_name parent env name    -- Add qualified name only
924         = addOneToGlobalRdrEnv env (mkRdrQual this_mod occ) elt
925         where
926           occ  = nameOccName name
927           elt  = GRE {gre_name   = name,
928                       gre_parent = if name == parent 
929                                    then Nothing 
930                                    else Just parent, 
931                       gre_prov   = mk_provenance name, 
932                       gre_deprec = lookupDeprec deprecs name}
933 \end{code}
934
935 \begin{code}
936 plusGlobalRdrEnv :: GlobalRdrEnv -> GlobalRdrEnv -> GlobalRdrEnv
937 plusGlobalRdrEnv env1 env2 = plusFM_C combine_globals env1 env2
938
939 addOneToGlobalRdrEnv :: GlobalRdrEnv -> RdrName -> GlobalRdrElt -> GlobalRdrEnv
940 addOneToGlobalRdrEnv env rdr_name name = addToFM_C combine_globals env rdr_name [name]
941
942 delOneFromGlobalRdrEnv :: GlobalRdrEnv -> RdrName -> GlobalRdrEnv 
943 delOneFromGlobalRdrEnv env rdr_name = delFromFM env rdr_name
944
945 combine_globals :: [GlobalRdrElt]       -- Old
946                 -> [GlobalRdrElt]       -- New
947                 -> [GlobalRdrElt]
948 combine_globals ns_old ns_new   -- ns_new is often short
949   = foldr add ns_old ns_new
950   where
951     add n ns | any (is_duplicate n) ns_old = map (choose n) ns  -- Eliminate duplicates
952              | otherwise                   = n:ns
953
954     choose n m | n `beats` m = n
955                | otherwise   = m
956
957     g1 `beats` g2 = gre_name g1 == gre_name g2 && 
958                     gre_prov g1 `hasBetterProv` gre_prov g2
959
960     is_duplicate :: GlobalRdrElt -> GlobalRdrElt -> Bool
961     is_duplicate g1 g2 | isLocalGRE g1 && isLocalGRE g2 = False
962     is_duplicate g1 g2 = gre_name g1 == gre_name g2
963 \end{code}
964
965 We treat two bindings of a locally-defined name as a duplicate,
966 because they might be two separate, local defns and we want to report
967 and error for that, {\em not} eliminate a duplicate.
968
969 On the other hand, if you import the same name from two different
970 import statements, we {\em do} want to eliminate the duplicate, not report
971 an error.
972
973 If a module imports itself then there might be a local defn and an imported
974 defn of the same name; in this case the names will compare as equal, but
975 will still have different provenances.
976
977
978 %************************************************************************
979 %*                                                                      *
980 \subsection{Free variable manipulation}
981 %*                                                                      *
982 %************************************************************************
983
984 \begin{code}
985 -- A useful utility
986 mapFvRn f xs = mappM f xs       `thenM` \ stuff ->
987                let
988                   (ys, fvs_s) = unzip stuff
989                in
990                returnM (ys, plusFVs fvs_s)
991 \end{code}
992
993
994 %************************************************************************
995 %*                                                                      *
996 \subsection{Envt utility functions}
997 %*                                                                      *
998 %************************************************************************
999
1000 \begin{code}
1001 warnUnusedModules :: [ModuleName] -> TcRn m ()
1002 warnUnusedModules mods
1003   = ifOptM Opt_WarnUnusedImports (mappM_ (addWarn . unused_mod) mods)
1004   where
1005     unused_mod m = vcat [ptext SLIT("Module") <+> quotes (ppr m) <+> 
1006                            text "is imported, but nothing from it is used",
1007                          parens (ptext SLIT("except perhaps instances visible in") <+>
1008                                    quotes (ppr m))]
1009
1010 warnUnusedImports, warnUnusedTopBinds :: [GlobalRdrElt] -> TcRn m ()
1011 warnUnusedImports gres  = ifOptM Opt_WarnUnusedImports (warnUnusedGREs gres)
1012 warnUnusedTopBinds gres = ifOptM Opt_WarnUnusedBinds   (warnUnusedGREs gres)
1013
1014 warnUnusedLocalBinds, warnUnusedMatches :: [Name] -> TcRn m ()
1015 warnUnusedLocalBinds names = ifOptM Opt_WarnUnusedBinds   (warnUnusedLocals names)
1016 warnUnusedMatches    names = ifOptM Opt_WarnUnusedMatches (warnUnusedLocals names)
1017
1018 -------------------------
1019 --      Helpers
1020 warnUnusedGREs   gres  = warnUnusedBinds [(n,p) | GRE {gre_name = n, gre_prov = p} <- gres]
1021 warnUnusedLocals names = warnUnusedBinds [(n,LocalDef) | n<-names]
1022
1023 warnUnusedBinds :: [(Name,Provenance)] -> TcRn m ()
1024 warnUnusedBinds names
1025   = mappM_ warnUnusedGroup groups
1026   where
1027         -- Group by provenance
1028    groups = equivClasses cmp (filter reportable names)
1029    (_,prov1) `cmp` (_,prov2) = prov1 `compare` prov2
1030  
1031    reportable (name,_) = reportIfUnused (nameOccName name)
1032
1033
1034 -------------------------
1035
1036 warnUnusedGroup :: [(Name,Provenance)] -> TcRn m ()
1037 warnUnusedGroup names
1038   = addSrcLoc def_loc   $
1039     addWarn             $
1040     sep [msg <> colon, nest 4 (fsep (punctuate comma (map (ppr.fst) names)))]
1041   where
1042     (name1, prov1) = head names
1043     loc1           = nameSrcLoc name1
1044     (def_loc, msg) = case prov1 of
1045                         LocalDef                           -> (loc1, unused_msg)
1046                         NonLocalDef (UserImport mod loc _) -> (loc,  imp_from mod)
1047
1048     unused_msg   = text "Defined but not used"
1049     imp_from mod = text "Imported from" <+> quotes (ppr mod) <+> text "but not used"
1050 \end{code}
1051
1052 \begin{code}
1053 addNameClashErrRn rdr_name (np1:nps)
1054   = addErr (vcat [ptext SLIT("Ambiguous occurrence") <+> quotes (ppr rdr_name),
1055                   ptext SLIT("It could refer to") <+> vcat (msg1 : msgs)])
1056   where
1057     msg1 = ptext  SLIT("either") <+> mk_ref np1
1058     msgs = [ptext SLIT("    or") <+> mk_ref np | np <- nps]
1059     mk_ref gre = quotes (ppr (gre_name gre)) <> comma <+> pprNameProvenance gre
1060
1061 shadowedNameWarn shadow
1062   = hsep [ptext SLIT("This binding for"), 
1063                quotes (ppr shadow),
1064                ptext SLIT("shadows an existing binding")]
1065
1066 unknownNameErr name
1067   = sep [text flavour, ptext SLIT("not in scope:"), quotes (ppr name)]
1068   where
1069     flavour = occNameFlavour (rdrNameOcc name)
1070
1071 badOrigBinding name
1072   = ptext SLIT("Illegal binding of built-in syntax:") <+> ppr (rdrNameOcc name)
1073         -- The rdrNameOcc is because we don't want to print Prelude.(,)
1074
1075 qualNameErr descriptor (name,loc)
1076   = addSrcLoc loc $
1077     addErr (vcat [ ptext SLIT("Invalid use of qualified name") <+> quotes (ppr name),
1078                      descriptor])
1079
1080 dupNamesErr descriptor ((name,loc) : dup_things)
1081   = addSrcLoc loc $
1082     addErr ((ptext SLIT("Conflicting definitions for") <+> quotes (ppr name))
1083               $$ 
1084               descriptor)
1085
1086 noIfaceErr dflags mod_name boot_file files
1087   = ptext SLIT("Could not find interface file for") <+> quotes (ppr mod_name)
1088     $$ extra
1089   where 
1090    extra
1091     | verbosity dflags < 3 = 
1092         text "(use -v to see a list of the files searched for)"
1093     | otherwise =
1094         hang (ptext SLIT("locations searched:")) 4 (vcat (map text files))
1095
1096 warnDeprec :: GlobalRdrElt -> TcRn m ()
1097 warnDeprec (GRE {gre_name = name, gre_deprec = Just txt})
1098   = ifOptM Opt_WarnDeprecations $
1099     addWarn (sep [ text (occNameFlavour (nameOccName name)) <+> 
1100                      quotes (ppr name) <+> text "is deprecated:", 
1101                      nest 4 (ppr txt) ])
1102 \end{code}
1103