[project @ 2003-12-30 16:29:17 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         tcIfaceGlobal, tcIfaceTyCon, tcIfaceClass, tcIfaceExtId,
11         tcIfaceTyVar, tcIfaceDataCon, tcIfaceLclId,
12
13         -- Name-cache stuff
14         allocateGlobalBinder, initNameCache
15    ) where
16
17 #include "HsVersions.h"
18
19 import {-# SOURCE #-}   TcIface( tcImportDecl )
20
21 import TcRnMonad
22 import IfaceType        ( IfaceExtName(..), IfaceTyCon(..), ifaceTyConName )
23 import HscTypes         ( NameCache(..), HscEnv(..), 
24                           TyThing, tyThingClass, tyThingTyCon, 
25                           ExternalPackageState(..), OrigNameCache, lookupType )
26 import TyCon            ( TyCon, tyConName )
27 import Class            ( Class )
28 import DataCon          ( DataCon, dataConWorkId, dataConName )
29 import Var              ( TyVar, Id, varName )
30 import Name             ( Name, nameUnique, nameModule, 
31                           nameOccName, nameSrcLoc,
32                           getOccName, nameParent_maybe,
33                           isWiredInName, nameIsLocalOrFrom, mkIPName,
34                           mkExternalName, mkInternalName )
35 import NameEnv
36 import OccName          ( OccName, isTupleOcc_maybe, tcName, dataName,
37                           lookupOccEnv, unitOccEnv, extendOccEnv, extendOccEnvList )
38 import PrelNames        ( gHC_PRIM_Name, pREL_TUP_Name )
39 import TysWiredIn       ( intTyCon, boolTyCon, charTyCon, listTyCon, parrTyCon, 
40                           tupleTyCon, tupleCon )
41 import HscTypes         ( ExternalPackageState, NameCache, TyThing(..) )
42 import Module           ( Module, ModuleName, moduleName, mkPackageModule, 
43                           emptyModuleEnv, lookupModuleEnvByName, extendModuleEnv_C )
44 import UniqSupply       ( UniqSupply, splitUniqSupply, uniqFromSupply, uniqsFromSupply )
45 import FiniteMap        ( emptyFM, lookupFM, addToFM )
46 import BasicTypes       ( IPName(..), mapIPName )
47 import SrcLoc           ( SrcLoc, noSrcLoc )
48 import Maybes           ( orElse )
49
50 import Outputable
51 \end{code}
52
53
54 %*********************************************************
55 %*                                                      *
56         Allocating new Names in the Name Cache
57 %*                                                      *
58 %*********************************************************
59
60 \begin{code}
61 newGlobalBinder :: Module -> OccName -> Maybe Name -> SrcLoc -> TcRnIf a b Name
62 -- Used for source code and interface files, to make the
63 -- Name for a thing, given its Module and OccName
64 --
65 -- The cache may already already have a binding for this thing,
66 -- because we may have seen an occurrence before, but now is the
67 -- moment when we know its Module and SrcLoc in their full glory
68
69 newGlobalBinder mod occ mb_parent loc
70   = do  { mod `seq` occ `seq` return () -- See notes with lookupOrig_help
71         ; name_supply <- getNameCache
72         ; let (name_supply', name) = allocateGlobalBinder 
73                                         name_supply mod occ
74                                         mb_parent loc
75         ; setNameCache name_supply'
76         ; return name }
77
78 allocateGlobalBinder
79   :: NameCache 
80   -> Module -> OccName -> Maybe Name -> SrcLoc 
81   -> (NameCache, Name)
82 allocateGlobalBinder name_supply mod occ mb_parent loc
83   = case lookupOrigNameCache (nsNames name_supply) (moduleName mod) occ of
84         -- A hit in the cache!  We are at the binding site of the name.
85         -- This is the moment when we know the defining Module and SrcLoc
86         -- of the Name, so we set these fields in the Name we return.
87         --
88         -- This is essential, to get the right Module in a Name.
89         -- Also: then (bogus) multiple bindings of the same Name
90         --              get different SrcLocs can can be reported as such.
91         --
92         -- Possible other reason: it might be in the cache because we
93         --      encountered an occurrence before the binding site for an
94         --      implicitly-imported Name.  Perhaps the current SrcLoc is
95         --      better... but not really: it'll still just say 'imported'
96         --
97         -- IMPORTANT: Don't mess with wired-in names.  
98         --            Their wired-in-ness is in their NameSort
99         --            and their Module is correct.
100
101         Just name | isWiredInName name -> (name_supply, name)
102                   | otherwise -> (new_name_supply, name')
103                   where
104                     uniq      = nameUnique name
105                     name'     = mkExternalName uniq mod occ mb_parent loc
106                     new_cache = extend_name_cache (nsNames name_supply) mod occ name'
107                     new_name_supply = name_supply {nsNames = new_cache}              
108
109         -- Miss in the cache!
110         -- Build a completely new Name, and put it in the cache
111         Nothing -> (new_name_supply, name)
112                 where
113                   (us', us1)      = splitUniqSupply (nsUniqs name_supply)
114                   uniq            = uniqFromSupply us1
115                   name            = mkExternalName uniq mod occ mb_parent loc
116                   new_cache       = extend_name_cache (nsNames name_supply) mod occ name
117                   new_name_supply = name_supply {nsUniqs = us', nsNames = new_cache}
118
119
120 newImplicitBinder :: Name                       -- Base name
121                   -> (OccName -> OccName)       -- Occurrence name modifier
122                   -> TcRnIf m n Name            -- Implicit name
123 -- Called in BuildTyCl to allocate the implicit binders of type/class decls
124 -- For source type/class decls, this is the first occurrence
125 -- For iface ones, the LoadIface has alrady allocated a suitable name in the cache
126 --
127 -- An *implicit* name has the base-name as parent
128 newImplicitBinder base_name mk_sys_occ
129   = newGlobalBinder (nameModule base_name)
130                     (mk_sys_occ (nameOccName base_name))
131                     (Just parent_name)
132                     (nameSrcLoc base_name)    
133   where
134     parent_name = case nameParent_maybe base_name of
135                     Just parent_name  -> parent_name
136                     Nothing           -> base_name
137
138 lookupOrig :: ModuleName -> OccName -> TcRnIf a b Name
139 -- This one starts with a ModuleName, not a Module, because 
140 -- we may be simply looking at an occurrence M.x in an interface file.
141 -- We may enounter this well before finding the binding site for M.x
142 --
143 -- So, even if we get a miss in the original-name cache, we 
144 -- make a new External Name. 
145 -- We fake up 
146 --      Module to AnotherPackage
147 --      SrcLoc to noSrcLoc
148 --      Parent no Nothing
149 -- They'll be overwritten, in due course, by LoadIface.loadDecl.
150
151 lookupOrig mod_name occ 
152   = do  {       -- First ensure that mod_name and occ are evaluated
153                 -- If not, chaos can ensue:
154                 --      we read the name-cache
155                 --      then pull on mod (say)
156                 --      which does some stuff that modifies the name cache
157                 -- This did happen, with tycon_mod in TcIface.tcIfaceAlt (DataAlt..)
158           mod `seq` occ `seq` return () 
159     
160         ; name_supply <- getNameCache
161         ; case lookupOrigNameCache (nsNames name_supply) mod_name occ of {
162               Just name -> returnM name ;
163               Nothing   -> do 
164
165         { let { (us', us1)      = splitUniqSupply (nsUniqs name_supply)
166               ; uniq            = uniqFromSupply us1
167               ; name            = mkExternalName uniq tmp_mod occ Nothing noSrcLoc
168               ; new_cache       = extend_name_cache (nsNames name_supply) tmp_mod occ name
169               ; new_name_supply = name_supply {nsUniqs = us', nsNames = new_cache}
170               ; tmp_mod         = mkPackageModule mod_name 
171                         -- Guess at the package-ness for now, becuase we don't know whether
172                         -- this imported module is from the home package or not.
173                         -- If we ever need it, we'll open its interface, and update the cache
174                         -- with a better name (newGlobalBinder)
175           }
176         ; setNameCache new_name_supply
177         ; return name }
178     }}
179
180 newIPName :: IPName OccName -> TcRnIf m n (IPName Name)
181 newIPName occ_name_ip
182   = getNameCache                `thenM` \ name_supply ->
183     let
184         ipcache = nsIPs name_supply
185     in
186     case lookupFM ipcache key of
187         Just name_ip -> returnM name_ip
188         Nothing      -> setNameCache new_ns     `thenM_`
189                         returnM name_ip
190                   where
191                      (us', us1)  = splitUniqSupply (nsUniqs name_supply)
192                      uniq        = uniqFromSupply us1
193                      name_ip     = mapIPName (mkIPName uniq) occ_name_ip
194                      new_ipcache = addToFM ipcache key name_ip
195                      new_ns      = name_supply {nsUniqs = us', nsIPs = new_ipcache}
196     where 
197         key = occ_name_ip       -- Ensures that ?x and %x get distinct Names
198 \end{code}
199
200         Local helper functions (not exported)
201
202 \begin{code}
203 lookupOrigNameCache :: OrigNameCache -> ModuleName -> OccName -> Maybe Name
204 lookupOrigNameCache nc mod_name occ
205   | mod_name == pREL_TUP_Name || mod_name == gHC_PRIM_Name,     -- Boxed tuples from one, 
206     Just tup_info <- isTupleOcc_maybe occ                       -- unboxed from the other
207   =     -- Special case for tuples; there are too many
208         -- of them to pre-populate the original-name cache
209     Just (mk_tup_name tup_info)
210   where
211     mk_tup_name (ns, boxity, arity)
212         | ns == tcName   = tyConName (tupleTyCon boxity arity)
213         | ns == dataName = dataConName (tupleCon boxity arity)
214         | otherwise      = varName (dataConWorkId (tupleCon boxity arity))
215
216 lookupOrigNameCache nc mod_name occ     -- The normal case
217   = case lookupModuleEnvByName nc mod_name of
218         Nothing      -> Nothing
219         Just occ_env -> lookupOccEnv occ_env occ
220
221 extendOrigNameCache :: OrigNameCache -> Name -> OrigNameCache
222 extendOrigNameCache nc name 
223   = extend_name_cache nc (nameModule name) (nameOccName name) name
224
225 extend_name_cache :: OrigNameCache -> Module -> OccName -> Name -> OrigNameCache
226 extend_name_cache nc mod occ name
227   = extendModuleEnv_C combine nc mod (unitOccEnv occ name)
228   where
229     combine occ_env _ = extendOccEnv occ_env occ name
230
231 getNameCache :: TcRnIf a b NameCache
232 getNameCache = do { HscEnv { hsc_NC = nc_var } <- getTopEnv; 
233                     readMutVar nc_var }
234
235 setNameCache :: NameCache -> TcRnIf a b ()
236 setNameCache nc = do { HscEnv { hsc_NC = nc_var } <- getTopEnv; 
237                        writeMutVar nc_var nc }
238 \end{code}
239
240
241 \begin{code}
242 initNameCache :: UniqSupply -> [Name] -> NameCache
243 initNameCache us names
244   = NameCache { nsUniqs = us,
245                 nsNames = initOrigNames names,
246                 nsIPs   = emptyFM }
247
248 initOrigNames :: [Name] -> OrigNameCache
249 initOrigNames names = foldl extendOrigNameCache emptyModuleEnv names
250 \end{code}
251
252
253 %************************************************************************
254 %*                                                                      *
255                 Getting from Names to TyThings
256 %*                                                                      *
257 %************************************************************************
258
259 \begin{code}
260 tcIfaceGlobal :: Name -> IfM a TyThing
261 tcIfaceGlobal name
262   = do  { eps <- getEps
263         ; hpt <- getHpt
264         ; case lookupType hpt (eps_PTE eps) name of {
265             Just thing -> return thing ;
266             Nothing    -> 
267
268         setLclEnv () $ do       -- This gets us back to IfG, mainly to 
269                                 -- pacify get_type_env; rather untidy
270         { env <- getGblEnv
271         ; case if_rec_types env of
272             Just (mod, get_type_env) 
273                 | nameIsLocalOrFrom mod name
274                 -> do           -- It's defined in the module being compiled
275                 { type_env <- get_type_env
276                 ; case lookupNameEnv type_env name of
277                         Just thing -> return thing
278                         Nothing    -> pprPanic "tcIfaceGlobal (local): not found:"  
279                                                 (ppr name $$ ppr type_env) }
280
281             other -> tcImportDecl name  -- It's imported; go get it
282     }}}
283
284 tcIfaceTyCon :: IfaceTyCon -> IfL TyCon
285 tcIfaceTyCon IfaceIntTc  = return intTyCon
286 tcIfaceTyCon IfaceBoolTc = return boolTyCon
287 tcIfaceTyCon IfaceCharTc = return charTyCon
288 tcIfaceTyCon IfaceListTc = return listTyCon
289 tcIfaceTyCon IfacePArrTc = return parrTyCon
290 tcIfaceTyCon (IfaceTupTc bx ar) = return (tupleTyCon bx ar)
291 tcIfaceTyCon (IfaceTc ext_nm) = do { name <- lookupIfaceExt ext_nm
292                                    ; thing <- tcIfaceGlobal name
293                                    ; return (tyThingTyCon thing) }
294
295 tcIfaceClass :: IfaceExtName -> IfL Class
296 tcIfaceClass rdr_name = do { name <- lookupIfaceExt rdr_name
297                            ; thing <- tcIfaceGlobal name
298                            ; return (tyThingClass thing) }
299
300 tcIfaceDataCon :: IfaceExtName -> IfL DataCon
301 tcIfaceDataCon gbl = do { name <- lookupIfaceExt gbl
302                         ; thing <- tcIfaceGlobal name
303                         ; case thing of
304                                 ADataCon dc -> return dc
305                                 other   -> pprPanic "tcIfaceExtDC" (ppr gbl $$ ppr name$$ ppr thing) }
306
307 tcIfaceExtId :: IfaceExtName -> IfL Id
308 tcIfaceExtId gbl = do { name <- lookupIfaceExt gbl
309                       ; thing <- tcIfaceGlobal name
310                       ; case thing of
311                           AnId id -> return id
312                           other   -> pprPanic "tcIfaceExtId" (ppr gbl $$ ppr name$$ ppr thing) }
313
314 ------------------------------------------
315 tcIfaceLclId :: OccName -> IfL Id
316 tcIfaceLclId occ
317   = do  { lcl <- getLclEnv
318         ; return (lookupOccEnv (if_id_env lcl) occ
319                   `orElse` 
320                   pprPanic "tcIfaceLclId" (ppr occ)) }
321
322 tcIfaceTyVar :: OccName -> IfL TyVar
323 tcIfaceTyVar occ
324   = do  { lcl <- getLclEnv
325         ; return (lookupOccEnv (if_tv_env lcl) occ
326                   `orElse`
327                   pprPanic "tcIfaceTyVar" (ppr occ)) }
328
329 extendIfaceIdEnv :: [Id] -> IfL a -> IfL a
330 extendIfaceIdEnv ids thing_inside
331   = do  { env <- getLclEnv
332         ; let { id_env' = extendOccEnvList (if_id_env env) pairs
333               ; pairs   = [(getOccName id, id) | id <- ids] }
334         ; setLclEnv (env { if_id_env = id_env' }) thing_inside }
335
336 extendIfaceTyVarEnv :: [TyVar] -> IfL a -> IfL a
337 extendIfaceTyVarEnv tyvars thing_inside
338   = do  { env <- getLclEnv
339         ; let { tv_env' = extendOccEnvList (if_tv_env env) pairs
340               ; pairs   = [(getOccName tv, tv) | tv <- tyvars] }
341         ; setLclEnv (env { if_tv_env = tv_env' }) thing_inside }
342 \end{code}
343
344
345 %************************************************************************
346 %*                                                                      *
347                 Getting from RdrNames to Names
348 %*                                                                      *
349 %************************************************************************
350
351 \begin{code}
352 lookupIfaceTc :: IfaceTyCon -> IfL Name
353 lookupIfaceTc (IfaceTc ext) = lookupIfaceExt ext
354 lookupIfaceTc other_tc      = return (ifaceTyConName other_tc)
355
356 lookupIfaceExt :: IfaceExtName -> IfL Name
357 lookupIfaceExt (ExtPkg  mod occ)   = lookupOrig mod occ
358 lookupIfaceExt (HomePkg mod occ _) = lookupOrig mod occ
359 lookupIfaceExt (LocalTop occ)      = lookupIfaceTop occ
360 lookupIfaceExt (LocalTopSub occ _) = lookupIfaceTop occ
361
362 lookupIfaceTop :: OccName -> IfL Name
363 -- Look up a top-level name from the current Iface module
364 lookupIfaceTop occ
365   = do  { env <- getLclEnv; lookupOrig (if_mod env) occ }
366
367 newIfaceName :: OccName -> IfL Name
368 newIfaceName occ
369   = do  { uniq <- newUnique
370         ; return (mkInternalName uniq occ noSrcLoc) }
371
372 newIfaceNames :: [OccName] -> IfL [Name]
373 newIfaceNames occs
374   = do  { uniqs <- newUniqueSupply
375         ; return [ mkInternalName uniq occ noSrcLoc
376                  | (occ,uniq) <- occs `zip` uniqsFromSupply uniqs] }
377 \end{code}