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