[project @ 2003-01-23 14:54:35 by simonpj]
[ghc-hetmet.git] / ghc / compiler / rename / RnEnv.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section[RnEnv]{Environment manipulation for the renamer monad}
5
6 \begin{code}
7 module RnEnv where              -- Export everything
8
9 #include "HsVersions.h"
10
11 import {-# SOURCE #-} RnHiFiles( loadInterface )
12
13 import FlattenInfo      ( namesNeededForFlattening )
14 import HsSyn
15 import RdrHsSyn         ( RdrNameHsType, RdrNameFixitySig, extractHsTyRdrTyVars )
16 import RdrName          ( RdrName, rdrNameModule, rdrNameOcc, isQual, isUnqual, isOrig,
17                           mkRdrUnqual, mkRdrQual, setRdrNameSpace, rdrNameOcc,
18                           lookupRdrEnv, rdrEnvToList, elemRdrEnv, 
19                           extendRdrEnv, addListToRdrEnv, emptyRdrEnv,
20                           isExact_maybe, unqualifyRdrName
21                         )
22 import HsTypes          ( hsTyVarName, replaceTyVarName )
23 import HscTypes         ( Provenance(..), pprNameProvenance, hasBetterProv,
24                           ImportReason(..), GlobalRdrEnv, GlobalRdrElt(..), 
25                           GenAvailInfo(..), AvailInfo, Avails, 
26                           ModIface(..), NameCache(..), OrigNameCache,
27                           Deprecations(..), lookupDeprec, isLocalGRE,
28                           extendLocalRdrEnv, availName, availNames,
29                           lookupFixity
30                         )
31 import TcRnMonad
32 import Name             ( Name, getName, nameIsLocalOrFrom, 
33                           isWiredInName, mkInternalName, mkExternalName, mkIPName, 
34                           nameSrcLoc, nameOccName, setNameSrcLoc, nameModule    )
35 import NameSet
36 import OccName          ( OccName, tcName, isDataOcc, occNameUserString, occNameFlavour,
37                           reportIfUnused )
38 import Module           ( Module, ModuleName, moduleName, mkHomeModule,
39                           lookupModuleEnv, lookupModuleEnvByName, extendModuleEnv_C )
40 import PrelNames        ( mkUnboundName, intTyConName, 
41                           boolTyConName, funTyConName,
42                           unpackCStringName, unpackCStringFoldrName, unpackCStringUtf8Name,
43                           eqStringName, printName, 
44                           bindIOName, returnIOName, failIOName, thenIOName
45                         )
46 #ifdef GHCI     
47 import DsMeta           ( templateHaskellNames, qTyConName )
48 #endif
49 import TysWiredIn       ( unitTyCon )   -- A little odd
50 import Finder           ( findModule )
51 import FiniteMap
52 import UniqSupply
53 import SrcLoc           ( SrcLoc, importedSrcLoc )
54 import Outputable
55 import ListSetOps       ( removeDups, equivClasses )
56 import BasicTypes       ( mapIPName, FixitySig(..) )
57 import List             ( nub )
58 import CmdLineOpts
59 import FastString       ( FastString )
60 \end{code}
61
62 %*********************************************************
63 %*                                                      *
64 \subsection{Making new names}
65 %*                                                      *
66 %*********************************************************
67
68 \begin{code}
69 newTopBinder :: Module -> RdrName -> SrcLoc -> TcRn m Name
70 newTopBinder mod rdr_name loc
71   | Just name <- isExact_maybe rdr_name
72   = returnM name
73
74   | otherwise
75   = ASSERT( not (isOrig rdr_name) || rdrNameModule rdr_name == moduleName mod )
76         -- When reading External Core we get Orig names as binders, 
77         -- but they should agree with the module gotten from the monad
78     newGlobalName mod (rdrNameOcc rdr_name) loc
79
80 newGlobalName :: Module -> OccName -> SrcLoc -> TcRn m Name
81 newGlobalName mod occ loc
82   =     -- First check the cache
83     getNameCache                `thenM` \ name_supply -> 
84     case lookupOrigNameCache (nsNames name_supply) mod occ of
85
86         -- A hit in the cache!  We are at the binding site of the name.
87         -- This is the moment when we know the defining SrcLoc
88         -- of the Name, so we set the SrcLoc of the name we return.
89         --
90         -- Main reason: then (bogus) multiple bindings of the same Name
91         --              get different SrcLocs can can be reported as such.
92         --
93         -- Possible other reason: it might be in the cache because we
94         --      encountered an occurrence before the binding site for an
95         --      implicitly-imported Name.  Perhaps the current SrcLoc is
96         --      better... but not really: it'll still just say 'imported'
97         --
98         -- IMPORTANT: Don't mess with wired-in names.  
99         --            Their wired-in-ness is in the SrcLoc
100
101         Just name | isWiredInName name -> returnM name
102                   | otherwise          -> returnM (setNameSrcLoc name loc)
103                      
104         -- Miss in the cache!
105         -- Build a completely new Name, and put it in the cache
106         Nothing -> addNewName name_supply mod occ loc
107
108 -- Look up a "system name" in the name cache.
109 -- This is done by the type checker... 
110 lookupSysName :: Name                   -- Base name
111               -> (OccName -> OccName)   -- Occurrence name modifier
112               -> TcRn m Name            -- System name
113 lookupSysName base_name mk_sys_occ
114   = newGlobalName (nameModule base_name)
115                   (mk_sys_occ (nameOccName base_name))
116                   (nameSrcLoc base_name)    
117
118
119 newGlobalNameFromRdrName rdr_name               -- Qualified original name
120  = newGlobalName2 (rdrNameModule rdr_name) (rdrNameOcc rdr_name)
121
122 newGlobalName2 :: ModuleName -> OccName -> TcRn m Name
123   -- This one starts with a ModuleName, not a Module, because 
124   -- we may be simply looking at an occurrence M.x in an interface file.
125   --
126   -- Used for *occurrences*.  Even if we get a miss in the
127   -- original-name cache, we make a new External Name.
128   -- We get its Module either from the OrigNameCache, or (if this
129   -- is the first Name from that module) from the Finder
130   --
131   -- In the case of a miss, we have to make up the SrcLoc, but that's
132   -- OK: it must be an implicitly-imported Name, and that never occurs
133   -- in an error message.
134
135 newGlobalName2 mod_name occ
136   = getNameCache                `thenM` \ name_supply ->
137     let
138         new_name mod = addNewName name_supply mod occ importedSrcLoc
139     in
140     case lookupModuleEnvByName (nsNames name_supply) mod_name of
141       Just (mod, occ_env) ->    
142         -- There are some names from this module already
143         -- Next, look up in the OccNameEnv
144         case lookupFM occ_env occ of
145              Just name -> returnM name
146              Nothing   -> new_name mod
147
148       Nothing   ->      -- No names from this module yet
149         ioToTcRn (findModule mod_name)          `thenM` \ mb_loc ->
150         case mb_loc of
151             Right (mod, _) -> new_name mod
152             Left files     -> 
153                 getDOpts `thenM` \ dflags ->
154                 addErr (noIfaceErr dflags mod_name False files) `thenM_`
155                         -- Things have really gone wrong at this point,
156                         -- so having the wrong package info in the 
157                         -- Module is the least of our worries.
158                 new_name (mkHomeModule mod_name)
159
160
161 newIPName rdr_name_ip
162   = getNameCache                `thenM` \ name_supply ->
163     let
164         ipcache = nsIPs name_supply
165     in
166     case lookupFM ipcache key of
167         Just name_ip -> returnM name_ip
168         Nothing      -> setNameCache new_ns     `thenM_`
169                         returnM name_ip
170                   where
171                      (us', us1)  = splitUniqSupply (nsUniqs name_supply)
172                      uniq        = uniqFromSupply us1
173                      name_ip     = mapIPName mk_name rdr_name_ip
174                      mk_name rdr_name = mkIPName uniq (rdrNameOcc rdr_name)
175                      new_ipcache = addToFM ipcache key name_ip
176                      new_ns      = name_supply {nsUniqs = us', nsIPs = new_ipcache}
177     where 
178         key = rdr_name_ip       -- Ensures that ?x and %x get distinct Names
179
180 -- A local helper function
181 addNewName name_supply mod occ loc
182   = setNameCache new_name_supply        `thenM_`
183     returnM name
184   where
185     (new_name_supply, name) = newExternalName name_supply mod occ loc
186
187
188 newExternalName :: NameCache -> Module -> OccName -> SrcLoc 
189                   -> (NameCache,Name)
190 -- Allocate a new unique, manufacture a new External Name,
191 -- put it in the cache, and return the two
192 newExternalName name_supply mod occ loc
193   = (new_name_supply, name)
194   where
195      (us', us1)      = splitUniqSupply (nsUniqs name_supply)
196      uniq            = uniqFromSupply us1
197      name            = mkExternalName uniq mod occ loc
198      new_cache       = extend_name_cache (nsNames name_supply) mod occ name
199      new_name_supply = name_supply {nsUniqs = us', nsNames = new_cache}
200
201 lookupOrigNameCache :: OrigNameCache -> Module -> OccName -> Maybe Name
202 lookupOrigNameCache nc mod occ
203   = case lookupModuleEnv nc mod of
204         Nothing           -> Nothing
205         Just (_, occ_env) -> lookupFM occ_env occ
206
207 extendOrigNameCache :: OrigNameCache -> Name -> OrigNameCache
208 extendOrigNameCache nc name 
209   = extend_name_cache nc (nameModule name) (nameOccName name) name
210
211 extend_name_cache :: OrigNameCache -> Module -> OccName -> Name -> OrigNameCache
212 extend_name_cache nc mod occ name
213   = extendModuleEnv_C combine nc mod (mod, unitFM occ name)
214   where
215     combine (mod, occ_env) _ = (mod, addToFM occ_env occ name)
216 \end{code}
217
218 %*********************************************************
219 %*                                                      *
220 \subsection{Looking up names}
221 %*                                                      *
222 %*********************************************************
223
224 Looking up a name in the RnEnv.
225
226 \begin{code}
227 lookupBndrRn rdr_name
228   = getLocalRdrEnv              `thenM` \ local_env ->
229     case lookupRdrEnv local_env rdr_name of 
230           Just name -> returnM name
231           Nothing   -> lookupTopBndrRn rdr_name
232
233 lookupTopBndrRn rdr_name
234 -- Look up a top-level local binder.   We may be looking up an unqualified 'f',
235 -- and there may be several imported 'f's too, which must not confuse us.
236 -- So we have to filter out the non-local ones.
237 -- A separate function (importsFromLocalDecls) reports duplicate top level
238 -- decls, so here it's safe just to choose an arbitrary one.
239
240 -- There should never be a qualified name in a binding position in Haskell,
241 -- but there can be if we have read in an external-Core file.
242 -- The Haskell parser checks for the illegal qualified name in Haskell 
243 -- source files, so we don't need to do so here.
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         --      Hmm.  Sooner rather than later.. data type decls
833 --     mappM_ (qualNameErr doc_str) quals       `thenM_`
834     checkDupNames doc_str rdr_names_w_loc
835   where
836     quals = filter (isQual . fst) rdr_names_w_loc
837     
838 checkDupNames doc_str rdr_names_w_loc
839   =     -- Check for duplicated names in a binding group
840     mappM_ (dupNamesErr doc_str) dups
841   where
842     (_, dups) = removeDups (\(n1,l1) (n2,l2) -> n1 `compare` n2) rdr_names_w_loc
843 \end{code}
844
845
846 %************************************************************************
847 %*                                                                      *
848 \subsection{GlobalRdrEnv}
849 %*                                                                      *
850 %************************************************************************
851
852 \begin{code}
853 mkGlobalRdrEnv :: ModuleName            -- Imported module (after doing the "as M" name change)
854                -> Bool                  -- True <=> want unqualified import
855                -> (Name -> Provenance)
856                -> Avails                -- Whats imported
857                -> Deprecations
858                -> GlobalRdrEnv
859
860 mkGlobalRdrEnv this_mod unqual_imp mk_provenance avails deprecs
861   = gbl_env2
862   where
863         -- Make the name environment.  We're talking about a 
864         -- single module here, so there must be no name clashes.
865         -- In practice there only ever will be if it's the module
866         -- being compiled.
867
868         -- Add qualified names for the things that are available
869         -- (Qualified names are always imported)
870     gbl_env1 = foldl add_avail emptyRdrEnv avails
871
872         -- Add unqualified names
873     gbl_env2 | unqual_imp = foldl add_unqual gbl_env1 (rdrEnvToList gbl_env1)
874              | otherwise  = gbl_env1
875
876     add_unqual env (qual_name, elts)
877         = foldl add_one env elts
878         where
879           add_one env elt = addOneToGlobalRdrEnv env unqual_name elt
880           unqual_name     = unqualifyRdrName qual_name
881         -- The qualified import should only have added one 
882         -- binding for each qualified name!  But if there's an error in
883         -- the module (multiple bindings for the same name) we may get
884         -- duplicates.  So the simple thing is to do the fold.
885
886     add_avail :: GlobalRdrEnv -> AvailInfo -> GlobalRdrEnv
887     add_avail env avail = foldl (add_name (availName avail)) env (availNames avail)
888
889     add_name parent env name    -- Add qualified name only
890         = addOneToGlobalRdrEnv env (mkRdrQual this_mod occ) elt
891         where
892           occ  = nameOccName name
893           elt  = GRE {gre_name   = name,
894                       gre_parent = if name == parent 
895                                    then Nothing 
896                                    else Just parent, 
897                       gre_prov   = mk_provenance name, 
898                       gre_deprec = lookupDeprec deprecs name}
899                       
900 \end{code}
901
902 \begin{code}
903 plusGlobalRdrEnv :: GlobalRdrEnv -> GlobalRdrEnv -> GlobalRdrEnv
904 plusGlobalRdrEnv env1 env2 = plusFM_C combine_globals env1 env2
905
906 addOneToGlobalRdrEnv :: GlobalRdrEnv -> RdrName -> GlobalRdrElt -> GlobalRdrEnv
907 addOneToGlobalRdrEnv env rdr_name name = addToFM_C combine_globals env rdr_name [name]
908
909 delOneFromGlobalRdrEnv :: GlobalRdrEnv -> RdrName -> GlobalRdrEnv 
910 delOneFromGlobalRdrEnv env rdr_name = delFromFM env rdr_name
911
912 combine_globals :: [GlobalRdrElt]       -- Old
913                 -> [GlobalRdrElt]       -- New
914                 -> [GlobalRdrElt]
915 combine_globals ns_old ns_new   -- ns_new is often short
916   = foldr add ns_old ns_new
917   where
918     add n ns | any (is_duplicate n) ns_old = map (choose n) ns  -- Eliminate duplicates
919              | otherwise                   = n:ns
920
921     choose n m | n `beats` m = n
922                | otherwise   = m
923
924     g1 `beats` g2 = gre_name g1 == gre_name g2 && 
925                     gre_prov g1 `hasBetterProv` gre_prov g2
926
927     is_duplicate :: GlobalRdrElt -> GlobalRdrElt -> Bool
928     is_duplicate g1 g2 | isLocalGRE g1 && isLocalGRE g2 = False
929     is_duplicate g1 g2 = gre_name g1 == gre_name g2
930 \end{code}
931
932 We treat two bindings of a locally-defined name as a duplicate,
933 because they might be two separate, local defns and we want to report
934 and error for that, {\em not} eliminate a duplicate.
935
936 On the other hand, if you import the same name from two different
937 import statements, we {\em do} want to eliminate the duplicate, not report
938 an error.
939
940 If a module imports itself then there might be a local defn and an imported
941 defn of the same name; in this case the names will compare as equal, but
942 will still have different provenances.
943
944
945 %************************************************************************
946 %*                                                                      *
947 \subsection{Free variable manipulation}
948 %*                                                                      *
949 %************************************************************************
950
951 \begin{code}
952 -- A useful utility
953 mapFvRn f xs = mappM f xs       `thenM` \ stuff ->
954                let
955                   (ys, fvs_s) = unzip stuff
956                in
957                returnM (ys, plusFVs fvs_s)
958 \end{code}
959
960
961 %************************************************************************
962 %*                                                                      *
963 \subsection{Envt utility functions}
964 %*                                                                      *
965 %************************************************************************
966
967 \begin{code}
968 warnUnusedModules :: [ModuleName] -> TcRn m ()
969 warnUnusedModules mods
970   = ifOptM Opt_WarnUnusedImports (mappM_ (addWarn . unused_mod) mods)
971   where
972     unused_mod m = vcat [ptext SLIT("Module") <+> quotes (ppr m) <+> 
973                            text "is imported, but nothing from it is used",
974                          parens (ptext SLIT("except perhaps instances visible in") <+>
975                                    quotes (ppr m))]
976
977 warnUnusedImports, warnUnusedTopBinds :: [GlobalRdrElt] -> TcRn m ()
978 warnUnusedImports gres  = ifOptM Opt_WarnUnusedImports (warnUnusedGREs gres)
979 warnUnusedTopBinds gres = ifOptM Opt_WarnUnusedBinds   (warnUnusedGREs gres)
980
981 warnUnusedLocalBinds, warnUnusedMatches :: [Name] -> TcRn m ()
982 warnUnusedLocalBinds names = ifOptM Opt_WarnUnusedBinds   (warnUnusedLocals names)
983 warnUnusedMatches    names = ifOptM Opt_WarnUnusedMatches (warnUnusedLocals names)
984
985 -------------------------
986 --      Helpers
987 warnUnusedGREs   gres  = warnUnusedBinds [(n,p) | GRE {gre_name = n, gre_prov = p} <- gres]
988 warnUnusedLocals names = warnUnusedBinds [(n,LocalDef) | n<-names]
989
990 warnUnusedBinds :: [(Name,Provenance)] -> TcRn m ()
991 warnUnusedBinds names
992   = mappM_ warnUnusedGroup groups
993   where
994         -- Group by provenance
995    groups = equivClasses cmp (filter reportable names)
996    (_,prov1) `cmp` (_,prov2) = prov1 `compare` prov2
997  
998    reportable (name,_) = reportIfUnused (nameOccName name)
999
1000
1001 -------------------------
1002
1003 warnUnusedGroup :: [(Name,Provenance)] -> TcRn m ()
1004 warnUnusedGroup names
1005   = addSrcLoc def_loc   $
1006     addWarn             $
1007     sep [msg <> colon, nest 4 (fsep (punctuate comma (map (ppr.fst) names)))]
1008   where
1009     (name1, prov1) = head names
1010     loc1           = nameSrcLoc name1
1011     (def_loc, msg) = case prov1 of
1012                         LocalDef                           -> (loc1, unused_msg)
1013                         NonLocalDef (UserImport mod loc _) -> (loc,  imp_from mod)
1014
1015     unused_msg   = text "Defined but not used"
1016     imp_from mod = text "Imported from" <+> quotes (ppr mod) <+> text "but not used"
1017 \end{code}
1018
1019 \begin{code}
1020 addNameClashErrRn rdr_name (np1:nps)
1021   = addErr (vcat [ptext SLIT("Ambiguous occurrence") <+> quotes (ppr rdr_name),
1022                   ptext SLIT("It could refer to") <+> vcat (msg1 : msgs)])
1023   where
1024     msg1 = ptext  SLIT("either") <+> mk_ref np1
1025     msgs = [ptext SLIT("    or") <+> mk_ref np | np <- nps]
1026     mk_ref gre = quotes (ppr (gre_name gre)) <> comma <+> pprNameProvenance gre
1027
1028 shadowedNameWarn shadow
1029   = hsep [ptext SLIT("This binding for"), 
1030                quotes (ppr shadow),
1031                ptext SLIT("shadows an existing binding")]
1032
1033 unknownNameErr name
1034   = sep [text flavour, ptext SLIT("not in scope:"), quotes (ppr name)]
1035   where
1036     flavour = occNameFlavour (rdrNameOcc name)
1037
1038 badOrigBinding name
1039   = ptext SLIT("Illegal binding of built-in syntax:") <+> ppr (rdrNameOcc name)
1040         -- The rdrNameOcc is because we don't want to print Prelude.(,)
1041
1042 qualNameErr descriptor (name,loc)
1043   = addSrcLoc loc $
1044     addErr (vcat [ ptext SLIT("Invalid use of qualified name") <+> quotes (ppr name),
1045                      descriptor])
1046
1047 dupNamesErr descriptor ((name,loc) : dup_things)
1048   = addSrcLoc loc $
1049     addErr ((ptext SLIT("Conflicting definitions for") <+> quotes (ppr name))
1050               $$ 
1051               descriptor)
1052
1053 noIfaceErr dflags mod_name boot_file files
1054   = ptext SLIT("Could not find interface file for") <+> quotes (ppr mod_name)
1055     $$ extra
1056   where 
1057    extra
1058     | verbosity dflags < 3 = 
1059         text "(use -v to see a list of the files searched for)"
1060     | otherwise =
1061         hang (ptext SLIT("locations searched:")) 4 (vcat (map text files))
1062
1063 warnDeprec :: GlobalRdrElt -> TcRn m ()
1064 warnDeprec (GRE {gre_name = name, gre_deprec = Just txt})
1065   = ifOptM Opt_WarnDeprecations $
1066     addWarn (sep [ text (occNameFlavour (nameOccName name)) <+> 
1067                      quotes (ppr name) <+> text "is deprecated:", 
1068                      nest 4 (ppr txt) ])
1069 \end{code}
1070