2844c72e11ba6724269a7c67a1e7a732fd5e041f
[ghc-hetmet.git] / ghc / compiler / rename / RnEnv.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1996
3 %
4 \section[RnEnv]{Environment manipulation for the renamer monad}
5
6 \begin{code}
7 #include "HsVersions.h"
8
9 module RnEnv where              -- Export everything
10
11 IMPORT_1_3(List (nub))
12 IMP_Ubiq()
13
14 import CmdLineOpts      ( opt_WarnNameShadowing )
15 import HsSyn
16 import RdrHsSyn         ( RdrName(..), SYN_IE(RdrNameIE),
17                           rdrNameOcc, ieOcc, isQual, qual
18                         )
19 import HsTypes          ( getTyVarName, replaceTyVarName )
20 import BasicTypes       ( Fixity(..), FixityDirection(..) )
21 import RnMonad
22 import Name             ( Name, OccName(..), Provenance(..), DefnInfo(..), ExportFlag(..), NamedThing(..),
23                           occNameString, occNameFlavour,
24                           SYN_IE(NameSet), emptyNameSet, addListToNameSet,
25                           mkLocalName, mkGlobalName, modAndOcc, isLocallyDefinedName,
26                           isWiredInName, nameOccName, setNameProvenance, isVarOcc, getNameProvenance,
27                           pprProvenance, pprOccName, pprModule, pprNameProvenance
28                         )
29 import TyCon            ( TyCon )
30 import TysWiredIn       ( tupleTyCon, listTyCon, charTyCon, intTyCon )
31 import FiniteMap
32 import Outputable
33 import Unique           ( Unique, unboundKey )
34 import UniqFM           ( Uniquable(..) )
35 import Maybes           ( maybeToBool )
36 import UniqSupply
37 import SrcLoc           ( SrcLoc, noSrcLoc )
38 import Pretty
39 import Outputable       ( PprStyle(..) )
40 import Util             --( panic, removeDups, pprTrace, assertPanic )
41
42 \end{code}
43
44
45
46 %*********************************************************
47 %*                                                      *
48 \subsection{Making new names}
49 %*                                                      *
50 %*********************************************************
51
52 \begin{code}
53 newGlobalName :: Module -> OccName -> RnM s d Name
54 newGlobalName mod occ
55   =     -- First check the cache
56     getNameSupplyRn             `thenRn` \ (us, inst_ns, cache) ->
57     let key = (mod,occ)         in
58     case lookupFM cache key of
59
60         -- A hit in the cache!  Return it, but change the src loc
61         -- of the thing we've found if this is a second definition site
62         -- (that is, if loc /= NoSrcLoc)
63         Just name ->  returnRn name
64
65         -- Miss in the cache, so build a new original name,
66         -- and put it in the cache
67         Nothing        -> 
68             let
69                 (us', us1) = splitUniqSupply us
70                 uniq       = getUnique us1
71                 name       = mkGlobalName uniq mod occ VanillaDefn Implicit
72                 cache'     = addToFM cache key name
73             in
74             setNameSupplyRn (us', inst_ns, cache')              `thenRn_`
75             returnRn name
76
77 newLocallyDefinedGlobalName :: Module -> OccName 
78                             -> (Name -> ExportFlag) -> SrcLoc
79                             -> RnM s d Name
80 newLocallyDefinedGlobalName mod occ rec_exp_fn loc
81   =     -- First check the cache
82     getNameSupplyRn             `thenRn` \ (us, inst_ns, cache) ->
83
84         -- We are at the binding site for a locally-defined thing, so
85         -- you might think it can't be in the cache, but it can if it's a
86         -- wired in thing. In that case we need to use the correct unique etc...
87         -- so all we do is replace its provenance.  
88         -- If it's not in the cache we put it there with the correct provenance.
89         -- The idea is that, after all this, the cache
90         -- will contain a Name with the correct Provenance (i.e. Local)
91         --
92         -- Actually, there's a catch.  If this is the *second* binding for something
93         -- we want to allocate a *fresh* unique, rather than using the same Name as before.
94         -- Otherwise we don't detect conflicting definitions of the same top-level name!
95         -- So the only time we re-use a Name already in the cache is when it's one of
96         -- the Implicit magic-unique ones mentioned in the previous para
97     let
98         provenance = LocalDef (rec_exp_fn new_name) loc
99         (us', us1) = splitUniqSupply us
100         uniq       = getUnique us1
101         key        = (mod,occ)
102         new_name   = case lookupFM cache key of
103                          Just name | is_implicit_prov
104                                    -> setNameProvenance name provenance
105                                    where
106                                       is_implicit_prov = case getNameProvenance name of
107                                                             Implicit -> True
108                                                             other    -> False
109                          other   -> mkGlobalName uniq mod occ VanillaDefn provenance
110
111         new_cache  = addToFM cache key new_name
112     in
113     setNameSupplyRn (us', inst_ns, new_cache)           `thenRn_`
114     returnRn new_name
115
116 -- newSysName is used to create the names for
117 --      a) default methods
118 -- These are never mentioned explicitly in source code (hence no point in looking
119 -- them up in the NameEnv), but when reading an interface file
120 -- we may want to slurp in their pragma info.  In the source file itself we
121 -- need to create these names too so that we export them into the inferface file for this module.
122
123 newSysName :: OccName -> ExportFlag -> SrcLoc -> RnMS s Name
124 newSysName occ export_flag loc
125   = getModeRn   `thenRn` \ mode ->
126     getModuleRn `thenRn` \ mod_name ->
127     case mode of 
128         SourceMode -> newLocallyDefinedGlobalName 
129                                 mod_name occ
130                                 (\_ -> export_flag)
131                                 loc
132         InterfaceMode _ -> newGlobalName mod_name occ
133
134 -- newDfunName is a variant, specially for dfuns.  
135 -- When renaming derived definitions we are in *interface* mode (because we can trip
136 -- over original names), but we still want to make the Dfun locally-defined.
137 -- So we can't use whether or not we're in source mode to decide the locally-defined question.
138 newDfunName :: Maybe RdrName -> SrcLoc -> RnMS s Name
139 newDfunName Nothing src_loc                     -- Local instance decls have a "Nothing"
140   = getModuleRn         `thenRn` \ mod_name ->
141     newInstUniq         `thenRn` \ inst_uniq ->
142     let
143         dfun_occ = VarOcc (_PK_ ("$d" ++ show inst_uniq))
144     in
145     newLocallyDefinedGlobalName mod_name dfun_occ 
146                                 (\_ -> Exported) src_loc
147
148 newDfunName (Just n) src_loc                    -- Imported ones have "Just n"
149   = getModuleRn         `thenRn` \ mod_name ->
150     newGlobalName mod_name (rdrNameOcc n)
151
152
153 newLocalNames :: [(RdrName,SrcLoc)] -> RnM s d [Name]
154 newLocalNames rdr_names
155   = getNameSupplyRn             `thenRn` \ (us, inst_ns, cache) ->
156     let
157         n          = length rdr_names
158         (us', us1) = splitUniqSupply us
159         uniqs      = getUniques n us1
160         locals     = [ mkLocalName uniq (rdrNameOcc rdr_name) loc
161                      | ((rdr_name,loc), uniq) <- rdr_names `zip` uniqs
162                      ]
163     in
164     setNameSupplyRn (us', inst_ns, cache)       `thenRn_`
165     returnRn locals
166
167 -- mkUnboundName makes a place-holder Name; it shouldn't be looked at except possibly
168 -- during compiler debugging.
169 mkUnboundName :: RdrName -> Name
170 mkUnboundName rdr_name = mkLocalName unboundKey (rdrNameOcc rdr_name) noSrcLoc
171
172 isUnboundName :: Name -> Bool
173 isUnboundName name = uniqueOf name == unboundKey
174 \end{code}
175
176 \begin{code}
177 bindLocatedLocalsRn :: (PprStyle -> Doc)                -- Documentation string for error message
178                     -> [(RdrName,SrcLoc)]
179                     -> ([Name] -> RnMS s a)
180                     -> RnMS s a
181 bindLocatedLocalsRn doc_str rdr_names_w_loc enclosed_scope
182   = checkDupOrQualNames doc_str rdr_names_w_loc `thenRn_`
183
184     getNameEnv                  `thenRn` \ name_env ->
185     (if opt_WarnNameShadowing
186      then
187         mapRn (check_shadow name_env) rdr_names_w_loc
188      else
189         returnRn []
190     )                                   `thenRn_`
191         
192     newLocalNames rdr_names_w_loc       `thenRn` \ names ->
193     let
194         new_name_env = addListToFM name_env (map fst rdr_names_w_loc `zip` names)
195     in
196     setNameEnv new_name_env (enclosed_scope names)
197   where
198     check_shadow name_env (rdr_name,loc)
199         = case lookupFM name_env rdr_name of
200                 Nothing   -> returnRn ()
201                 Just name -> pushSrcLocRn loc $
202                              addWarnRn (shadowedNameWarn rdr_name)
203
204 bindLocalsRn doc_str rdr_names enclosed_scope
205   = getSrcLocRn         `thenRn` \ loc ->
206     bindLocatedLocalsRn (\_ -> text doc_str)
207                         (rdr_names `zip` repeat loc)
208                         enclosed_scope
209
210 bindTyVarsRn doc_str tyvar_names enclosed_scope
211   = getSrcLocRn                                 `thenRn` \ loc ->
212     let
213         located_tyvars = [(getTyVarName tv, loc) | tv <- tyvar_names] 
214     in
215     bindLocatedLocalsRn doc_str located_tyvars  $ \ names ->
216     enclosed_scope (zipWith replaceTyVarName tyvar_names names)
217
218         -- Works in any variant of the renamer monad
219 checkDupOrQualNames, checkDupNames :: (PprStyle -> Doc)
220                                    -> [(RdrName, SrcLoc)]
221                                    -> RnM s d ()
222
223 checkDupOrQualNames doc_str rdr_names_w_loc
224   =     -- Check for use of qualified names
225     mapRn (qualNameErr doc_str) quals   `thenRn_`
226     checkDupNames doc_str rdr_names_w_loc
227   where
228     quals = filter (isQual.fst) rdr_names_w_loc
229     
230 checkDupNames doc_str rdr_names_w_loc
231   =     -- Check for dupicated names in a binding group
232     mapRn (dupNamesErr doc_str) dups    `thenRn_`
233     returnRn ()
234   where
235     (_, dups) = removeDups (\(n1,l1) (n2,l2) -> n1 `cmp` n2) rdr_names_w_loc
236 \end{code}
237
238
239 %*********************************************************
240 %*                                                      *
241 \subsection{Looking up names}
242 %*                                                      *
243 %*********************************************************
244
245 Looking up a name in the RnEnv.
246
247 \begin{code}
248 lookupRn :: NameEnv -> RdrName -> RnMS s Name
249 lookupRn name_env rdr_name
250   = case lookupFM name_env rdr_name of
251
252         -- Found it!
253         Just name -> returnRn name
254
255         -- Not found
256         Nothing -> getModeRn    `thenRn` \ mode ->
257                    case mode of 
258                         -- Not found when processing source code; so fail
259                         SourceMode    -> failWithRn (mkUnboundName rdr_name)
260                                                     (unknownNameErr rdr_name)
261                 
262                         -- Not found when processing an imported declaration,
263                         -- so we create a new name for the purpose
264                         InterfaceMode _ -> 
265                             case rdr_name of
266
267                                 Qual mod_name occ -> newGlobalName mod_name occ
268
269                                 -- An Unqual is allowed; interface files contain 
270                                 -- unqualified names for locally-defined things, such as
271                                 -- constructors of a data type.
272                                 Unqual occ -> getModuleRn       `thenRn ` \ mod_name ->
273                                               newGlobalName mod_name occ
274
275
276 lookupBndrRn rdr_name
277   = getNameEnv                  `thenRn` \ name_env ->
278     lookupRn name_env rdr_name
279
280 -- Just like lookupRn except that we record the occurrence too
281 -- Perhaps surprisingly, even wired-in names are recorded.
282 -- Why?  So that we know which wired-in names are referred to when
283 -- deciding which instance declarations to import.
284 lookupOccRn :: RdrName -> RnMS s Name
285 lookupOccRn rdr_name
286   = getNameEnv                  `thenRn` \ name_env ->
287     lookupRn name_env rdr_name  `thenRn` \ name ->
288     addOccurrenceName name
289
290 -- lookupGlobalOccRn is like lookupOccRn, except that it looks in the global 
291 -- environment.  It's used for record field names only.
292 lookupGlobalOccRn :: RdrName -> RnMS s Name
293 lookupGlobalOccRn rdr_name
294   = getGlobalNameEnv            `thenRn` \ name_env ->
295     lookupRn name_env rdr_name  `thenRn` \ name ->
296     addOccurrenceName name
297
298    
299
300 -- lookupImplicitOccRn takes an RdrName representing an *original* name, and
301 -- adds it to the occurrence pool so that it'll be loaded later.  This is
302 -- used when language constructs (such as monad comprehensions, overloaded literals,
303 -- or deriving clauses) require some stuff to be loaded that isn't explicitly
304 -- mentioned in the code.
305 --
306 -- This doesn't apply in interface mode, where everything is explicit, but
307 -- we don't check for this case: it does no harm to record an "extra" occurrence
308 -- and lookupImplicitOccRn isn't used much in interface mode (it's only the
309 -- Nothing clause of rnDerivs that calls it at all I think).
310 --
311 -- For List and Tuple types it's important to get the correct
312 -- isLocallyDefined flag, which is used in turn when deciding
313 -- whether there are any instance decls in this module are "special".
314 -- The name cache should have the correct provenance, though.
315
316 lookupImplicitOccRn :: RdrName -> RnMS s Name 
317 lookupImplicitOccRn (Qual mod occ)
318  = newGlobalName mod occ                `thenRn` \ name ->
319    addOccurrenceName name
320
321 addImplicitOccRn :: Name -> RnMS s Name
322 addImplicitOccRn name = addOccurrenceName name
323
324 addImplicitOccsRn :: [Name] -> RnMS s ()
325 addImplicitOccsRn names = addOccurrenceNames names
326
327 listType_RDR    = qual (modAndOcc listType_name)
328 tupleType_RDR n = qual (modAndOcc (tupleType_name n))
329
330 charType_name    = getName charTyCon
331 listType_name    = getName listTyCon
332 tupleType_name n = getName (tupleTyCon n)
333 \end{code}
334
335 \begin{code}
336 lookupFixity :: RdrName -> RnMS s Fixity
337 lookupFixity rdr_name
338   = getFixityEnv        `thenRn` \ fixity_env ->
339     returnRn (lookupFixityEnv fixity_env rdr_name)
340 \end{code}
341
342
343
344 %************************************************************************
345 %*                                                                      *
346 \subsection{Envt utility functions}
347 %*                                                                      *
348 %************************************************************************
349
350 ===============  RnEnv  ================
351 \begin{code}
352 plusRnEnv (RnEnv n1 f1) (RnEnv n2 f2) 
353   = plusNameEnvRn n1 n2         `thenRn` \ n ->
354     plusFixityEnvRn f1 f2       `thenRn` \ f -> 
355     returnRn (RnEnv n f)
356 \end{code}
357
358 ===============  NameEnv  ================
359 \begin{code}
360 plusNameEnvRn :: NameEnv -> NameEnv -> RnM s d NameEnv
361 plusNameEnvRn n1 n2
362   = mapRn (addErrRn.nameClashErr) (conflictsFM (/=) n1 n2)              `thenRn_`
363     returnRn (n1 `plusFM` n2)
364
365 addOneToNameEnv :: NameEnv -> RdrName -> Name -> RnM s d NameEnv
366 addOneToNameEnv env rdr_name name
367  = case lookupFM env rdr_name of
368         Nothing    -> returnRn (addToFM env rdr_name name)
369         Just name2 -> addErrRn (nameClashErr (rdr_name, (name, name2))) `thenRn_`
370                       returnRn env
371
372 lookupNameEnv :: NameEnv -> RdrName -> Maybe Name
373 lookupNameEnv = lookupFM
374
375 delOneFromNameEnv :: NameEnv -> RdrName -> NameEnv 
376 delOneFromNameEnv env rdr_name = delFromFM env rdr_name
377 \end{code}
378
379 ===============  FixityEnv  ================
380 \begin{code}
381 plusFixityEnvRn f1 f2
382   = mapRn (addErrRn.fixityClashErr) (conflictsFM bad_fix f1 f2)         `thenRn_`
383     returnRn (f1 `plusFM` f2)
384
385 addOneToFixityEnv env rdr_name fixity = addToFM env rdr_name fixity
386
387 lookupFixityEnv env rdr_name 
388   = case lookupFM env rdr_name of
389         Just (fixity,_) -> fixity
390         Nothing         -> Fixity 9 InfixL              -- Default case
391
392 bad_fix :: (Fixity, Provenance) -> (Fixity, Provenance) -> Bool
393 bad_fix (f1,_) (f2,_) = f1 /= f2
394
395 pprFixityProvenance :: PprStyle -> (Fixity,Provenance) -> Doc
396 pprFixityProvenance sty (fixity, prov) = pprProvenance sty prov
397 \end{code}
398
399
400
401 ===============  Avails  ================
402 \begin{code}
403 emptyModuleAvails :: ModuleAvails
404 plusModuleAvails ::  ModuleAvails ->  ModuleAvails ->  ModuleAvails
405 lookupModuleAvails :: ModuleAvails -> Module -> Maybe [AvailInfo]
406
407 emptyModuleAvails = emptyFM
408 plusModuleAvails  = plusFM_C (++)
409 lookupModuleAvails = lookupFM
410 \end{code}
411
412
413 ===============  AvailInfo  ================
414 \begin{code}
415 plusAvail (Avail n1)       (Avail n2)       = Avail n1
416 plusAvail (AvailTC n1 ns1) (AvailTC n2 ns2) = AvailTC n1 (nub (ns1 ++ ns2))
417 plusAvail a NotAvailable = a
418 plusAvail NotAvailable a = a
419 -- Added SOF 4/97
420 #ifdef DEBUG
421 plusAvail a1 a2 = panic ("RnEnv.plusAvail " ++ (show (hsep [pprAvail PprDebug a1,pprAvail PprDebug a2])))
422 #endif
423
424 addAvailToNameSet :: NameSet -> AvailInfo -> NameSet
425 addAvailToNameSet names avail = addListToNameSet names (availNames avail)
426
427 availsToNameSet :: [AvailInfo] -> NameSet
428 availsToNameSet avails = foldl addAvailToNameSet emptyNameSet avails
429
430 availName :: AvailInfo -> Name
431 availName (Avail n)     = n
432 availName (AvailTC n _) = n
433
434 availNames :: AvailInfo -> [Name]
435 availNames NotAvailable   = []
436 availNames (Avail n)      = [n]
437 availNames (AvailTC n ns) = ns
438
439 -- availEntityNames is used to extract the names that can appear on their own in
440 -- an export or import list.  For class decls, class methods can appear on their
441 -- own, thus    import A( op )
442 -- but constructors cannot; thus
443 --              import B( T )
444 -- means import type T from B, not constructor T.
445
446 availEntityNames :: AvailInfo -> [Name]
447 availEntityNames NotAvailable   = []
448 availEntityNames (Avail n)      = [n]
449 availEntityNames (AvailTC n ns) = n : filter (isVarOcc . nameOccName) ns
450
451 filterAvail :: RdrNameIE        -- Wanted
452             -> AvailInfo        -- Available
453             -> AvailInfo        -- Resulting available; 
454                                 -- NotAvailable if wanted stuff isn't there
455
456 filterAvail ie@(IEThingWith want wants) avail@(AvailTC n ns)
457   | sub_names_ok = AvailTC n (filter is_wanted ns)
458   | otherwise    = pprTrace "filterAvail" (hsep [ppr PprDebug ie, pprAvail PprDebug avail]) $
459                    NotAvailable
460   where
461     is_wanted name = nameOccName name `elem` wanted_occs
462     sub_names_ok   = all (`elem` avail_occs) wanted_occs
463     avail_occs     = map nameOccName ns
464     wanted_occs    = map rdrNameOcc (want:wants)
465
466 filterAvail (IEThingAbs _) (AvailTC n ns)      
467   | n `elem` ns = AvailTC n [n]
468
469 filterAvail (IEThingAbs _) avail@(Avail n)      = avail         -- Type synonyms
470
471 filterAvail (IEVar _)      avail@(Avail n)      = avail
472 filterAvail (IEVar v)      avail@(AvailTC n ns) = AvailTC n (filter wanted ns)
473                                                 where
474                                                   wanted n = nameOccName n == occ
475                                                   occ      = rdrNameOcc v
476         -- The second equation happens if we import a class op, thus
477         --      import A( op ) 
478         -- where op is a class operation
479
480 filterAvail (IEThingAll _) avail@(AvailTC _ _)  = avail
481
482 filterAvail ie avail = NotAvailable 
483
484
485 -- In interfaces, pprAvail gets given the OccName of the "host" thing
486 pprAvail PprInterface avail = ppr_avail (pprOccName PprInterface . nameOccName) avail
487 pprAvail sty          avail = ppr_avail (ppr sty) avail
488
489 ppr_avail pp_name NotAvailable = ptext SLIT("NotAvailable")
490 ppr_avail pp_name (AvailTC n ns) = hsep [
491                                      pp_name n,
492                                      parens  $ hsep $ punctuate comma $
493                                      map pp_name ns
494                                    ]
495 ppr_avail pp_name (Avail n) = pp_name n
496 \end{code}
497
498
499
500
501 %************************************************************************
502 %*                                                                      *
503 \subsection{Finite map utilities}
504 %*                                                                      *
505 %************************************************************************
506
507
508 Generally useful function on finite maps to check for overlap.
509
510 \begin{code}
511 conflictsFM :: Ord a 
512             => (b->b->Bool)             -- False <=> no conflict; you can pick either
513             -> FiniteMap a b -> FiniteMap a b
514             -> [(a,(b,b))]
515 conflictsFM bad fm1 fm2 
516   = filter (\(a,(b1,b2)) -> bad b1 b2)
517            (fmToList (intersectFM_C (\b1 b2 -> (b1,b2)) fm1 fm2))
518
519 conflictFM :: Ord a 
520            => (b->b->Bool)
521            -> FiniteMap a b -> a -> b
522            -> [(a,(b,b))]
523 conflictFM bad fm key elt
524   = case lookupFM fm key of
525         Just elt' | bad elt elt' -> [(key,(elt,elt'))]
526         other                    -> []
527 \end{code}
528
529
530 %************************************************************************
531 %*                                                                      *
532 \subsection{Envt utility functions}
533 %*                                                                      *
534 %************************************************************************
535
536
537 \begin{code}
538 nameClashErr (rdr_name, (name1,name2)) sty
539   = hang (hsep [ptext SLIT("Conflicting definitions for:"), ppr sty rdr_name])
540         4 (vcat [pprNameProvenance sty name1,
541                  pprNameProvenance sty name2])
542
543 fixityClashErr (rdr_name, (fp1,fp2)) sty
544   = hang (hsep [ptext SLIT("Conflicting fixities for:"), ppr sty rdr_name])
545         4 (vcat [pprFixityProvenance sty fp1,
546                  pprFixityProvenance sty fp2])
547
548 shadowedNameWarn shadow sty
549   = hcat [ptext SLIT("This binding for"), 
550                ppr sty shadow,
551                ptext SLIT("shadows an existing binding")]
552
553 unknownNameErr name sty
554   = sep [text flavour, ptext SLIT("not in scope:"), ppr sty name]
555   where
556     flavour = occNameFlavour (rdrNameOcc name)
557
558 qualNameErr descriptor (name,loc)
559   = pushSrcLocRn loc $
560     addErrRn (\sty -> hsep [ ptext SLIT("Invalid use of qualified name"), 
561                              ppr sty name,
562                              ptext SLIT("in"),
563                              descriptor sty])
564
565 dupNamesErr descriptor ((name,loc) : dup_things)
566   = pushSrcLocRn loc $
567     addErrRn (\sty -> hsep [ptext SLIT("Conflicting definitions for"), 
568                             ppr sty name, 
569                             ptext SLIT("in"), descriptor sty])
570 \end{code}
571