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