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