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