f38d1262c7701bdfa759cc6dab476bda066be376
[ghc-hetmet.git] / ghc / compiler / typecheck / TcEnv.lhs
1 \begin{code}
2 module TcEnv(
3         TcId, TcIdSet, 
4         TyThing(..), TyThingDetails(..), TcTyThing(..),
5
6         -- Getting stuff from the environment
7         TcEnv, initTcEnv, 
8         tcEnvTyCons, tcEnvClasses, tcEnvIds, tcEnvTcIds, tcEnvTyVars,
9         getTcGEnv,
10         
11         -- Instance environment, and InstInfo type
12         tcGetInstEnv, tcSetInstEnv, 
13         InstInfo(..), pprInstInfo,
14         simpleInstInfoTy, simpleInstInfoTyCon, 
15
16         -- Global environment
17         tcExtendGlobalEnv, tcExtendGlobalValEnv, 
18         tcLookupTyCon, tcLookupClass, tcLookupGlobalId, tcLookupDataCon,
19         tcLookupGlobal_maybe, tcLookupGlobal, 
20
21         -- Local environment
22         tcExtendKindEnv, 
23         tcExtendTyVarEnv, tcExtendTyVarEnvForMeths, 
24         tcExtendLocalValEnv, tcLookup,
25
26         -- Global type variables
27         tcGetGlobalTyVars, tcExtendGlobalTyVars,
28
29         -- Random useful things
30         RecTcEnv, tcAddImportedIdInfo, tcLookupRecId, tcLookupRecId_maybe, tcInstId,
31
32         -- New Ids
33         newLocalId, newSpecPragmaId,
34         newDFunName,
35
36         -- Misc
37         isLocalThing, tcSetEnv
38   ) where
39
40 #include "HsVersions.h"
41
42 import RnHsSyn          ( RenamedMonoBinds, RenamedSig )
43 import TcMonad
44 import TcType           ( TcKind,  TcType, TcTyVar, TcTyVarSet, TcThetaType,
45                           tcInstTyVars, zonkTcTyVars,
46                         )
47 import Id               ( idName, mkUserLocal, isDataConWrapId_maybe )
48 import IdInfo           ( constantIdInfo )
49 import MkId             ( mkSpecPragmaId )
50 import Var              ( TyVar, Id, idType, lazySetIdInfo, idInfo )
51 import VarSet
52 import Type             ( Type,
53                           tyVarsOfTypes, splitDFunTy,
54                           splitForAllTys, splitRhoTy,
55                           getDFunTyKey, tyConAppTyCon
56                         )
57 import DataCon          ( DataCon )
58 import TyCon            ( TyCon )
59 import Class            ( Class, ClassOpItem, ClassContext )
60 import Subst            ( substTy )
61 import Name             ( Name, OccName, NamedThing(..), 
62                           nameOccName, getSrcLoc, mkLocalName,
63                           isLocalName, nameModule_maybe
64                         )
65 import Name             ( NameEnv, lookupNameEnv, nameEnvElts, extendNameEnvList, emptyNameEnv )
66 import OccName          ( mkDFunOcc, occNameString )
67 import HscTypes         ( DFunId, TypeEnv, HomeSymbolTable, PackageTypeEnv )
68 import Module           ( Module )
69 import InstEnv          ( InstEnv, emptyInstEnv )
70 import HscTypes         ( lookupType, TyThing(..) )
71 import Util             ( zipEqual )
72 import SrcLoc           ( SrcLoc )
73 import Outputable
74
75 import IOExts           ( newIORef )
76 \end{code}
77
78 %************************************************************************
79 %*                                                                      *
80 \subsection{TcEnv}
81 %*                                                                      *
82 %************************************************************************
83
84 \begin{code}
85 type TcId    = Id                       -- Type may be a TcType
86 type TcIdSet = IdSet
87
88 data TcEnv
89   = TcEnv {
90         tcGST    :: Name -> Maybe TyThing,      -- The type environment at the moment we began this compilation
91
92         tcInsts  :: InstEnv,            -- All instances (both imported and in this module)
93
94         tcGEnv   :: TypeEnv,            -- The global type environment we've accumulated while
95                  {- NameEnv TyThing-}   -- compiling this module:
96                                         --      types and classes (both imported and local)
97                                         --      imported Ids
98                                         -- (Ids defined in this module are in the local envt)
99
100         tcLEnv   :: NameEnv TcTyThing,  -- The local type environment: Ids and TyVars
101                                         -- defined in this module
102
103         tcTyVars :: TcRef TcTyVarSet    -- The "global tyvars"
104                                         -- Namely, the in-scope TyVars bound in tcLEnv, plus the tyvars
105                                         -- mentioned in the types of Ids bound in tcLEnv
106                                         -- Why mutable? see notes with tcGetGlobalTyVars
107     }
108
109 \end{code}
110
111 The Global-Env/Local-Env story
112 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
113 During type checking, we keep in the GlobalEnv
114         * All types and classes
115         * All Ids derived from types and classes (constructors, selectors)
116         * Imported Ids
117
118 At the end of type checking, we zonk the local bindings,
119 and as we do so we add to the GlobalEnv
120         * Locally defined top-level Ids
121
122 Why?  Because they are now Ids not TcIds.  This final GlobalEnv is
123 used thus:
124         a) fed back (via the knot) to typechecking the 
125            unfoldings of interface signatures
126
127         b) used to augment the GlobalSymbolTable
128
129
130 \begin{code}
131 data TcTyThing
132   = AGlobal TyThing     -- Used only in the return type of a lookup
133   | ATcId  TcId         -- Ids defined in this module
134   | ATyVar TyVar        -- Type variables
135   | AThing TcKind       -- Used temporarily, during kind checking
136 -- Here's an example of how the AThing guy is used
137 -- Suppose we are checking (forall a. T a Int):
138 --      1. We first bind (a -> AThink kv), where kv is a kind variable. 
139 --      2. Then we kind-check the (T a Int) part.
140 --      3. Then we zonk the kind variable.
141 --      4. Now we know the kind for 'a', and we add (a -> ATyVar a::K) to the environment
142
143 initTcEnv :: HomeSymbolTable -> PackageTypeEnv -> IO TcEnv
144 initTcEnv hst pte 
145   = do { gtv_var <- newIORef emptyVarSet ;
146          return (TcEnv { tcGST    = lookup,
147                          tcGEnv   = emptyNameEnv,
148                          tcInsts  = emptyInstEnv,
149                          tcLEnv   = emptyNameEnv,
150                          tcTyVars = gtv_var
151          })}
152   where
153     lookup name | isLocalName name = Nothing
154                 | otherwise        = lookupType hst pte name
155
156
157 tcEnvClasses env = [cl | AClass cl <- nameEnvElts (tcGEnv env)]
158 tcEnvTyCons  env = [tc | ATyCon tc <- nameEnvElts (tcGEnv env)] 
159 tcEnvIds     env = [id | AnId   id <- nameEnvElts (tcGEnv env)] 
160 tcEnvTyVars  env = [tv | ATyVar tv <- nameEnvElts (tcLEnv env)]
161 tcEnvTcIds   env = [id | ATcId  id <- nameEnvElts (tcLEnv env)]
162
163 getTcGEnv (TcEnv { tcGEnv = genv }) = genv
164
165 -- This data type is used to help tie the knot
166 -- when type checking type and class declarations
167 data TyThingDetails = SynTyDetails Type
168                     | DataTyDetails ClassContext [DataCon] [Id]
169                     | ClassDetails ClassContext [Id] [ClassOpItem] DataCon
170 \end{code}
171
172
173 %************************************************************************
174 %*                                                                      *
175 \subsection{Basic lookups}
176 %*                                                                      *
177 %************************************************************************
178
179 \begin{code}
180 lookup_global :: TcEnv -> Name -> Maybe TyThing
181         -- Try the global envt and then the global symbol table
182 lookup_global env name 
183   = case lookupNameEnv (tcGEnv env) name of
184         Just thing -> Just thing
185         Nothing    -> tcGST env name
186
187 lookup_local :: TcEnv -> Name -> Maybe TcTyThing
188         -- Try the local envt and then try the global
189 lookup_local env name
190   = case lookupNameEnv (tcLEnv env) name of
191         Just thing -> Just thing
192         Nothing    -> case lookup_global env name of
193                         Just thing -> Just (AGlobal thing)
194                         Nothing    -> Nothing
195 \end{code}
196
197 \begin{code}
198 type RecTcEnv = TcEnv
199 -- This environment is used for getting the 'right' IdInfo 
200 -- on imported things and for looking up Ids in unfoldings
201 -- The environment doesn't have any local Ids in it
202
203 tcAddImportedIdInfo :: RecTcEnv -> Id -> Id
204 tcAddImportedIdInfo env id
205   = id `lazySetIdInfo` new_info
206         -- The Id must be returned without a data dependency on maybe_id
207   where
208     new_info = case tcLookupRecId_maybe env (idName id) of
209                   Nothing          -> constantIdInfo
210                   Just imported_id -> idInfo imported_id
211                 -- ToDo: could check that types are the same
212
213 tcLookupRecId_maybe :: RecTcEnv -> Name -> Maybe Id
214 tcLookupRecId_maybe env name = case lookup_global env name of
215                                    Just (AnId id) -> Just id
216                                    other          -> Nothing
217
218 tcLookupRecId ::  RecTcEnv -> Name -> Id
219 tcLookupRecId env name = case lookup_global env name of
220                                 Just (AnId id) -> id
221                                 Nothing        -> pprPanic "tcLookupRecId" (ppr name)
222 \end{code}
223
224 %************************************************************************
225 %*                                                                      *
226 \subsection{Random useful functions}
227 %*                                                                      *
228 %************************************************************************
229
230
231 \begin{code}
232 -- A useful function that takes an occurrence of a global thing
233 -- and instantiates its type with fresh type variables
234 tcInstId :: Id
235          -> NF_TcM ([TcTyVar],  -- It's instantiated type
236                       TcThetaType,      --
237                       TcType)           --
238 tcInstId id
239   = let
240       (tyvars, rho) = splitForAllTys (idType id)
241     in
242     tcInstTyVars tyvars         `thenNF_Tc` \ (tyvars', arg_tys, tenv) ->
243     let
244         rho'           = substTy tenv rho
245         (theta', tau') = splitRhoTy rho' 
246     in
247     returnNF_Tc (tyvars', theta', tau')
248 \end{code}
249
250
251 %************************************************************************
252 %*                                                                      *
253 \subsection{Making new Ids}
254 %*                                                                      *
255 %************************************************************************
256
257 Constructing new Ids
258
259 \begin{code}
260 newLocalId :: OccName -> TcType -> SrcLoc -> NF_TcM TcId
261 newLocalId name ty loc
262   = tcGetUnique         `thenNF_Tc` \ uniq ->
263     returnNF_Tc (mkUserLocal name uniq ty loc)
264
265 newSpecPragmaId :: Name -> TcType -> NF_TcM TcId
266 newSpecPragmaId name ty 
267   = tcGetUnique         `thenNF_Tc` \ uniq ->
268     returnNF_Tc (mkSpecPragmaId (nameOccName name) uniq ty (getSrcLoc name))
269 \end{code}
270
271 Make a name for the dict fun for an instance decl.
272 It's a *local* name for the moment.  The CoreTidy pass
273 will globalise it.
274
275 \begin{code}
276 newDFunName :: Class -> [Type] -> SrcLoc -> NF_TcM Name
277 newDFunName clas (ty:_) loc
278   = tcGetUnique                 `thenNF_Tc` \ uniq ->
279     returnNF_Tc (mkLocalName uniq (mkDFunOcc dfun_string) loc)
280   where
281         -- Any string that is somewhat unique will do
282     dfun_string = occNameString (getOccName clas) ++ occNameString (getDFunTyKey ty)
283
284 newDFunName clas [] loc = pprPanic "newDFunName" (ppr clas <+> ppr loc)
285 \end{code}
286
287 \begin{code}
288 isLocalThing :: NamedThing a => Module -> a -> Bool
289   -- True if the thing has a Local name, 
290   -- or a Global name from the specified module
291 isLocalThing mod thing = case nameModule_maybe (getName thing) of
292                            Nothing -> True      -- A local name
293                            Just m  -> m == mod  -- A global thing
294 \end{code}
295
296 %************************************************************************
297 %*                                                                      *
298 \subsection{The global environment}
299 %*                                                                      *
300 %************************************************************************
301
302 \begin{code}
303 tcExtendGlobalEnv :: [TyThing] -> TcM r -> TcM r
304 tcExtendGlobalEnv things thing_inside
305   = tcGetEnv                            `thenNF_Tc` \ env ->
306     let
307         ge' = extendNameEnvList (tcGEnv env) [(getName thing, thing) | thing <- things]
308     in
309     tcSetEnv (env {tcGEnv = ge'}) thing_inside
310
311 tcExtendGlobalValEnv :: [Id] -> TcM a -> TcM a
312 tcExtendGlobalValEnv ids thing_inside
313   = tcGetEnv                            `thenNF_Tc` \ env ->
314     let
315         ge' = extendNameEnvList (tcGEnv env) [(getName id, AnId id) | id <- ids]
316     in
317     tcSetEnv (env {tcGEnv = ge'}) thing_inside
318 \end{code}
319
320
321 \begin{code}
322 tcLookupGlobal_maybe :: Name -> NF_TcM (Maybe TyThing)
323 tcLookupGlobal_maybe name
324   = tcGetEnv            `thenNF_Tc` \ env ->
325     returnNF_Tc (lookup_global env name)
326 \end{code}
327
328 A variety of global lookups, when we know what we are looking for.
329
330 \begin{code}
331 tcLookupGlobal :: Name -> NF_TcM TyThing
332 tcLookupGlobal name
333   = tcLookupGlobal_maybe name   `thenNF_Tc` \ maybe_thing ->
334     case maybe_thing of
335         Just thing -> returnNF_Tc thing
336         other      -> notFound "tcLookupGlobal" name
337
338 tcLookupGlobalId :: Name -> NF_TcM Id
339 tcLookupGlobalId name
340   = tcLookupGlobal_maybe name   `thenNF_Tc` \ maybe_id ->
341     case maybe_id of
342         Just (AnId clas) -> returnNF_Tc clas
343         other            -> notFound "tcLookupGlobalId" name
344         
345 tcLookupDataCon :: Name -> TcM DataCon
346 tcLookupDataCon con_name
347   = tcLookupGlobalId con_name           `thenNF_Tc` \ con_id ->
348     case isDataConWrapId_maybe con_id of
349         Just data_con -> returnTc data_con
350         Nothing       -> failWithTc (badCon con_id)
351
352
353 tcLookupClass :: Name -> NF_TcM Class
354 tcLookupClass name
355   = tcLookupGlobal_maybe name   `thenNF_Tc` \ maybe_clas ->
356     case maybe_clas of
357         Just (AClass clas) -> returnNF_Tc clas
358         other              -> notFound "tcLookupClass" name
359         
360 tcLookupTyCon :: Name -> NF_TcM TyCon
361 tcLookupTyCon name
362   = tcLookupGlobal_maybe name   `thenNF_Tc` \ maybe_tc ->
363     case maybe_tc of
364         Just (ATyCon tc) -> returnNF_Tc tc
365         other            -> notFound "tcLookupTyCon" name
366 \end{code}
367
368
369 %************************************************************************
370 %*                                                                      *
371 \subsection{The local environment}
372 %*                                                                      *
373 %************************************************************************
374
375 \begin{code}
376 tcLookup_maybe :: Name -> NF_TcM (Maybe TcTyThing)
377 tcLookup_maybe name
378   = tcGetEnv            `thenNF_Tc` \ env ->
379     returnNF_Tc (lookup_local env name)
380
381 tcLookup :: Name -> NF_TcM TcTyThing
382 tcLookup name
383   = tcLookup_maybe name         `thenNF_Tc` \ maybe_thing ->
384     case maybe_thing of
385         Just thing -> returnNF_Tc thing
386         other      -> notFound "tcLookup" name
387         -- Extract the IdInfo from an IfaceSig imported from an interface file
388 \end{code}
389
390
391 \begin{code}
392 tcExtendKindEnv :: [(Name,TcKind)] -> TcM r -> TcM r
393 tcExtendKindEnv pairs thing_inside
394   = tcGetEnv                            `thenNF_Tc` \ env ->
395     let
396         le' = extendNameEnvList (tcLEnv env) [(n, AThing k) | (n,k) <- pairs]
397         -- No need to extend global tyvars for kind checking
398     in
399     tcSetEnv (env {tcLEnv = le'}) thing_inside
400     
401 tcExtendTyVarEnv :: [TyVar] -> TcM r -> TcM r
402 tcExtendTyVarEnv tyvars thing_inside
403   = tcGetEnv                    `thenNF_Tc` \ env@(TcEnv {tcLEnv = le, tcTyVars = gtvs}) ->
404     let
405         le'        = extendNameEnvList le [ (getName tv, ATyVar tv) | tv <- tyvars]
406         new_tv_set = mkVarSet tyvars
407     in
408         -- It's important to add the in-scope tyvars to the global tyvar set
409         -- as well.  Consider
410         --      f (x::r) = let g y = y::r in ...
411         -- Here, g mustn't be generalised.  This is also important during
412         -- class and instance decls, when we mustn't generalise the class tyvars
413         -- when typechecking the methods.
414     tc_extend_gtvs gtvs new_tv_set              `thenNF_Tc` \ gtvs' ->
415     tcSetEnv (env {tcLEnv = le', tcTyVars = gtvs'}) thing_inside
416
417 -- This variant, tcExtendTyVarEnvForMeths, takes *two* bunches of tyvars:
418 --      the signature tyvars contain the original names
419 --      the instance  tyvars are what those names should be mapped to
420 -- It's needed when typechecking the method bindings of class and instance decls
421 -- It does *not* extend the global tyvars; tcMethodBind does that for itself
422
423 tcExtendTyVarEnvForMeths :: [TyVar] -> [TcTyVar] -> TcM r -> TcM r
424 tcExtendTyVarEnvForMeths sig_tyvars inst_tyvars thing_inside
425   = tcGetEnv                                    `thenNF_Tc` \ env ->
426     let
427         le'   = extendNameEnvList (tcLEnv env) stuff
428         stuff = [ (getName sig_tv, ATyVar inst_tv)
429                 | (sig_tv, inst_tv) <- zipEqual "tcMeth" sig_tyvars inst_tyvars
430                 ]
431     in
432     tcSetEnv (env {tcLEnv = le'}) thing_inside
433 \end{code}
434
435
436 \begin{code}
437 tcExtendLocalValEnv :: [(Name,TcId)] -> TcM a -> TcM a
438 tcExtendLocalValEnv names_w_ids thing_inside
439   = tcGetEnv            `thenNF_Tc` \ env ->
440     let
441         extra_global_tyvars = tyVarsOfTypes [idType id | (name,id) <- names_w_ids]
442         extra_env           = [(name, ATcId id) | (name,id) <- names_w_ids]
443         le'                 = extendNameEnvList (tcLEnv env) extra_env
444     in
445     tc_extend_gtvs (tcTyVars env) extra_global_tyvars   `thenNF_Tc` \ gtvs' ->
446     tcSetEnv (env {tcLEnv = le', tcTyVars = gtvs'}) thing_inside
447 \end{code}
448
449
450 %************************************************************************
451 %*                                                                      *
452 \subsection{The global tyvars}
453 %*                                                                      *
454 %************************************************************************
455
456 \begin{code}
457 tcExtendGlobalTyVars extra_global_tvs thing_inside
458   = tcGetEnv                                            `thenNF_Tc` \ env ->
459     tc_extend_gtvs (tcTyVars env) extra_global_tvs      `thenNF_Tc` \ gtvs' ->
460     tcSetEnv (env {tcTyVars = gtvs'}) thing_inside
461
462 tc_extend_gtvs gtvs extra_global_tvs
463   = tcReadMutVar gtvs                   `thenNF_Tc` \ global_tvs ->
464     tcNewMutVar (global_tvs `unionVarSet` extra_global_tvs)
465 \end{code}
466
467 @tcGetGlobalTyVars@ returns a fully-zonked set of tyvars free in the environment.
468 To improve subsequent calls to the same function it writes the zonked set back into
469 the environment.
470
471 \begin{code}
472 tcGetGlobalTyVars :: NF_TcM TcTyVarSet
473 tcGetGlobalTyVars
474   = tcGetEnv                                    `thenNF_Tc` \ (TcEnv {tcTyVars = gtv_var}) ->
475     tcReadMutVar gtv_var                        `thenNF_Tc` \ global_tvs ->
476     zonkTcTyVars (varSetElems global_tvs)       `thenNF_Tc` \ global_tys' ->
477     let
478         global_tvs' = (tyVarsOfTypes global_tys')
479     in
480     tcWriteMutVar gtv_var global_tvs'           `thenNF_Tc_` 
481     returnNF_Tc global_tvs'
482 \end{code}
483
484
485 %************************************************************************
486 %*                                                                      *
487 \subsection{The instance environment}
488 %*                                                                      *
489 %************************************************************************
490
491 \begin{code}
492 tcGetInstEnv :: NF_TcM InstEnv
493 tcGetInstEnv = tcGetEnv         `thenNF_Tc` \ env -> 
494                returnNF_Tc (tcInsts env)
495
496 tcSetInstEnv :: InstEnv -> TcM a -> TcM a
497 tcSetInstEnv ie thing_inside
498   = tcGetEnv    `thenNF_Tc` \ env ->
499     tcSetEnv (env {tcInsts = ie}) thing_inside
500 \end{code}    
501
502
503 %************************************************************************
504 %*                                                                      *
505 \subsection{The InstInfo type}
506 %*                                                                      *
507 %************************************************************************
508
509 The InstInfo type summarises the information in an instance declaration
510
511     instance c => k (t tvs) where b
512
513 \begin{code}
514 data InstInfo
515   = InstInfo {
516       iLocal  :: Bool,                  -- True <=> it's defined in this module
517       iDFunId :: DFunId,                -- The dfun id
518       iBinds  :: RenamedMonoBinds,      -- Bindings, b
519       iPrags  :: [RenamedSig]           -- User pragmas recorded for generating specialised instances
520     }
521
522 pprInstInfo info = vcat [ptext SLIT("InstInfo:") <+> ppr (idType (iDFunId info)),
523                          nest 4 (ppr (iBinds info))]
524
525 simpleInstInfoTy :: InstInfo -> Type
526 simpleInstInfoTy info = case splitDFunTy (idType (iDFunId info)) of
527                           (_, _, _, [ty]) -> ty
528
529 simpleInstInfoTyCon :: InstInfo -> TyCon
530   -- Gets the type constructor for a simple instance declaration,
531   -- i.e. one of the form       instance (...) => C (T a b c) where ...
532 simpleInstInfoTyCon inst = tyConAppTyCon (simpleInstInfoTy inst)
533 \end{code}
534
535
536 %************************************************************************
537 %*                                                                      *
538 \subsection{Errors}
539 %*                                                                      *
540 %************************************************************************
541
542 \begin{code}
543 badCon con_id = quotes (ppr con_id) <+> ptext SLIT("is not a data constructor")
544
545 notFound wheRe name = failWithTc (text wheRe <> colon <+> quotes (ppr name) <+> 
546                                   ptext SLIT("is not in scope"))
547 \end{code}