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