[project @ 2000-11-20 14:48:52 by simonpj]
[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         newDefaultMethodName, 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, nameModule, getSrcLoc, mkGlobalName,
63                           isLocalName, nameModule_maybe
64                         )
65 import Name             ( NameEnv, lookupNameEnv, nameEnvElts, extendNameEnvList, emptyNameEnv )
66 import OccName          ( mkDFunOcc, mkDefaultMethodOcc, 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
273 \begin{code}
274 newDFunName :: Module -> Class -> [Type] -> SrcLoc -> NF_TcM Name
275 newDFunName mod clas (ty:_) loc
276   = tcGetDFunUniq dfun_string   `thenNF_Tc` \ inst_uniq ->
277     tcGetUnique                 `thenNF_Tc` \ uniq ->
278     returnNF_Tc (mkGlobalName uniq mod
279                               (mkDFunOcc dfun_string inst_uniq) 
280                               loc)
281   where
282         -- Any string that is somewhat unique will do
283     dfun_string = occNameString (getOccName clas) ++ occNameString (getDFunTyKey ty)
284
285 newDFunName mod clas [] loc = pprPanic "newDFunName" (ppr mod <+> ppr clas <+> ppr loc)
286
287 newDefaultMethodName :: Name -> SrcLoc -> NF_TcM Name
288 newDefaultMethodName op_name loc
289   = tcGetUnique                 `thenNF_Tc` \ uniq ->
290     returnNF_Tc (mkGlobalName uniq (nameModule op_name)
291                               (mkDefaultMethodOcc (getOccName op_name))
292                               loc)
293 \end{code}
294
295 \begin{code}
296 isLocalThing :: NamedThing a => Module -> a -> Bool
297   -- True if the thing has a Local name, 
298   -- or a Global name from the specified module
299 isLocalThing mod thing = case nameModule_maybe (getName thing) of
300                            Nothing -> True      -- A local name
301                            Just m  -> m == mod  -- A global thing
302 \end{code}
303
304 %************************************************************************
305 %*                                                                      *
306 \subsection{The global environment}
307 %*                                                                      *
308 %************************************************************************
309
310 \begin{code}
311 tcExtendGlobalEnv :: [TyThing] -> TcM r -> TcM r
312 tcExtendGlobalEnv things thing_inside
313   = tcGetEnv                            `thenNF_Tc` \ env ->
314     let
315         ge' = extendNameEnvList (tcGEnv env) [(getName thing, thing) | thing <- things]
316     in
317     tcSetEnv (env {tcGEnv = ge'}) thing_inside
318
319 tcExtendGlobalValEnv :: [Id] -> TcM a -> TcM a
320 tcExtendGlobalValEnv ids thing_inside
321   = tcGetEnv                            `thenNF_Tc` \ env ->
322     let
323         ge' = extendNameEnvList (tcGEnv env) [(getName id, AnId id) | id <- ids]
324     in
325     tcSetEnv (env {tcGEnv = ge'}) thing_inside
326 \end{code}
327
328
329 \begin{code}
330 tcLookupGlobal_maybe :: Name -> NF_TcM (Maybe TyThing)
331 tcLookupGlobal_maybe name
332   = tcGetEnv            `thenNF_Tc` \ env ->
333     returnNF_Tc (lookup_global env name)
334 \end{code}
335
336 A variety of global lookups, when we know what we are looking for.
337
338 \begin{code}
339 tcLookupGlobal :: Name -> NF_TcM TyThing
340 tcLookupGlobal name
341   = tcLookupGlobal_maybe name   `thenNF_Tc` \ maybe_thing ->
342     case maybe_thing of
343         Just thing -> returnNF_Tc thing
344         other      -> notFound "tcLookupGlobal" name
345
346 tcLookupGlobalId :: Name -> NF_TcM Id
347 tcLookupGlobalId name
348   = tcLookupGlobal_maybe name   `thenNF_Tc` \ maybe_id ->
349     case maybe_id of
350         Just (AnId clas) -> returnNF_Tc clas
351         other            -> notFound "tcLookupGlobalId" name
352         
353 tcLookupDataCon :: Name -> TcM DataCon
354 tcLookupDataCon con_name
355   = tcLookupGlobalId con_name           `thenNF_Tc` \ con_id ->
356     case isDataConWrapId_maybe con_id of
357         Just data_con -> returnTc data_con
358         Nothing       -> failWithTc (badCon con_id)
359
360
361 tcLookupClass :: Name -> NF_TcM Class
362 tcLookupClass name
363   = tcLookupGlobal_maybe name   `thenNF_Tc` \ maybe_clas ->
364     case maybe_clas of
365         Just (AClass clas) -> returnNF_Tc clas
366         other              -> notFound "tcLookupClass" name
367         
368 tcLookupTyCon :: Name -> NF_TcM TyCon
369 tcLookupTyCon name
370   = tcLookupGlobal_maybe name   `thenNF_Tc` \ maybe_tc ->
371     case maybe_tc of
372         Just (ATyCon tc) -> returnNF_Tc tc
373         other            -> notFound "tcLookupTyCon" name
374 \end{code}
375
376
377 %************************************************************************
378 %*                                                                      *
379 \subsection{The local environment}
380 %*                                                                      *
381 %************************************************************************
382
383 \begin{code}
384 tcLookup_maybe :: Name -> NF_TcM (Maybe TcTyThing)
385 tcLookup_maybe name
386   = tcGetEnv            `thenNF_Tc` \ env ->
387     returnNF_Tc (lookup_local env name)
388
389 tcLookup :: Name -> NF_TcM TcTyThing
390 tcLookup name
391   = tcLookup_maybe name         `thenNF_Tc` \ maybe_thing ->
392     case maybe_thing of
393         Just thing -> returnNF_Tc thing
394         other      -> notFound "tcLookup" name
395         -- Extract the IdInfo from an IfaceSig imported from an interface file
396 \end{code}
397
398
399 \begin{code}
400 tcExtendKindEnv :: [(Name,TcKind)] -> TcM r -> TcM r
401 tcExtendKindEnv pairs thing_inside
402   = tcGetEnv                            `thenNF_Tc` \ env ->
403     let
404         le' = extendNameEnvList (tcLEnv env) [(n, AThing k) | (n,k) <- pairs]
405         -- No need to extend global tyvars for kind checking
406     in
407     tcSetEnv (env {tcLEnv = le'}) thing_inside
408     
409 tcExtendTyVarEnv :: [TyVar] -> TcM r -> TcM r
410 tcExtendTyVarEnv tyvars thing_inside
411   = tcGetEnv                    `thenNF_Tc` \ env@(TcEnv {tcLEnv = le, tcTyVars = gtvs}) ->
412     let
413         le'        = extendNameEnvList le [ (getName tv, ATyVar tv) | tv <- tyvars]
414         new_tv_set = mkVarSet tyvars
415     in
416         -- It's important to add the in-scope tyvars to the global tyvar set
417         -- as well.  Consider
418         --      f (x::r) = let g y = y::r in ...
419         -- Here, g mustn't be generalised.  This is also important during
420         -- class and instance decls, when we mustn't generalise the class tyvars
421         -- when typechecking the methods.
422     tc_extend_gtvs gtvs new_tv_set              `thenNF_Tc` \ gtvs' ->
423     tcSetEnv (env {tcLEnv = le', tcTyVars = gtvs'}) thing_inside
424
425 -- This variant, tcExtendTyVarEnvForMeths, takes *two* bunches of tyvars:
426 --      the signature tyvars contain the original names
427 --      the instance  tyvars are what those names should be mapped to
428 -- It's needed when typechecking the method bindings of class and instance decls
429 -- It does *not* extend the global tyvars; tcMethodBind does that for itself
430
431 tcExtendTyVarEnvForMeths :: [TyVar] -> [TcTyVar] -> TcM r -> TcM r
432 tcExtendTyVarEnvForMeths sig_tyvars inst_tyvars thing_inside
433   = tcGetEnv                                    `thenNF_Tc` \ env ->
434     let
435         le'   = extendNameEnvList (tcLEnv env) stuff
436         stuff = [ (getName sig_tv, ATyVar inst_tv)
437                 | (sig_tv, inst_tv) <- zipEqual "tcMeth" sig_tyvars inst_tyvars
438                 ]
439     in
440     tcSetEnv (env {tcLEnv = le'}) thing_inside
441 \end{code}
442
443
444 \begin{code}
445 tcExtendLocalValEnv :: [(Name,TcId)] -> TcM a -> TcM a
446 tcExtendLocalValEnv names_w_ids thing_inside
447   = tcGetEnv            `thenNF_Tc` \ env ->
448     let
449         extra_global_tyvars = tyVarsOfTypes [idType id | (name,id) <- names_w_ids]
450         extra_env           = [(name, ATcId id) | (name,id) <- names_w_ids]
451         le'                 = extendNameEnvList (tcLEnv env) extra_env
452     in
453     tc_extend_gtvs (tcTyVars env) extra_global_tyvars   `thenNF_Tc` \ gtvs' ->
454     tcSetEnv (env {tcLEnv = le', tcTyVars = gtvs'}) thing_inside
455 \end{code}
456
457
458 %************************************************************************
459 %*                                                                      *
460 \subsection{The global tyvars}
461 %*                                                                      *
462 %************************************************************************
463
464 \begin{code}
465 tcExtendGlobalTyVars extra_global_tvs thing_inside
466   = tcGetEnv                                            `thenNF_Tc` \ env ->
467     tc_extend_gtvs (tcTyVars env) extra_global_tvs      `thenNF_Tc` \ gtvs' ->
468     tcSetEnv (env {tcTyVars = gtvs'}) thing_inside
469
470 tc_extend_gtvs gtvs extra_global_tvs
471   = tcReadMutVar gtvs                   `thenNF_Tc` \ global_tvs ->
472     tcNewMutVar (global_tvs `unionVarSet` extra_global_tvs)
473 \end{code}
474
475 @tcGetGlobalTyVars@ returns a fully-zonked set of tyvars free in the environment.
476 To improve subsequent calls to the same function it writes the zonked set back into
477 the environment.
478
479 \begin{code}
480 tcGetGlobalTyVars :: NF_TcM TcTyVarSet
481 tcGetGlobalTyVars
482   = tcGetEnv                                    `thenNF_Tc` \ (TcEnv {tcTyVars = gtv_var}) ->
483     tcReadMutVar gtv_var                        `thenNF_Tc` \ global_tvs ->
484     zonkTcTyVars (varSetElems global_tvs)       `thenNF_Tc` \ global_tys' ->
485     let
486         global_tvs' = (tyVarsOfTypes global_tys')
487     in
488     tcWriteMutVar gtv_var global_tvs'           `thenNF_Tc_` 
489     returnNF_Tc global_tvs'
490 \end{code}
491
492
493 %************************************************************************
494 %*                                                                      *
495 \subsection{The instance environment}
496 %*                                                                      *
497 %************************************************************************
498
499 \begin{code}
500 tcGetInstEnv :: NF_TcM InstEnv
501 tcGetInstEnv = tcGetEnv         `thenNF_Tc` \ env -> 
502                returnNF_Tc (tcInsts env)
503
504 tcSetInstEnv :: InstEnv -> TcM a -> TcM a
505 tcSetInstEnv ie thing_inside
506   = tcGetEnv    `thenNF_Tc` \ env ->
507     tcSetEnv (env {tcInsts = ie}) thing_inside
508 \end{code}    
509
510
511 %************************************************************************
512 %*                                                                      *
513 \subsection{The InstInfo type}
514 %*                                                                      *
515 %************************************************************************
516
517 The InstInfo type summarises the information in an instance declaration
518
519     instance c => k (t tvs) where b
520
521 \begin{code}
522 data InstInfo
523   = InstInfo {
524       iLocal  :: Bool,                  -- True <=> it's defined in this module
525       iDFunId :: DFunId,                -- The dfun id
526       iBinds  :: RenamedMonoBinds,      -- Bindings, b
527       iPrags  :: [RenamedSig]           -- User pragmas recorded for generating specialised instances
528     }
529
530 pprInstInfo info = vcat [ptext SLIT("InstInfo:") <+> ppr (idType (iDFunId info)),
531                          nest 4 (ppr (iBinds info))]
532
533 simpleInstInfoTy :: InstInfo -> Type
534 simpleInstInfoTy info = case splitDFunTy (idType (iDFunId info)) of
535                           (_, _, _, [ty]) -> ty
536
537 simpleInstInfoTyCon :: InstInfo -> TyCon
538   -- Gets the type constructor for a simple instance declaration,
539   -- i.e. one of the form       instance (...) => C (T a b c) where ...
540 simpleInstInfoTyCon inst = tyConAppTyCon (simpleInstInfoTy inst)
541 \end{code}
542
543
544 %************************************************************************
545 %*                                                                      *
546 \subsection{Errors}
547 %*                                                                      *
548 %************************************************************************
549
550 \begin{code}
551 badCon con_id = quotes (ppr con_id) <+> ptext SLIT("is not a data constructor")
552
553 notFound wheRe name = failWithTc (text wheRe <> colon <+> quotes (ppr name) <+> 
554                                   ptext SLIT("is not in scope"))
555 \end{code}