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