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