[project @ 2001-11-26 09:20:25 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
12
13 import HsSyn
14 import RdrHsSyn         ( RdrNameIE, RdrNameHsType, extractHsTyRdrTyVars )
15 import RdrName          ( RdrName, rdrNameModule, rdrNameOcc, isQual, isUnqual, isOrig,
16                           mkRdrUnqual, mkRdrQual, 
17                           lookupRdrEnv, foldRdrEnv, rdrEnvToList, elemRdrEnv,
18                           unqualifyRdrName
19                         )
20 import HsTypes          ( hsTyVarName, replaceTyVarName )
21 import HscTypes         ( Provenance(..), pprNameProvenance, hasBetterProv,
22                           ImportReason(..), GlobalRdrEnv, GlobalRdrElt(..), AvailEnv,
23                           AvailInfo, Avails, GenAvailInfo(..), NameSupply(..), 
24                           ModIface(..),
25                           Deprecations(..), lookupDeprec,
26                           extendLocalRdrEnv
27                         )
28 import Type             ( mapIPName )
29 import RnMonad
30 import Name             ( Name, 
31                           getSrcLoc, nameIsLocalOrFrom,
32                           mkLocalName, mkGlobalName,
33                           mkIPName, nameOccName, nameModule_maybe,
34                           setNameModuleAndLoc
35                         )
36 import NameEnv
37 import NameSet
38 import OccName          ( OccName, occNameUserString, occNameFlavour )
39 import Module           ( ModuleName, moduleName, mkVanillaModule, 
40                           mkSysModuleNameFS, moduleNameFS, WhereFrom(..) )
41 import PrelNames        ( mkUnboundName, 
42                           derivingOccurrences,
43                           mAIN_Name, pREL_MAIN_Name, 
44                           ioTyConName, intTyConName, 
45                           boolTyConName, funTyConName,
46                           unpackCStringName, unpackCStringFoldrName, unpackCStringUtf8Name,
47                           eqStringName, printName, 
48                           bindIOName, returnIOName, failIOName
49                         )
50 import TysWiredIn       ( unitTyCon )   -- A little odd
51 import FiniteMap
52 import UniqSupply
53 import SrcLoc           ( SrcLoc, noSrcLoc )
54 import Outputable
55 import ListSetOps       ( removeDups, equivClasses )
56 import Util             ( sortLt )
57 import List             ( nub )
58 import UniqFM           ( lookupWithDefaultUFM )
59 import CmdLineOpts
60 import FastString       ( FastString )
61 \end{code}
62
63 %*********************************************************
64 %*                                                      *
65 \subsection{Making new names}
66 %*                                                      *
67 %*********************************************************
68
69 \begin{code}
70 newTopBinder :: Module -> RdrName -> SrcLoc -> RnM d Name
71         -- newTopBinder puts into the cache the binder with the
72         -- module information set correctly.  When the decl is later renamed,
73         -- the binding site will thereby get the correct module.
74         -- There maybe occurrences that don't have the correct Module, but
75         -- by the typechecker will propagate the binding definition to all 
76         -- the occurrences, so that doesn't matter
77
78 newTopBinder mod rdr_name loc
79   =     -- First check the cache
80
81         -- There should never be a qualified name in a binding position (except in instance decls)
82         -- The parser doesn't check this because the same parser parses instance decls
83     (if isQual rdr_name then
84         qualNameErr (text "In its declaration") (rdr_name,loc)
85      else
86         returnRn ()
87     )                           `thenRn_`
88
89     getNameSupplyRn             `thenRn` \ name_supply -> 
90     let 
91         occ = rdrNameOcc rdr_name
92         key = (moduleName mod, occ)
93         cache = nsNames name_supply
94     in
95     case lookupFM cache key of
96
97         -- A hit in the cache!  We are at the binding site of the name, and
98         -- this is the moment when we know all about 
99         --      a) the Name's host Module (in particular, which
100         --         package it comes from)
101         --      b) its defining SrcLoc
102         -- So we update this info
103
104         Just name -> let 
105                         new_name  = setNameModuleAndLoc name mod loc
106                         new_cache = addToFM cache key new_name
107                      in
108                      setNameSupplyRn (name_supply {nsNames = new_cache})        `thenRn_`
109 --                   traceRn (text "newTopBinder: overwrite" <+> ppr new_name) `thenRn_`
110                      returnRn new_name
111                      
112         -- Miss in the cache!
113         -- Build a completely new Name, and put it in the cache
114         -- Even for locally-defined names we use implicitImportProvenance; 
115         -- updateProvenances will set it to rights
116         Nothing -> let
117                         (us', us1) = splitUniqSupply (nsUniqs name_supply)
118                         uniq       = uniqFromSupply us1
119                         new_name   = mkGlobalName uniq mod occ loc
120                         new_cache  = addToFM cache key new_name
121                    in
122                    setNameSupplyRn (name_supply {nsUniqs = us', nsNames = new_cache})   `thenRn_`
123 --                 traceRn (text "newTopBinder: new" <+> ppr new_name) `thenRn_`
124                    returnRn new_name
125
126
127 newGlobalName :: ModuleName -> OccName -> RnM d Name
128   -- Used for *occurrences*.  We make a place-holder Name, really just
129   -- to agree on its unique, which gets overwritten when we read in
130   -- the binding occurence later (newTopBinder)
131   -- The place-holder Name doesn't have the right SrcLoc, and its
132   -- Module won't have the right Package either.
133   --
134   -- (We have to pass a ModuleName, not a Module, because we may be
135   -- simply looking at an occurrence M.x in an interface file.)
136   --
137   -- This means that a renamed program may have incorrect info
138   -- on implicitly-imported occurrences, but the correct info on the 
139   -- *binding* declaration. It's the type checker that propagates the 
140   -- correct information to all the occurrences.
141   -- Since implicitly-imported names never occur in error messages,
142   -- it doesn't matter that we get the correct info in place till later,
143   -- (but since it affects DLL-ery it does matter that we get it right
144   --  in the end).
145 newGlobalName mod_name occ
146   = getNameSupplyRn             `thenRn` \ name_supply ->
147     let
148         key = (mod_name, occ)
149         cache = nsNames name_supply
150     in
151     case lookupFM cache key of
152         Just name -> -- traceRn (text "newGlobalName: hit" <+> ppr name) `thenRn_`
153                      returnRn name
154
155         Nothing   -> setNameSupplyRn (name_supply {nsUniqs = us', nsNames = new_cache})  `thenRn_`
156                      -- traceRn (text "newGlobalName: new" <+> ppr name)                  `thenRn_`
157                      returnRn name
158                   where
159                      (us', us1) = splitUniqSupply (nsUniqs name_supply)
160                      uniq       = uniqFromSupply us1
161                      mod        = mkVanillaModule mod_name
162                      name       = mkGlobalName uniq mod occ noSrcLoc
163                      new_cache  = addToFM cache key name
164
165 newIPName rdr_name_ip
166   = getNameSupplyRn             `thenRn` \ name_supply ->
167     let
168         ipcache = nsIPs name_supply
169     in
170     case lookupFM ipcache key of
171         Just name_ip -> returnRn name_ip
172         Nothing      -> setNameSupplyRn new_ns  `thenRn_`
173                         returnRn name_ip
174                   where
175                      (us', us1)  = splitUniqSupply (nsUniqs name_supply)
176                      uniq        = uniqFromSupply us1
177                      name_ip     = mapIPName mk_name rdr_name_ip
178                      mk_name rdr_name = mkIPName uniq (rdrNameOcc rdr_name)
179                      new_ipcache = addToFM ipcache key name_ip
180                      new_ns      = name_supply {nsUniqs = us', nsIPs = new_ipcache}
181     where 
182         key = rdr_name_ip       -- Ensures that ?x and %x get distinct Names
183 \end{code}
184
185 %*********************************************************
186 %*                                                      *
187 \subsection{Looking up names}
188 %*                                                      *
189 %*********************************************************
190
191 Looking up a name in the RnEnv.
192
193 \begin{code}
194 lookupBndrRn rdr_name
195   = getLocalNameEnv             `thenRn` \ local_env ->
196     case lookupRdrEnv local_env rdr_name of 
197           Just name -> returnRn name
198           Nothing   -> lookupTopBndrRn rdr_name
199
200 lookupTopBndrRn rdr_name
201 -- Look up a top-level local binder.   We may be looking up an unqualified 'f',
202 -- and there may be several imported 'f's too, which must not confuse us.
203 -- So we have to filter out the non-local ones.
204 -- A separate function (importsFromLocalDecls) reports duplicate top level
205 -- decls, so here it's safe just to choose an arbitrary one.
206
207   | isOrig rdr_name
208         -- This is here just to catch the PrelBase defn of (say) [] and similar
209         -- The parser reads the special syntax and returns an Orig RdrName
210         -- But the global_env contains only Qual RdrNames, so we won't
211         -- find it there; instead just get the name via the Orig route
212   = lookupOrigName rdr_name
213
214   | otherwise
215   = getModeRn   `thenRn` \ mode ->
216     if isInterfaceMode mode
217         then lookupIfaceName rdr_name   
218     else 
219     getModuleRn         `thenRn` \ mod ->
220     getGlobalNameEnv    `thenRn` \ global_env ->
221     case lookup_local mod global_env rdr_name of
222         Just name -> returnRn name
223         Nothing   -> failWithRn (mkUnboundName rdr_name)
224                                 (unknownNameErr rdr_name)
225   where
226     lookup_local mod global_env rdr_name
227       = case lookupRdrEnv global_env rdr_name of
228           Nothing   -> Nothing
229           Just gres -> case [n | GRE n _ _ <- gres, nameIsLocalOrFrom mod n] of
230                          []     -> Nothing
231                          (n:ns) -> Just n
232               
233
234 -- lookupSigOccRn is used for type signatures and pragmas
235 -- Is this valid?
236 --   module A
237 --      import M( f )
238 --      f :: Int -> Int
239 --      f x = x
240 -- It's clear that the 'f' in the signature must refer to A.f
241 -- The Haskell98 report does not stipulate this, but it will!
242 -- So we must treat the 'f' in the signature in the same way
243 -- as the binding occurrence of 'f', using lookupBndrRn
244 lookupSigOccRn :: RdrName -> RnMS Name
245 lookupSigOccRn = lookupBndrRn
246
247 -- lookupOccRn looks up an occurrence of a RdrName
248 lookupOccRn :: RdrName -> RnMS Name
249 lookupOccRn rdr_name
250   = getLocalNameEnv                     `thenRn` \ local_env ->
251     case lookupRdrEnv local_env rdr_name of
252           Just name -> returnRn name
253           Nothing   -> lookupGlobalOccRn rdr_name
254
255 -- lookupGlobalOccRn is like lookupOccRn, except that it looks in the global 
256 -- environment.  It's used only for
257 --      record field names
258 --      class op names in class and instance decls
259
260 lookupGlobalOccRn rdr_name
261   = getModeRn           `thenRn` \ mode ->
262     if (isInterfaceMode mode)
263         then lookupIfaceName rdr_name
264         else 
265
266     getGlobalNameEnv    `thenRn` \ global_env ->
267     case mode of 
268         SourceMode -> lookupSrcName global_env rdr_name
269
270         CmdLineMode
271          | not (isQual rdr_name) -> 
272                 lookupSrcName global_env rdr_name
273
274                 -- We allow qualified names on the command line to refer to 
275                 -- *any* name exported by any module in scope, just as if 
276                 -- there was an "import qualified M" declaration for every 
277                 -- module.
278                 --
279                 -- First look up the name in the normal environment.  If
280                 -- it isn't there, we manufacture a new occurrence of an
281                 -- original name.
282          | otherwise -> 
283                 case lookupRdrEnv global_env rdr_name of
284                        Just _  -> lookupSrcName global_env rdr_name
285                        Nothing -> lookupQualifiedName rdr_name
286
287 -- a qualified name on the command line can refer to any module at all: we
288 -- try to load the interface if we don't already have it.
289 lookupQualifiedName :: RdrName -> RnM d Name
290 lookupQualifiedName rdr_name
291  = let 
292        mod = rdrNameModule rdr_name
293        occ = rdrNameOcc rdr_name
294    in
295    loadInterface (ppr rdr_name) mod ImportByUser `thenRn` \ iface ->
296    case  [ name | (_,avails) <- mi_exports iface,
297            avail             <- avails,
298            name              <- availNames avail,
299            nameOccName name == occ ] of
300       (n:ns) -> ASSERT (null ns) returnRn n
301       _      -> failWithRn (mkUnboundName rdr_name) (unknownNameErr rdr_name)
302
303 lookupSrcName :: GlobalRdrEnv -> RdrName -> RnM d Name
304 -- NB: passed GlobalEnv explicitly, not necessarily in RnMS monad
305 lookupSrcName global_env rdr_name
306   | isOrig rdr_name     -- Can occur in source code too
307   = lookupOrigName rdr_name
308
309   | otherwise
310   = case lookupRdrEnv global_env rdr_name of
311         Just [GRE name _ Nothing]       -> returnRn name
312         Just [GRE name _ (Just deprec)] -> warnDeprec name deprec       `thenRn_`
313                                            returnRn name
314         Just stuff@(GRE name _ _ : _)   -> addNameClashErrRn rdr_name stuff     `thenRn_`
315                                            returnRn name
316         Nothing                         -> failWithRn (mkUnboundName rdr_name)
317                                                       (unknownNameErr rdr_name)
318
319 lookupOrigName :: RdrName -> RnM d Name 
320 lookupOrigName rdr_name
321   = ASSERT( isOrig rdr_name )
322     newGlobalName (rdrNameModule rdr_name) (rdrNameOcc rdr_name)
323
324 lookupIfaceUnqual :: RdrName -> RnM d Name
325 lookupIfaceUnqual rdr_name
326   = ASSERT( isUnqual rdr_name )
327         -- An Unqual is allowed; interface files contain 
328         -- unqualified names for locally-defined things, such as
329         -- constructors of a data type.
330     getModuleRn                         `thenRn ` \ mod ->
331     newGlobalName (moduleName mod) (rdrNameOcc rdr_name)
332
333 lookupIfaceName :: RdrName -> RnM d Name
334 lookupIfaceName rdr_name
335   | isUnqual rdr_name = lookupIfaceUnqual rdr_name
336   | otherwise         = lookupOrigName rdr_name
337 \end{code}
338
339 @lookupOrigName@ takes an RdrName representing an {\em original}
340 name, and adds it to the occurrence pool so that it'll be loaded
341 later.  This is used when language constructs (such as monad
342 comprehensions, overloaded literals, or deriving clauses) require some
343 stuff to be loaded that isn't explicitly mentioned in the code.
344
345 This doesn't apply in interface mode, where everything is explicit,
346 but we don't check for this case: it does no harm to record an
347 ``extra'' occurrence and @lookupOrigNames@ isn't used much in
348 interface mode (it's only the @Nothing@ clause of @rnDerivs@ that
349 calls it at all I think).
350
351   \fbox{{\em Jan 98: this comment is wrong: @rnHsType@ uses it quite a bit.}}
352
353 \begin{code}
354 lookupOrigNames :: [RdrName] -> RnM d NameSet
355 lookupOrigNames rdr_names
356   = mapRn lookupOrigName rdr_names      `thenRn` \ names ->
357     returnRn (mkNameSet names)
358 \end{code}
359
360 lookupSysBinder is used for the "system binders" of a type, class, or
361 instance decl.  It ensures that the module is set correctly in the
362 name cache, and sets the provenance on the returned name too.  The
363 returned name will end up actually in the type, class, or instance.
364
365 \begin{code}
366 lookupSysBinder rdr_name
367   = ASSERT( isUnqual rdr_name )
368     getModuleRn                         `thenRn` \ mod ->
369     getSrcLocRn                         `thenRn` \ loc ->
370     newTopBinder mod rdr_name loc
371 \end{code}
372
373
374 %*********************************************************
375 %*                                                      *
376 \subsection{Implicit free vars and sugar names}
377 %*                                                      *
378 %*********************************************************
379
380 @getXImplicitFVs@ forces the renamer to slurp in some things which aren't
381 mentioned explicitly, but which might be needed by the type checker.
382
383 \begin{code}
384 getImplicitStmtFVs      -- Compiling a statement
385   = returnRn (mkFVs [printName, bindIOName, returnIOName, failIOName]
386               `plusFV` ubiquitousNames)
387                 -- These are all needed implicitly when compiling a statement
388                 -- See TcModule.tc_stmts
389
390 getImplicitModuleFVs mod_name decls     -- Compiling a module
391   = lookupOrigNames deriv_occs          `thenRn` \ deriving_names ->
392     returnRn (deriving_names `plusFV` implicit_main `plusFV` ubiquitousNames)
393   where
394         -- Add occurrences for IO or PrimIO
395         implicit_main |  mod_name == mAIN_Name
396                       || mod_name == pREL_MAIN_Name = unitFV ioTyConName
397                       |  otherwise                  = emptyFVs
398
399         deriv_occs = [occ | TyClD (TyData {tcdDerivs = Just deriv_classes}) <- decls,
400                             cls <- deriv_classes,
401                             occ <- lookupWithDefaultUFM derivingOccurrences [] cls ]
402
403 -- ubiquitous_names are loaded regardless, because 
404 -- they are needed in virtually every program
405 ubiquitousNames 
406   = mkFVs [unpackCStringName, unpackCStringFoldrName, 
407            unpackCStringUtf8Name, eqStringName]
408         -- Virtually every program has error messages in it somewhere
409
410   `plusFV`
411     mkFVs [getName unitTyCon, funTyConName, boolTyConName, intTyConName]
412         -- Add occurrences for very frequently used types.
413         --       (e.g. we don't want to be bothered with making funTyCon a
414         --        free var at every function application!)
415 \end{code}
416
417 %************************************************************************
418 %*                                                                      *
419 \subsection{Re-bindable desugaring names}
420 %*                                                                      *
421 %************************************************************************
422
423 Haskell 98 says that when you say "3" you get the "fromInteger" from the
424 Standard Prelude, regardless of what is in scope.   However, to experiment
425 with having a language that is less coupled to the standard prelude, we're
426 trying a non-standard extension that instead gives you whatever "Prelude.fromInteger"
427 happens to be in scope.  Then you can
428         import Prelude ()
429         import MyPrelude as Prelude
430 to get the desired effect.
431
432 At the moment this just happens for
433   * fromInteger, fromRational on literals (in expressions and patterns)
434   * negate (in expressions)
435   * minus  (arising from n+k patterns)
436
437 We store the relevant Name in the HsSyn tree, in 
438   * HsIntegral/HsFractional     
439   * NegApp
440   * NPlusKPatIn
441 respectively.  Initially, we just store the "standard" name (PrelNames.fromIntegralName,
442 fromRationalName etc), but the renamer changes this to the appropriate user
443 name if Opt_NoImplicitPrelude is on.  That is what lookupSyntaxName does.
444
445 \begin{code}
446 lookupSyntaxName :: Name        -- The standard name
447                  -> RnMS Name   -- Possibly a non-standard name
448 lookupSyntaxName std_name
449   = doptRn Opt_NoImplicitPrelude        `thenRn` \ no_prelude -> 
450     if not no_prelude then
451         returnRn std_name       -- Normal case
452     else
453     let
454         rdr_name = mkRdrUnqual (nameOccName std_name)
455         -- Get the similarly named thing from the local environment
456     in
457     lookupOccRn rdr_name
458 \end{code}
459
460
461 %*********************************************************
462 %*                                                      *
463 \subsection{Binding}
464 %*                                                      *
465 %*********************************************************
466
467 \begin{code}
468 newLocalsRn :: [(RdrName,SrcLoc)]
469             -> RnMS [Name]
470 newLocalsRn rdr_names_w_loc
471  =  getNameSupplyRn             `thenRn` \ name_supply ->
472     let
473         (us', us1) = splitUniqSupply (nsUniqs name_supply)
474         uniqs      = uniqsFromSupply us1
475         names      = [ mkLocalName uniq (rdrNameOcc rdr_name) loc
476                      | ((rdr_name,loc), uniq) <- rdr_names_w_loc `zip` uniqs
477                      ]
478     in
479     setNameSupplyRn (name_supply {nsUniqs = us'})       `thenRn_`
480     returnRn names
481
482
483 bindLocatedLocalsRn :: SDoc     -- Documentation string for error message
484                     -> [(RdrName,SrcLoc)]
485                     -> ([Name] -> RnMS a)
486                     -> RnMS a
487 bindLocatedLocalsRn doc_str rdr_names_w_loc enclosed_scope
488   = getModeRn                           `thenRn` \ mode ->
489     getLocalNameEnv                     `thenRn` \ local_env ->
490     getGlobalNameEnv                    `thenRn` \ global_env ->
491
492         -- Check for duplicate names
493     checkDupOrQualNames doc_str rdr_names_w_loc `thenRn_`
494
495         -- Warn about shadowing, but only in source modules
496     let
497       check_shadow (rdr_name,loc)
498         |  rdr_name `elemRdrEnv` local_env 
499         || rdr_name `elemRdrEnv` global_env 
500         = pushSrcLocRn loc $ addWarnRn (shadowedNameWarn rdr_name)
501         | otherwise 
502         = returnRn ()
503     in
504
505     (case mode of
506         SourceMode -> ifOptRn Opt_WarnNameShadowing     $
507                       mapRn_ check_shadow rdr_names_w_loc
508         other      -> returnRn ()
509     )                                   `thenRn_`
510
511     newLocalsRn rdr_names_w_loc         `thenRn` \ names ->
512     let
513         new_local_env = addListToRdrEnv local_env (map fst rdr_names_w_loc `zip` names)
514     in
515     setLocalNameEnv new_local_env (enclosed_scope names)
516
517 bindCoreLocalRn :: RdrName -> (Name -> RnMS a) -> RnMS a
518   -- A specialised variant when renaming stuff from interface
519   -- files (of which there is a lot)
520   --    * one at a time
521   --    * no checks for shadowing
522   --    * always imported
523   --    * deal with free vars
524 bindCoreLocalRn rdr_name enclosed_scope
525   = getSrcLocRn                 `thenRn` \ loc ->
526     getLocalNameEnv             `thenRn` \ name_env ->
527     getNameSupplyRn             `thenRn` \ name_supply ->
528     let
529         (us', us1) = splitUniqSupply (nsUniqs name_supply)
530         uniq       = uniqFromSupply us1
531         name       = mkLocalName uniq (rdrNameOcc rdr_name) loc
532     in
533     setNameSupplyRn (name_supply {nsUniqs = us'})       `thenRn_`
534     let
535         new_name_env = extendRdrEnv name_env rdr_name name
536     in
537     setLocalNameEnv new_name_env (enclosed_scope name)
538
539 bindCoreLocalsRn []     thing_inside = thing_inside []
540 bindCoreLocalsRn (b:bs) thing_inside = bindCoreLocalRn b        $ \ name' ->
541                                        bindCoreLocalsRn bs      $ \ names' ->
542                                        thing_inside (name':names')
543
544 bindLocalNames names enclosed_scope
545   = getLocalNameEnv             `thenRn` \ name_env ->
546     setLocalNameEnv (extendLocalRdrEnv name_env names)
547                     enclosed_scope
548
549 bindLocalNamesFV names enclosed_scope
550   = bindLocalNames names $
551     enclosed_scope `thenRn` \ (thing, fvs) ->
552     returnRn (thing, delListFromNameSet fvs names)
553
554
555 -------------------------------------
556 bindLocalRn doc rdr_name enclosed_scope
557   = getSrcLocRn                                 `thenRn` \ loc ->
558     bindLocatedLocalsRn doc [(rdr_name,loc)]    $ \ (n:ns) ->
559     ASSERT( null ns )
560     enclosed_scope n
561
562 bindLocalsRn doc rdr_names enclosed_scope
563   = getSrcLocRn         `thenRn` \ loc ->
564     bindLocatedLocalsRn doc
565                         (rdr_names `zip` repeat loc)
566                         enclosed_scope
567
568         -- binLocalsFVRn is the same as bindLocalsRn
569         -- except that it deals with free vars
570 bindLocalsFVRn doc rdr_names enclosed_scope
571   = bindLocalsRn doc rdr_names          $ \ names ->
572     enclosed_scope names                `thenRn` \ (thing, fvs) ->
573     returnRn (thing, delListFromNameSet fvs names)
574
575 -------------------------------------
576 extendTyVarEnvFVRn :: [Name] -> RnMS (a, FreeVars) -> RnMS (a, FreeVars)
577         -- This tiresome function is used only in rnSourceDecl on InstDecl
578 extendTyVarEnvFVRn tyvars enclosed_scope
579   = bindLocalNames tyvars enclosed_scope        `thenRn` \ (thing, fvs) -> 
580     returnRn (thing, delListFromNameSet fvs tyvars)
581
582 bindTyVarsRn :: SDoc -> [HsTyVarBndr RdrName]
583               -> ([HsTyVarBndr Name] -> RnMS a)
584               -> RnMS a
585 bindTyVarsRn doc_str tyvar_names enclosed_scope
586   = bindTyVars2Rn doc_str tyvar_names   $ \ names tyvars ->
587     enclosed_scope tyvars
588
589 -- Gruesome name: return Names as well as HsTyVars
590 bindTyVars2Rn :: SDoc -> [HsTyVarBndr RdrName]
591               -> ([Name] -> [HsTyVarBndr Name] -> RnMS a)
592               -> RnMS a
593 bindTyVars2Rn doc_str tyvar_names enclosed_scope
594   = getSrcLocRn                                 `thenRn` \ loc ->
595     let
596         located_tyvars = [(hsTyVarName tv, loc) | tv <- tyvar_names] 
597     in
598     bindLocatedLocalsRn doc_str located_tyvars  $ \ names ->
599     enclosed_scope names (zipWith replaceTyVarName tyvar_names names)
600
601 bindPatSigTyVars :: [RdrNameHsType]
602                  -> RnMS (a, FreeVars)
603                  -> RnMS (a, FreeVars)
604   -- Find the type variables in the pattern type 
605   -- signatures that must be brought into scope
606
607 bindPatSigTyVars tys enclosed_scope
608   = getLocalNameEnv                     `thenRn` \ name_env ->
609     getSrcLocRn                         `thenRn` \ loc ->
610     let
611         forall_tyvars  = nub [ tv | ty <- tys,
612                                     tv <- extractHsTyRdrTyVars ty, 
613                                     not (tv `elemFM` name_env)
614                          ]
615                 -- The 'nub' is important.  For example:
616                 --      f (x :: t) (y :: t) = ....
617                 -- We don't want to complain about binding t twice!
618
619         located_tyvars = [(tv, loc) | tv <- forall_tyvars] 
620         doc_sig        = text "In a pattern type-signature"
621     in
622     bindLocatedLocalsRn doc_sig located_tyvars  $ \ names ->
623     enclosed_scope                              `thenRn` \ (thing, fvs) ->
624     returnRn (thing, delListFromNameSet fvs names)
625
626
627 -------------------------------------
628 checkDupOrQualNames, checkDupNames :: SDoc
629                                    -> [(RdrName, SrcLoc)]
630                                    -> RnM d ()
631         -- Works in any variant of the renamer monad
632
633 checkDupOrQualNames doc_str rdr_names_w_loc
634   =     -- Check for use of qualified names
635     mapRn_ (qualNameErr doc_str) quals  `thenRn_`
636     checkDupNames doc_str rdr_names_w_loc
637   where
638     quals = filter (isQual . fst) rdr_names_w_loc
639     
640 checkDupNames doc_str rdr_names_w_loc
641   =     -- Check for duplicated names in a binding group
642     mapRn_ (dupNamesErr doc_str) dups
643   where
644     (_, dups) = removeDups (\(n1,l1) (n2,l2) -> n1 `compare` n2) rdr_names_w_loc
645 \end{code}
646
647
648 %************************************************************************
649 %*                                                                      *
650 \subsection{GlobalRdrEnv}
651 %*                                                                      *
652 %************************************************************************
653
654 \begin{code}
655 mkGlobalRdrEnv :: ModuleName            -- Imported module (after doing the "as M" name change)
656                -> Bool                  -- True <=> want unqualified import
657                -> (Name -> Provenance)
658                -> Avails                -- Whats imported
659                -> Avails                -- What's to be hidden
660                                         -- I.e. import (imports - hides)
661                -> Deprecations
662                -> GlobalRdrEnv
663
664 mkGlobalRdrEnv this_mod unqual_imp mk_provenance avails hides deprecs
665   = gbl_env3
666   where
667         -- Make the name environment.  We're talking about a 
668         -- single module here, so there must be no name clashes.
669         -- In practice there only ever will be if it's the module
670         -- being compiled.
671
672         -- Add qualified names for the things that are available
673         -- (Qualified names are always imported)
674     gbl_env1 = foldl add_avail emptyRdrEnv avails
675
676         -- Delete (qualified names of) things that are hidden
677     gbl_env2 = foldl del_avail gbl_env1 hides
678
679         -- Add unqualified names
680     gbl_env3 | unqual_imp = foldl add_unqual gbl_env2 (rdrEnvToList gbl_env2)
681              | otherwise  = gbl_env2
682
683     add_unqual env (qual_name, elts)
684         = foldl add_one env elts
685         where
686           add_one env elt = addOneToGlobalRdrEnv env unqual_name elt
687           unqual_name     = unqualifyRdrName qual_name
688         -- The qualified import should only have added one 
689         -- binding for each qualified name!  But if there's an error in
690         -- the module (multiple bindings for the same name) we may get
691         -- duplicates.  So the simple thing is to do the fold.
692
693     del_avail env avail 
694         = foldl delOneFromGlobalRdrEnv env rdr_names
695         where
696           rdr_names = map (mkRdrQual this_mod . nameOccName)
697                           (availNames avail)
698
699
700     add_avail :: GlobalRdrEnv -> AvailInfo -> GlobalRdrEnv
701     add_avail env avail = foldl add_name env (availNames avail)
702
703     add_name env name   -- Add qualified name only
704         = addOneToGlobalRdrEnv env  (mkRdrQual this_mod occ) elt
705         where
706           occ  = nameOccName name
707           elt  = GRE name (mk_provenance name) (lookupDeprec deprecs name)
708
709 mkIfaceGlobalRdrEnv :: [(ModuleName,Avails)] -> GlobalRdrEnv
710 -- Used to construct a GlobalRdrEnv for an interface that we've
711 -- read from a .hi file.  We can't construct the original top-level
712 -- environment because we don't have enough info, but we compromise
713 -- by making an environment from its exports
714 mkIfaceGlobalRdrEnv m_avails
715   = foldl add emptyRdrEnv m_avails
716   where
717     add env (mod,avails) = plusGlobalRdrEnv env (mkGlobalRdrEnv mod True 
718                                                                 (\n -> LocalDef) avails [] NoDeprecs)
719                 -- The NoDeprecs is a bit of a hack I suppose
720 \end{code}
721
722 \begin{code}
723 plusGlobalRdrEnv :: GlobalRdrEnv -> GlobalRdrEnv -> GlobalRdrEnv
724 plusGlobalRdrEnv env1 env2 = plusFM_C combine_globals env1 env2
725
726 addOneToGlobalRdrEnv :: GlobalRdrEnv -> RdrName -> GlobalRdrElt -> GlobalRdrEnv
727 addOneToGlobalRdrEnv env rdr_name name = addToFM_C combine_globals env rdr_name [name]
728
729 delOneFromGlobalRdrEnv :: GlobalRdrEnv -> RdrName -> GlobalRdrEnv 
730 delOneFromGlobalRdrEnv env rdr_name = delFromFM env rdr_name
731
732 combine_globals :: [GlobalRdrElt]       -- Old
733                 -> [GlobalRdrElt]       -- New
734                 -> [GlobalRdrElt]
735 combine_globals ns_old ns_new   -- ns_new is often short
736   = foldr add ns_old ns_new
737   where
738     add n ns | any (is_duplicate n) ns_old = map (choose n) ns  -- Eliminate duplicates
739              | otherwise                   = n:ns
740
741     choose n m | n `beats` m = n
742                | otherwise   = m
743
744     (GRE n pn _) `beats` (GRE m pm _) = n==m && pn `hasBetterProv` pm
745
746     is_duplicate :: GlobalRdrElt -> GlobalRdrElt -> Bool
747     is_duplicate (GRE n1 LocalDef _) (GRE n2 LocalDef _) = False
748     is_duplicate (GRE n1 _        _) (GRE n2 _        _) = n1 == n2
749 \end{code}
750
751 We treat two bindings of a locally-defined name as a duplicate,
752 because they might be two separate, local defns and we want to report
753 and error for that, {\em not} eliminate a duplicate.
754
755 On the other hand, if you import the same name from two different
756 import statements, we {\em do} want to eliminate the duplicate, not report
757 an error.
758
759 If a module imports itself then there might be a local defn and an imported
760 defn of the same name; in this case the names will compare as equal, but
761 will still have different provenances.
762
763
764 @unQualInScope@ returns a function that takes a @Name@ and tells whether
765 its unqualified name is in scope.  This is put as a boolean flag in
766 the @Name@'s provenance to guide whether or not to print the name qualified
767 in error messages.
768
769 \begin{code}
770 unQualInScope :: GlobalRdrEnv -> Name -> Bool
771 -- True if 'f' is in scope, and has only one binding
772 -- (i.e. false if A.f and B.f are both in scope as unqualified 'f')
773 unQualInScope env
774   = (`elemNameSet` unqual_names)
775   where
776     unqual_names :: NameSet
777     unqual_names = foldRdrEnv add emptyNameSet env
778     add rdr_name [GRE name _ _] unquals | isUnqual rdr_name = addOneToNameSet unquals name
779     add _        _              unquals                     = unquals
780 \end{code}
781
782
783 %************************************************************************
784 %*                                                                      *
785 \subsection{Avails}
786 %*                                                                      *
787 %************************************************************************
788
789 \begin{code}
790 plusAvail (Avail n1)       (Avail n2)       = Avail n1
791 plusAvail (AvailTC n1 ns1) (AvailTC n2 ns2) = AvailTC n2 (nub (ns1 ++ ns2))
792 -- Added SOF 4/97
793 #ifdef DEBUG
794 plusAvail a1 a2 = pprPanic "RnEnv.plusAvail" (hsep [ppr a1,ppr a2])
795 #endif
796
797 addAvail :: AvailEnv -> AvailInfo -> AvailEnv
798 addAvail avails avail = extendNameEnv_C plusAvail avails (availName avail) avail
799
800 emptyAvailEnv = emptyNameEnv
801 unitAvailEnv :: AvailInfo -> AvailEnv
802 unitAvailEnv a = unitNameEnv (availName a) a
803
804 plusAvailEnv :: AvailEnv -> AvailEnv -> AvailEnv
805 plusAvailEnv = plusNameEnv_C plusAvail
806
807 availEnvElts = nameEnvElts
808
809 addAvailToNameSet :: NameSet -> AvailInfo -> NameSet
810 addAvailToNameSet names avail = addListToNameSet names (availNames avail)
811
812 availsToNameSet :: [AvailInfo] -> NameSet
813 availsToNameSet avails = foldl addAvailToNameSet emptyNameSet avails
814
815 availName :: GenAvailInfo name -> name
816 availName (Avail n)     = n
817 availName (AvailTC n _) = n
818
819 availNames :: GenAvailInfo name -> [name]
820 availNames (Avail n)      = [n]
821 availNames (AvailTC n ns) = ns
822
823 -------------------------------------
824 filterAvail :: RdrNameIE        -- Wanted
825             -> AvailInfo        -- Available
826             -> Maybe AvailInfo  -- Resulting available; 
827                                 -- Nothing if (any of the) wanted stuff isn't there
828
829 filterAvail ie@(IEThingWith want wants) avail@(AvailTC n ns)
830   | sub_names_ok = Just (AvailTC n (filter is_wanted ns))
831   | otherwise    = Nothing
832   where
833     is_wanted name = nameOccName name `elem` wanted_occs
834     sub_names_ok   = all (`elem` avail_occs) wanted_occs
835     avail_occs     = map nameOccName ns
836     wanted_occs    = map rdrNameOcc (want:wants)
837
838 filterAvail (IEThingAbs _) (AvailTC n ns)       = ASSERT( n `elem` ns ) 
839                                                   Just (AvailTC n [n])
840
841 filterAvail (IEThingAbs _) avail@(Avail n)      = Just avail            -- Type synonyms
842
843 filterAvail (IEVar _)      avail@(Avail n)      = Just avail
844 filterAvail (IEVar v)      avail@(AvailTC n ns) = Just (AvailTC n (filter wanted ns))
845                                                 where
846                                                   wanted n = nameOccName n == occ
847                                                   occ      = rdrNameOcc v
848         -- The second equation happens if we import a class op, thus
849         --      import A( op ) 
850         -- where op is a class operation
851
852 filterAvail (IEThingAll _) avail@(AvailTC _ _)   = Just avail
853         -- We don't complain even if the IE says T(..), but
854         -- no constrs/class ops of T are available
855         -- Instead that's caught with a warning by the caller
856
857 filterAvail ie avail = Nothing
858
859 -------------------------------------
860 groupAvails :: Module -> Avails -> [(ModuleName, Avails)]
861   -- Group by module and sort by occurrence
862   -- This keeps the list in canonical order
863 groupAvails this_mod avails 
864   = [ (mkSysModuleNameFS fs, sortLt lt avails)
865     | (fs,avails) <- fmToList groupFM
866     ]
867   where
868     groupFM :: FiniteMap FastString Avails
869         -- Deliberately use the FastString so we
870         -- get a canonical ordering
871     groupFM = foldl add emptyFM avails
872
873     add env avail = addToFM_C combine env mod_fs [avail']
874                   where
875                     mod_fs = moduleNameFS (moduleName avail_mod)
876                     avail_mod = case nameModule_maybe (availName avail) of
877                                           Just m  -> m
878                                           Nothing -> this_mod
879                     combine old _ = avail':old
880                     avail'        = sortAvail avail
881
882     a1 `lt` a2 = occ1 < occ2
883                where
884                  occ1  = nameOccName (availName a1)
885                  occ2  = nameOccName (availName a2)
886
887 sortAvail :: AvailInfo -> AvailInfo
888 -- Sort the sub-names into canonical order.
889 -- The canonical order has the "main name" at the beginning 
890 -- (if it's there at all)
891 sortAvail (Avail n) = Avail n
892 sortAvail (AvailTC n ns) | n `elem` ns = AvailTC n (n : sortLt lt (filter (/= n) ns))
893                          | otherwise   = AvailTC n (    sortLt lt ns)
894                          where
895                            n1 `lt` n2 = nameOccName n1 < nameOccName n2
896 \end{code}
897
898
899 %************************************************************************
900 %*                                                                      *
901 \subsection{Free variable manipulation}
902 %*                                                                      *
903 %************************************************************************
904
905 \begin{code}
906 -- A useful utility
907 mapFvRn f xs = mapRn f xs       `thenRn` \ stuff ->
908                let
909                   (ys, fvs_s) = unzip stuff
910                in
911                returnRn (ys, plusFVs fvs_s)
912 \end{code}
913
914
915 %************************************************************************
916 %*                                                                      *
917 \subsection{Envt utility functions}
918 %*                                                                      *
919 %************************************************************************
920
921 \begin{code}
922 warnUnusedModules :: [ModuleName] -> RnM d ()
923 warnUnusedModules mods
924   = ifOptRn Opt_WarnUnusedImports (mapRn_ (addWarnRn . unused_mod) mods)
925   where
926     unused_mod m = vcat [ptext SLIT("Module") <+> quotes (ppr m) <+> 
927                            text "is imported, but nothing from it is used",
928                          parens (ptext SLIT("except perhaps to re-export instances visible in") <+>
929                                    quotes (ppr m))]
930
931 warnUnusedImports :: [(Name,Provenance)] -> RnM d ()
932 warnUnusedImports names
933   = ifOptRn Opt_WarnUnusedImports (warnUnusedBinds names)
934
935 warnUnusedLocalBinds, warnUnusedMatches :: [Name] -> RnM d ()
936 warnUnusedLocalBinds names
937   = ifOptRn Opt_WarnUnusedBinds (warnUnusedBinds [(n,LocalDef) | n<-names])
938
939 warnUnusedMatches names
940   = ifOptRn Opt_WarnUnusedMatches (warnUnusedGroup [(n,LocalDef) | n<-names])
941
942 -------------------------
943
944 warnUnusedBinds :: [(Name,Provenance)] -> RnM d ()
945 warnUnusedBinds names
946   = mapRn_ warnUnusedGroup  groups
947   where
948         -- Group by provenance
949    groups = equivClasses cmp names
950    (_,prov1) `cmp` (_,prov2) = prov1 `compare` prov2
951  
952
953 -------------------------
954
955 warnUnusedGroup :: [(Name,Provenance)] -> RnM d ()
956 warnUnusedGroup names
957   | null filtered_names  = returnRn ()
958   | not is_local         = returnRn ()
959   | otherwise
960   = pushSrcLocRn def_loc        $
961     addWarnRn                   $
962     sep [msg <> colon, nest 4 (fsep (punctuate comma (map (ppr.fst) filtered_names)))]
963   where
964     filtered_names = filter reportable names
965     (name1, prov1) = head filtered_names
966     (is_local, def_loc, msg)
967         = case prov1 of
968                 LocalDef -> (True, getSrcLoc name1, text "Defined but not used")
969
970                 NonLocalDef (UserImport mod loc _)
971                         -> (True, loc, text "Imported from" <+> quotes (ppr mod) <+> text "but not used")
972
973     reportable (name,_) = case occNameUserString (nameOccName name) of
974                                 ('_' : _) -> False
975                                 zz_other  -> True
976         -- Haskell 98 encourages compilers to suppress warnings about
977         -- unused names in a pattern if they start with "_".
978 \end{code}
979
980 \begin{code}
981 addNameClashErrRn rdr_name (np1:nps)
982   = addErrRn (vcat [ptext SLIT("Ambiguous occurrence") <+> quotes (ppr rdr_name),
983                     ptext SLIT("It could refer to") <+> vcat (msg1 : msgs)])
984   where
985     msg1 = ptext  SLIT("either") <+> mk_ref np1
986     msgs = [ptext SLIT("    or") <+> mk_ref np | np <- nps]
987     mk_ref (GRE name prov _) = quotes (ppr name) <> comma <+> pprNameProvenance name prov
988
989 shadowedNameWarn shadow
990   = hsep [ptext SLIT("This binding for"), 
991                quotes (ppr shadow),
992                ptext SLIT("shadows an existing binding")]
993
994 unknownNameErr name
995   = sep [text flavour, ptext SLIT("not in scope:"), quotes (ppr name)]
996   where
997     flavour = occNameFlavour (rdrNameOcc name)
998
999 qualNameErr descriptor (name,loc)
1000   = pushSrcLocRn loc $
1001     addErrRn (vcat [ ptext SLIT("Invalid use of qualified name") <+> quotes (ppr name),
1002                      descriptor])
1003
1004 dupNamesErr descriptor ((name,loc) : dup_things)
1005   = pushSrcLocRn loc $
1006     addErrRn ((ptext SLIT("Conflicting definitions for") <+> quotes (ppr name))
1007               $$ 
1008               descriptor)
1009
1010 warnDeprec :: Name -> DeprecTxt -> RnM d ()
1011 warnDeprec name txt
1012   = ifOptRn Opt_WarnDeprecations        $
1013     addWarnRn (sep [ text (occNameFlavour (nameOccName name)) <+> 
1014                      quotes (ppr name) <+> text "is deprecated:", 
1015                      nest 4 (ppr txt) ])
1016 \end{code}
1017