[project @ 2005-04-16 22:47:23 by simonpj]
[ghc-hetmet.git] / ghc / compiler / iface / IfaceEnv.lhs
1 (c) The University of Glasgow 2002
2
3 \begin{code}
4 module IfaceEnv (
5         newGlobalBinder, newIPName, newImplicitBinder, 
6         lookupIfaceTop, lookupIfaceExt,
7         lookupOrig, lookupIfaceTc,
8         newIfaceName, newIfaceNames,
9         extendIfaceIdEnv, extendIfaceTyVarEnv,
10         tcIfaceLclId,     tcIfaceTyVar, 
11
12         lookupAvail, ifaceExportNames,
13
14         -- Name-cache stuff
15         allocateGlobalBinder, initNameCache, 
16    ) where
17
18 #include "HsVersions.h"
19
20 import TcRnMonad
21 import IfaceType        ( IfaceExtName(..), IfaceTyCon(..), ifaceTyConName )
22 import TysWiredIn       ( tupleTyCon, tupleCon )
23 import HscTypes         ( NameCache(..), HscEnv(..), GenAvailInfo(..), 
24                           IfaceExport, OrigNameCache )
25 import TyCon            ( TyCon, tyConName )
26 import DataCon          ( dataConWorkId, dataConName )
27 import Var              ( TyVar, Id, varName )
28 import Name             ( Name, nameUnique, nameModule, 
29                           nameOccName, nameSrcLoc, 
30                           getOccName, nameParent_maybe,
31                           isWiredInName, mkIPName,
32                           mkExternalName, mkInternalName )
33 import NameSet          ( NameSet, emptyNameSet, addListToNameSet )
34 import OccName          ( OccName, isTupleOcc_maybe, tcName, dataName,
35                           lookupOccEnv, unitOccEnv, extendOccEnv, extendOccEnvList )
36 import PrelNames        ( gHC_PRIM, pREL_TUP )
37 import Module           ( Module, emptyModuleEnv, 
38                           lookupModuleEnv, extendModuleEnv_C )
39 import UniqSupply       ( UniqSupply, splitUniqSupply, uniqFromSupply, uniqsFromSupply )
40 import FiniteMap        ( emptyFM, lookupFM, addToFM )
41 import BasicTypes       ( IPName(..), mapIPName )
42 import SrcLoc           ( SrcLoc, noSrcLoc )
43 import Maybes           ( orElse )
44
45 import Outputable
46 \end{code}
47
48
49 %*********************************************************
50 %*                                                      *
51         Allocating new Names in the Name Cache
52 %*                                                      *
53 %*********************************************************
54
55 \begin{code}
56 newGlobalBinder :: Module -> OccName -> Maybe Name -> SrcLoc -> TcRnIf a b Name
57 -- Used for source code and interface files, to make the
58 -- Name for a thing, given its Module and OccName
59 --
60 -- The cache may already already have a binding for this thing,
61 -- because we may have seen an occurrence before, but now is the
62 -- moment when we know its Module and SrcLoc in their full glory
63
64 newGlobalBinder mod occ mb_parent loc
65   = do  { mod `seq` occ `seq` return () -- See notes with lookupOrig_help
66         ; traceIf (text "newGlobalBinder" <+> ppr mod <+> ppr occ <+> ppr loc)
67         ; name_supply <- getNameCache
68         ; let (name_supply', name) = allocateGlobalBinder 
69                                         name_supply mod occ
70                                         mb_parent loc
71         ; setNameCache name_supply'
72         ; return name }
73
74 allocateGlobalBinder
75   :: NameCache 
76   -> Module -> OccName -> Maybe Name -> SrcLoc 
77   -> (NameCache, Name)
78 allocateGlobalBinder name_supply mod occ mb_parent loc
79   = case lookupOrigNameCache (nsNames name_supply) mod occ of
80         -- A hit in the cache!  We are at the binding site of the name.
81         -- This is the moment when we know the defining parent and SrcLoc
82         -- of the Name, so we set these fields in the Name we return.
83         --
84         -- Then (bogus) multiple bindings of the same Name
85         -- get different SrcLocs can can be reported as such.
86         --
87         -- Possible other reason: it might be in the cache because we
88         --      encountered an occurrence before the binding site for an
89         --      implicitly-imported Name.  Perhaps the current SrcLoc is
90         --      better... but not really: it'll still just say 'imported'
91         --
92         -- IMPORTANT: Don't mess with wired-in names.  
93         --            Their wired-in-ness is in their NameSort
94         --            and their Module is correct.
95
96         Just name | isWiredInName name -> (name_supply, name)
97                   | otherwise -> (new_name_supply, name')
98                   where
99                     uniq      = nameUnique name
100                     name'     = mkExternalName uniq mod occ mb_parent loc
101                     new_cache = extend_name_cache (nsNames name_supply) mod occ name'
102                     new_name_supply = name_supply {nsNames = new_cache}              
103
104         -- Miss in the cache!
105         -- Build a completely new Name, and put it in the cache
106         Nothing -> (new_name_supply, name)
107                 where
108                   (us', us1)      = splitUniqSupply (nsUniqs name_supply)
109                   uniq            = uniqFromSupply us1
110                   name            = mkExternalName uniq mod occ mb_parent loc
111                   new_cache       = extend_name_cache (nsNames name_supply) mod occ name
112                   new_name_supply = name_supply {nsUniqs = us', nsNames = new_cache}
113
114
115 newImplicitBinder :: Name                       -- Base name
116                   -> (OccName -> OccName)       -- Occurrence name modifier
117                   -> TcRnIf m n Name            -- Implicit name
118 -- Called in BuildTyCl to allocate the implicit binders of type/class decls
119 -- For source type/class decls, this is the first occurrence
120 -- For iface ones, the LoadIface has alrady allocated a suitable name in the cache
121 --
122 -- An *implicit* name has the base-name as parent
123 newImplicitBinder base_name mk_sys_occ
124   = newGlobalBinder (nameModule base_name)
125                     (mk_sys_occ (nameOccName base_name))
126                     (Just parent_name)
127                     (nameSrcLoc base_name)    
128   where
129     parent_name = case nameParent_maybe base_name of
130                     Just parent_name  -> parent_name
131                     Nothing           -> base_name
132
133 ifaceExportNames :: [IfaceExport] -> TcRnIf gbl lcl NameSet
134 ifaceExportNames exports 
135   = foldlM do_one emptyNameSet exports
136   where
137     do_one acc (mod, exports)  = foldlM (do_avail mod) acc exports
138     do_avail mod acc avail = do { ns <- lookupAvail mod avail
139                                 ; return (addListToNameSet acc ns) }
140
141 lookupAvail :: Module -> GenAvailInfo OccName -> TcRnIf a b [Name]
142 -- Find all the names arising from an import
143 -- Make sure the parent info is correct, even though we may not
144 -- yet have read the interface for this module
145 lookupAvail mod (Avail n) = do { n' <- lookupOrig mod n; 
146                                ; return [n'] }
147 lookupAvail mod (AvailTC p_occ occs) 
148   = do { p_name <- lookupOrig mod p_occ
149        ; let lookup_sub occ | occ == p_occ = return p_name
150                             | otherwise    = lookup_orig mod occ (Just p_name)
151        ; mappM lookup_sub occs }
152         -- Remember that 'occs' is all the exported things, including
153         -- the parent.  It's possible to export just class ops without
154         -- the class, via C( op ). If the class was exported too we'd
155         -- have C( C, op )
156
157         -- The use of lookupOrigSub here (rather than lookupOrig) 
158         -- ensures that the subordinate names record their parent; 
159         -- and that in turn ensures that the GlobalRdrEnv
160         -- has the correct parent for all the names in its range.
161         -- For imported things, we may only suck in the interface later, if ever.
162         -- Reason for all this:
163         --   Suppose module M exports type A.T, and constructor A.MkT
164         --   Then, we know that A.MkT is a subordinate name of A.T,
165         --   even though we aren't at the binding site of A.T
166         --   And it's important, because we may simply re-export A.T
167         --   without ever sucking in the declaration itself.
168
169
170 lookupOrig :: Module -> OccName -> TcRnIf a b Name
171 -- Even if we get a miss in the original-name cache, we 
172 -- make a new External Name. 
173 -- We fake up 
174 --      SrcLoc to noSrcLoc
175 --      Parent no Nothing
176 -- They'll be overwritten, in due course, by LoadIface.loadDecl.
177 lookupOrig mod occ = lookup_orig mod occ Nothing
178
179 lookup_orig :: Module -> OccName ->  Maybe Name -> TcRnIf a b Name
180 -- Used when we know the parent of the thing we are looking up
181 lookup_orig mod occ mb_parent
182   = do  {       -- First ensure that mod and occ are evaluated
183                 -- If not, chaos can ensue:
184                 --      we read the name-cache
185                 --      then pull on mod (say)
186                 --      which does some stuff that modifies the name cache
187                 -- This did happen, with tycon_mod in TcIface.tcIfaceAlt (DataAlt..)
188           mod `seq` occ `seq` return () 
189     
190         ; name_supply <- getNameCache
191         ; case lookupOrigNameCache (nsNames name_supply) mod occ of {
192               Just name -> returnM name ;
193               Nothing   -> do 
194
195         { let { (us', us1)      = splitUniqSupply (nsUniqs name_supply)
196               ; uniq            = uniqFromSupply us1
197               ; name            = mkExternalName uniq mod occ mb_parent noSrcLoc
198               ; new_cache       = extend_name_cache (nsNames name_supply) mod occ name
199               ; new_name_supply = name_supply {nsUniqs = us', nsNames = new_cache}
200           }
201         ; setNameCache new_name_supply
202         ; return name }
203     }}
204
205 newIPName :: IPName OccName -> TcRnIf m n (IPName Name)
206 newIPName occ_name_ip
207   = getNameCache                `thenM` \ name_supply ->
208     let
209         ipcache = nsIPs name_supply
210     in
211     case lookupFM ipcache key of
212         Just name_ip -> returnM name_ip
213         Nothing      -> setNameCache new_ns     `thenM_`
214                         returnM name_ip
215                   where
216                      (us', us1)  = splitUniqSupply (nsUniqs name_supply)
217                      uniq        = uniqFromSupply us1
218                      name_ip     = mapIPName (mkIPName uniq) occ_name_ip
219                      new_ipcache = addToFM ipcache key name_ip
220                      new_ns      = name_supply {nsUniqs = us', nsIPs = new_ipcache}
221     where 
222         key = occ_name_ip       -- Ensures that ?x and %x get distinct Names
223 \end{code}
224
225         Local helper functions (not exported)
226
227 \begin{code}
228 lookupOrigNameCache :: OrigNameCache -> Module -> OccName -> Maybe Name
229 lookupOrigNameCache nc mod occ
230   | mod == pREL_TUP || mod == gHC_PRIM,         -- Boxed tuples from one, 
231     Just tup_info <- isTupleOcc_maybe occ       -- unboxed from the other
232   =     -- Special case for tuples; there are too many
233         -- of them to pre-populate the original-name cache
234     Just (mk_tup_name tup_info)
235   where
236     mk_tup_name (ns, boxity, arity)
237         | ns == tcName   = tyConName (tupleTyCon boxity arity)
238         | ns == dataName = dataConName (tupleCon boxity arity)
239         | otherwise      = varName (dataConWorkId (tupleCon boxity arity))
240
241 lookupOrigNameCache nc mod occ  -- The normal case
242   = case lookupModuleEnv nc mod of
243         Nothing      -> Nothing
244         Just occ_env -> lookupOccEnv occ_env occ
245
246 extendOrigNameCache :: OrigNameCache -> Name -> OrigNameCache
247 extendOrigNameCache nc name 
248   = extend_name_cache nc (nameModule name) (nameOccName name) name
249
250 extend_name_cache :: OrigNameCache -> Module -> OccName -> Name -> OrigNameCache
251 extend_name_cache nc mod occ name
252   = extendModuleEnv_C combine nc mod (unitOccEnv occ name)
253   where
254     combine occ_env _ = extendOccEnv occ_env occ name
255
256 getNameCache :: TcRnIf a b NameCache
257 getNameCache = do { HscEnv { hsc_NC = nc_var } <- getTopEnv; 
258                     readMutVar nc_var }
259
260 setNameCache :: NameCache -> TcRnIf a b ()
261 setNameCache nc = do { HscEnv { hsc_NC = nc_var } <- getTopEnv; 
262                        writeMutVar nc_var nc }
263 \end{code}
264
265
266 \begin{code}
267 initNameCache :: UniqSupply -> [Name] -> NameCache
268 initNameCache us names
269   = NameCache { nsUniqs = us,
270                 nsNames = initOrigNames names,
271                 nsIPs   = emptyFM }
272
273 initOrigNames :: [Name] -> OrigNameCache
274 initOrigNames names = foldl extendOrigNameCache emptyModuleEnv names
275 \end{code}
276
277
278
279 %************************************************************************
280 %*                                                                      *
281                 Type variables and local Ids
282 %*                                                                      *
283 %************************************************************************
284
285 \begin{code}
286 tcIfaceLclId :: OccName -> IfL Id
287 tcIfaceLclId occ
288   = do  { lcl <- getLclEnv
289         ; return (lookupOccEnv (if_id_env lcl) occ
290                   `orElse` 
291                   pprPanic "tcIfaceLclId" (ppr occ)) }
292
293 extendIfaceIdEnv :: [Id] -> IfL a -> IfL a
294 extendIfaceIdEnv ids thing_inside
295   = do  { env <- getLclEnv
296         ; let { id_env' = extendOccEnvList (if_id_env env) pairs
297               ; pairs   = [(getOccName id, id) | id <- ids] }
298         ; setLclEnv (env { if_id_env = id_env' }) thing_inside }
299
300
301 tcIfaceTyVar :: OccName -> IfL TyVar
302 tcIfaceTyVar occ
303   = do  { lcl <- getLclEnv
304         ; return (lookupOccEnv (if_tv_env lcl) occ
305                   `orElse`
306                   pprPanic "tcIfaceTyVar" (ppr occ)) }
307
308 extendIfaceTyVarEnv :: [TyVar] -> IfL a -> IfL a
309 extendIfaceTyVarEnv tyvars thing_inside
310   = do  { env <- getLclEnv
311         ; let { tv_env' = extendOccEnvList (if_tv_env env) pairs
312               ; pairs   = [(getOccName tv, tv) | tv <- tyvars] }
313         ; setLclEnv (env { if_tv_env = tv_env' }) thing_inside }
314 \end{code}
315
316
317 %************************************************************************
318 %*                                                                      *
319                 Getting from RdrNames to Names
320 %*                                                                      *
321 %************************************************************************
322
323 \begin{code}
324 lookupIfaceTc :: IfaceTyCon -> IfL Name
325 lookupIfaceTc (IfaceTc ext) = lookupIfaceExt ext
326 lookupIfaceTc other_tc      = return (ifaceTyConName other_tc)
327
328 lookupIfaceExt :: IfaceExtName -> IfL Name
329 lookupIfaceExt (ExtPkg  mod occ)   = lookupOrig mod occ
330 lookupIfaceExt (HomePkg mod occ _) = lookupOrig mod occ
331 lookupIfaceExt (LocalTop occ)      = lookupIfaceTop occ
332 lookupIfaceExt (LocalTopSub occ _) = lookupIfaceTop occ
333
334 lookupIfaceTop :: OccName -> IfL Name
335 -- Look up a top-level name from the current Iface module
336 lookupIfaceTop occ
337   = do  { env <- getLclEnv; lookupOrig (if_mod env) occ }
338
339 newIfaceName :: OccName -> IfL Name
340 newIfaceName occ
341   = do  { uniq <- newUnique
342         ; return (mkInternalName uniq occ noSrcLoc) }
343
344 newIfaceNames :: [OccName] -> IfL [Name]
345 newIfaceNames occs
346   = do  { uniqs <- newUniqueSupply
347         ; return [ mkInternalName uniq occ noSrcLoc
348                  | (occ,uniq) <- occs `zip` uniqsFromSupply uniqs] }
349 \end{code}