3 TyThing(..), TcTyThing(..), TcId,
5 -- Instance environment, and InstInfo type
6 InstInfo(..), iDFunId, pprInstInfo, pprInstInfoDetails,
7 simpleInstInfoClsTy, simpleInstInfoTy, simpleInstInfoTyCon,
13 tcLookupLocatedGlobal, tcLookupGlobal,
14 tcLookupGlobalId, tcLookupTyCon, tcLookupClass, tcLookupDataCon,
15 tcLookupLocatedGlobalId, tcLookupLocatedTyCon,
19 tcExtendKindEnv, tcExtendKindEnvTvs,
20 tcExtendTyVarEnv, tcExtendTyVarEnv2,
21 tcExtendIdEnv, tcExtendIdEnv1, tcExtendIdEnv2,
22 tcLookup, tcLookupLocated, tcLookupLocalIds,
23 tcLookupId, tcLookupTyVar,
24 lclEnvElts, getInLocalScope, findGlobals,
25 wrongThingErr, pprBinders,
27 tcExtendRecEnv, -- For knot-tying
32 -- Global type variables
35 -- Template Haskell stuff
36 checkWellStaged, spliceOK, bracketOK, tcMetaTy, thLevel,
40 newLocalName, newDFunName
43 #include "HsVersions.h"
45 import HsSyn ( LRuleDecl, LHsBinds, LSig,
46 LHsTyVarBndr, HsTyVarBndr(..), pprLHsBinds )
47 import TcIface ( tcImportDecl )
48 import IfaceEnv ( newGlobalBinder )
49 import TcRnTypes ( pprTcTyThingCategory )
51 import TcMType ( zonkTcType, zonkTcTyVarsAndFV )
52 import TcType ( Type, TcKind, TcTyVar, TcTyVarSet, TcType,
53 tyVarsOfType, tyVarsOfTypes, mkGenTyConApp,
54 getDFunTyKey, tcTyConAppTyCon, tcGetTyVar, mkTyVarTy,
57 import qualified Type ( getTyVar_maybe )
58 import Id ( idName, isLocalId )
59 import Var ( TyVar, Id, idType, tyVarName )
62 import RdrName ( extendLocalRdrEnv )
63 import InstEnv ( Instance, DFunId, instanceDFunId, instanceHead )
64 import DataCon ( DataCon )
65 import TyCon ( TyCon )
66 import Class ( Class )
67 import Name ( Name, NamedThing(..), getSrcLoc, nameIsLocalOrFrom )
69 import OccName ( mkDFunOcc, occNameString )
70 import HscTypes ( extendTypeEnvList, lookupType,
71 TyThing(..), tyThingId, tyThingDataCon,
72 ExternalPackageState(..) )
74 import SrcLoc ( SrcLoc, Located(..) )
79 %************************************************************************
83 %************************************************************************
85 Using the Located versions (eg. tcLookupLocatedGlobal) is preferred,
86 unless you know that the SrcSpan in the monad is already set to the
90 tcLookupLocatedGlobal :: Located Name -> TcM TyThing
91 -- c.f. IfaceEnvEnv.tcIfaceGlobal
92 tcLookupLocatedGlobal name
93 = addLocM tcLookupGlobal name
95 tcLookupGlobal :: Name -> TcM TyThing
97 = do { env <- getGblEnv
98 ; if nameIsLocalOrFrom (tcg_mod env) name
100 then -- It's defined in this module
101 case lookupNameEnv (tcg_type_env env) name of
102 Just thing -> return thing
103 Nothing -> notFound name -- Panic!
105 else do -- It's imported
106 { (eps,hpt) <- getEpsAndHpt
107 ; case lookupType hpt (eps_PTE eps) name of
108 Just thing -> return thing
109 Nothing -> tcImportDecl name
112 tcLookupGlobalId :: Name -> TcM Id
113 -- Never used for Haskell-source DataCons, hence no ADataCon case
114 tcLookupGlobalId name
115 = tcLookupGlobal name `thenM` \ thing ->
116 return (tyThingId thing)
118 tcLookupDataCon :: Name -> TcM DataCon
119 tcLookupDataCon con_name
120 = tcLookupGlobal con_name `thenM` \ thing ->
121 return (tyThingDataCon thing)
123 tcLookupClass :: Name -> TcM Class
125 = tcLookupGlobal name `thenM` \ thing ->
127 AClass cls -> return cls
128 other -> wrongThingErr "class" (AGlobal thing) name
130 tcLookupTyCon :: Name -> TcM TyCon
132 = tcLookupGlobal name `thenM` \ thing ->
134 ATyCon tc -> return tc
135 other -> wrongThingErr "type constructor" (AGlobal thing) name
137 tcLookupLocatedGlobalId :: Located Name -> TcM Id
138 tcLookupLocatedGlobalId = addLocM tcLookupId
140 tcLookupLocatedClass :: Located Name -> TcM Class
141 tcLookupLocatedClass = addLocM tcLookupClass
143 tcLookupLocatedTyCon :: Located Name -> TcM TyCon
144 tcLookupLocatedTyCon = addLocM tcLookupTyCon
147 %************************************************************************
149 Extending the global environment
151 %************************************************************************
155 tcExtendGlobalEnv :: [TyThing] -> TcM r -> TcM r
156 -- Given a mixture of Ids, TyCons, Classes, all from the
157 -- module being compiled, extend the global environment
158 tcExtendGlobalEnv things thing_inside
159 = do { env <- getGblEnv
160 ; let ge' = extendTypeEnvList (tcg_type_env env) things
161 ; setGblEnv (env {tcg_type_env = ge'}) thing_inside }
163 tcExtendGlobalValEnv :: [Id] -> TcM a -> TcM a
164 -- Same deal as tcExtendGlobalEnv, but for Ids
165 tcExtendGlobalValEnv ids thing_inside
166 = tcExtendGlobalEnv [AnId id | id <- ids] thing_inside
170 tcExtendRecEnv :: [(Name,TyThing)] -> TcM r -> TcM r
171 -- Extend the global environments for the type/class knot tying game
172 tcExtendRecEnv gbl_stuff thing_inside
173 = updGblEnv upd thing_inside
175 upd env = env { tcg_type_env = extend (tcg_type_env env) }
176 extend env = extendNameEnvList env gbl_stuff
180 %************************************************************************
182 \subsection{The local environment}
184 %************************************************************************
187 tcLookupLocated :: Located Name -> TcM TcTyThing
188 tcLookupLocated = addLocM tcLookup
190 tcLookup :: Name -> TcM TcTyThing
192 = getLclEnv `thenM` \ local_env ->
193 case lookupNameEnv (tcl_env local_env) name of
194 Just thing -> returnM thing
195 Nothing -> tcLookupGlobal name `thenM` \ thing ->
196 returnM (AGlobal thing)
198 tcLookupTyVar :: Name -> TcM TcTyVar
200 = tcLookup name `thenM` \ thing ->
202 ATyVar _ ty -> returnM (tcGetTyVar "tcLookupTyVar" ty)
203 other -> pprPanic "tcLookupTyVar" (ppr name)
205 tcLookupId :: Name -> TcM Id
206 -- Used when we aren't interested in the binding level
207 -- Never a DataCon. (Why does that matter? see TcExpr.tcId)
209 = tcLookup name `thenM` \ thing ->
211 ATcId tc_id _ -> returnM tc_id
212 AGlobal (AnId id) -> returnM id
213 other -> pprPanic "tcLookupId" (ppr name)
215 tcLookupLocalIds :: [Name] -> TcM [TcId]
216 -- We expect the variables to all be bound, and all at
217 -- the same level as the lookup. Only used in one place...
219 = getLclEnv `thenM` \ env ->
220 returnM (map (lookup (tcl_env env) (thLevel (tcl_th_ctxt env))) ns)
223 = case lookupNameEnv lenv name of
224 Just (ATcId id lvl1) -> ASSERT( lvl == lvl1 ) id
225 other -> pprPanic "tcLookupLocalIds" (ppr name)
227 lclEnvElts :: TcLclEnv -> [TcTyThing]
228 lclEnvElts env = nameEnvElts (tcl_env env)
230 getInLocalScope :: TcM (Name -> Bool)
232 getInLocalScope = getLclEnv `thenM` \ env ->
234 lcl_env = tcl_env env
236 return (`elemNameEnv` lcl_env)
240 tcExtendKindEnv :: [(Name, TcKind)] -> TcM r -> TcM r
241 tcExtendKindEnv things thing_inside
242 = updLclEnv upd thing_inside
244 upd lcl_env = lcl_env { tcl_env = extend (tcl_env lcl_env) }
245 extend env = extendNameEnvList env [(n, AThing k) | (n,k) <- things]
247 tcExtendKindEnvTvs :: [LHsTyVarBndr Name] -> TcM r -> TcM r
248 tcExtendKindEnvTvs bndrs thing_inside
249 = updLclEnv upd thing_inside
251 upd lcl_env = lcl_env { tcl_env = extend (tcl_env lcl_env) }
252 extend env = extendNameEnvList env pairs
253 pairs = [(n, AThing k) | L _ (KindedTyVar n k) <- bndrs]
255 tcExtendTyVarEnv :: [TyVar] -> TcM r -> TcM r
256 tcExtendTyVarEnv tvs thing_inside
257 = tcExtendTyVarEnv2 [(tyVarName tv, mkTyVarTy tv) | tv <- tvs] thing_inside
259 tcExtendTyVarEnv2 :: [(Name,TcType)] -> TcM r -> TcM r
260 tcExtendTyVarEnv2 binds thing_inside
261 = getLclEnv `thenM` \ env@(TcLclEnv {tcl_env = le,
263 tcl_rdr = rdr_env}) ->
265 rdr_env' = extendLocalRdrEnv rdr_env (map fst binds)
266 new_tv_set = tyVarsOfTypes (map snd binds)
267 le' = extendNameEnvList le [(name, ATyVar name ty) | (name, ty) <- binds]
269 -- It's important to add the in-scope tyvars to the global tyvar set
271 -- f (_::r) = let g y = y::r in ...
272 -- Here, g mustn't be generalised. This is also important during
273 -- class and instance decls, when we mustn't generalise the class tyvars
274 -- when typechecking the methods.
275 tc_extend_gtvs gtvs new_tv_set `thenM` \ gtvs' ->
276 setLclEnv (env {tcl_env = le', tcl_tyvars = gtvs', tcl_rdr = rdr_env'}) thing_inside
281 tcExtendIdEnv :: [TcId] -> TcM a -> TcM a
282 -- Invariant: the TcIds are fully zonked. Reasons:
283 -- (a) The kinds of the forall'd type variables are defaulted
284 -- (see Kind.defaultKind, done in zonkQuantifiedTyVar)
285 -- (b) There are no via-Indirect occurrences of the bound variables
286 -- in the types, because instantiation does not look through such things
287 -- (c) The call to tyVarsOfTypes is ok without looking through refs
288 tcExtendIdEnv ids thing_inside = tcExtendIdEnv2 [(idName id, id) | id <- ids] thing_inside
290 tcExtendIdEnv1 :: Name -> TcId -> TcM a -> TcM a
291 tcExtendIdEnv1 name id thing_inside = tcExtendIdEnv2 [(name,id)] thing_inside
293 tcExtendIdEnv2 :: [(Name,TcId)] -> TcM a -> TcM a
294 -- Invariant: the TcIds are fully zonked (see tcExtendIdEnv above)
295 tcExtendIdEnv2 names_w_ids thing_inside
296 = getLclEnv `thenM` \ env ->
298 extra_global_tyvars = tyVarsOfTypes [idType id | (name,id) <- names_w_ids]
299 th_lvl = thLevel (tcl_th_ctxt env)
300 extra_env = [(name, ATcId id th_lvl) | (name,id) <- names_w_ids]
301 le' = extendNameEnvList (tcl_env env) extra_env
302 rdr_env' = extendLocalRdrEnv (tcl_rdr env) (map fst names_w_ids)
304 tc_extend_gtvs (tcl_tyvars env) extra_global_tyvars `thenM` \ gtvs' ->
305 setLclEnv (env {tcl_env = le', tcl_tyvars = gtvs', tcl_rdr = rdr_env'}) thing_inside
310 -----------------------
311 -- findGlobals looks at the value environment and finds values
312 -- whose types mention the offending type variable. It has to be
313 -- careful to zonk the Id's type first, so it has to be in the monad.
314 -- We must be careful to pass it a zonked type variable, too.
316 findGlobals :: TcTyVarSet
318 -> TcM (TidyEnv, [SDoc])
320 findGlobals tvs tidy_env
321 = getLclEnv `thenM` \ lcl_env ->
322 go tidy_env [] (lclEnvElts lcl_env)
324 go tidy_env acc [] = returnM (tidy_env, acc)
325 go tidy_env acc (thing : things)
326 = find_thing ignore_it tidy_env thing `thenM` \ (tidy_env1, maybe_doc) ->
328 Just d -> go tidy_env1 (d:acc) things
329 Nothing -> go tidy_env1 acc things
331 ignore_it ty = not (tvs `intersectsVarSet` tyVarsOfType ty)
333 -----------------------
334 find_thing ignore_it tidy_env (ATcId id _)
335 = zonkTcType (idType id) `thenM` \ id_ty ->
336 if ignore_it id_ty then
337 returnM (tidy_env, Nothing)
339 (tidy_env', tidy_ty) = tidyOpenType tidy_env id_ty
340 msg = sep [ppr id <+> dcolon <+> ppr tidy_ty,
341 nest 2 (parens (ptext SLIT("bound at") <+>
342 ppr (getSrcLoc id)))]
344 returnM (tidy_env', Just msg)
346 find_thing ignore_it tidy_env (ATyVar tv ty)
347 = zonkTcType ty `thenM` \ tv_ty ->
348 if ignore_it tv_ty then
349 returnM (tidy_env, Nothing)
351 -- The name tv is scoped, so we don't need to tidy it
352 (tidy_env1, tidy_ty) = tidyOpenType tidy_env tv_ty
353 msg = sep [ptext SLIT("Scoped type variable") <+> quotes (ppr tv) <+> eq_stuff, nest 2 bound_at]
355 eq_stuff | Just tv' <- Type.getTyVar_maybe tv_ty,
356 getOccName tv == getOccName tv' = empty
357 | otherwise = equals <+> ppr tidy_ty
358 -- It's ok to use Type.getTyVar_maybe because ty is zonked by now
359 bound_at = parens $ ptext SLIT("bound at:") <+> ppr (getSrcLoc tv)
361 returnM (tidy_env1, Just msg)
365 %************************************************************************
367 \subsection{The global tyvars}
369 %************************************************************************
372 tc_extend_gtvs gtvs extra_global_tvs
373 = readMutVar gtvs `thenM` \ global_tvs ->
374 newMutVar (global_tvs `unionVarSet` extra_global_tvs)
377 @tcGetGlobalTyVars@ returns a fully-zonked set of tyvars free in the environment.
378 To improve subsequent calls to the same function it writes the zonked set back into
382 tcGetGlobalTyVars :: TcM TcTyVarSet
384 = getLclEnv `thenM` \ (TcLclEnv {tcl_tyvars = gtv_var}) ->
385 readMutVar gtv_var `thenM` \ gbl_tvs ->
386 zonkTcTyVarsAndFV (varSetElems gbl_tvs) `thenM` \ gbl_tvs' ->
387 writeMutVar gtv_var gbl_tvs' `thenM_`
392 %************************************************************************
396 %************************************************************************
399 tcExtendRules :: [LRuleDecl Id] -> TcM a -> TcM a
400 -- Just pop the new rules into the EPS and envt resp
401 -- All the rules come from an interface file, not soruce
402 -- Nevertheless, some may be for this module, if we read
403 -- its interface instead of its source code
404 tcExtendRules lcl_rules thing_inside
405 = do { env <- getGblEnv
407 env' = env { tcg_rules = lcl_rules ++ tcg_rules env }
408 ; setGblEnv env' thing_inside }
412 %************************************************************************
416 %************************************************************************
419 instance Outputable ThStage where
420 ppr Comp = text "Comp"
421 ppr (Brack l _ _) = text "Brack" <+> int l
422 ppr (Splice l) = text "Splice" <+> int l
425 thLevel :: ThStage -> ThLevel
426 thLevel Comp = topLevel
427 thLevel (Splice l) = l
428 thLevel (Brack l _ _) = l
431 checkWellStaged :: SDoc -- What the stage check is for
432 -> ThLevel -- Binding level
433 -> ThStage -- Use stage
434 -> TcM () -- Fail if badly staged, adding an error
435 checkWellStaged pp_thing bind_lvl use_stage
436 | bind_lvl <= use_lvl -- OK!
439 | bind_lvl == topLevel -- GHC restriction on top level splices
441 sep [ptext SLIT("GHC stage restriction:") <+> pp_thing,
442 nest 2 (ptext SLIT("is used in a top-level splice, and must be imported, not defined locally"))]
444 | otherwise -- Badly staged
446 ptext SLIT("Stage error:") <+> pp_thing <+>
447 hsep [ptext SLIT("is bound at stage") <+> ppr bind_lvl,
448 ptext SLIT("but used at stage") <+> ppr use_lvl]
450 use_lvl = thLevel use_stage
453 topIdLvl :: Id -> ThLevel
454 -- Globals may either be imported, or may be from an earlier "chunk"
455 -- (separated by declaration splices) of this module. The former
456 -- *can* be used inside a top-level splice, but the latter cannot.
457 -- Hence we give the former impLevel, but the latter topLevel
461 -- By the time we are prcessing the $(f x), the binding for "x"
462 -- will be in the global env, not the local one.
463 topIdLvl id | isLocalId id = topLevel
464 | otherwise = impLevel
466 -- Indicates the legal transitions on bracket( [| |] ).
467 bracketOK :: ThStage -> Maybe ThLevel
468 bracketOK (Brack _ _ _) = Nothing -- Bracket illegal inside a bracket
469 bracketOK stage = Just (thLevel stage + 1)
471 -- Indicates the legal transitions on splice($).
472 spliceOK :: ThStage -> Maybe ThLevel
473 spliceOK (Splice _) = Nothing -- Splice illegal inside splice
474 spliceOK stage = Just (thLevel stage - 1)
476 tcMetaTy :: Name -> TcM Type
477 -- Given the name of a Template Haskell data type,
479 -- E.g. given the name "Expr" return the type "Expr"
481 = tcLookupTyCon tc_name `thenM` \ t ->
482 returnM (mkGenTyConApp t [])
483 -- Use mkGenTyConApp because it might be a synonym
487 %************************************************************************
489 \subsection{The InstInfo type}
491 %************************************************************************
493 The InstInfo type summarises the information in an instance declaration
495 instance c => k (t tvs) where b
497 It is used just for *local* instance decls (not ones from interface files).
498 But local instance decls includes
501 as well as explicit user written ones.
506 iSpec :: Instance, -- Includes the dfun id. Its forall'd type
507 iBinds :: InstBindings -- variables scope over the stuff in InstBindings!
510 iDFunId :: InstInfo -> DFunId
511 iDFunId info = instanceDFunId (iSpec info)
514 = VanillaInst -- The normal case
515 (LHsBinds Name) -- Bindings
516 [LSig Name] -- User pragmas recorded for generating
517 -- specialised instances
519 | NewTypeDerived -- Used for deriving instances of newtypes, where the
520 [Type] -- witness dictionary is identical to the argument
521 -- dictionary. Hence no bindings, no pragmas
522 -- The [Type] are the representation types
523 -- See notes in TcDeriv
525 pprInstInfo info = vcat [ptext SLIT("InstInfo:") <+> ppr (idType (iDFunId info))]
527 pprInstInfoDetails info = pprInstInfo info $$ nest 2 (details (iBinds info))
529 details (VanillaInst b _) = pprLHsBinds b
530 details (NewTypeDerived _) = text "Derived from the representation type"
532 simpleInstInfoClsTy :: InstInfo -> (Class, Type)
533 simpleInstInfoClsTy info = case instanceHead (iSpec info) of
534 (_, _, cls, [ty]) -> (cls, ty)
536 simpleInstInfoTy :: InstInfo -> Type
537 simpleInstInfoTy info = snd (simpleInstInfoClsTy info)
539 simpleInstInfoTyCon :: InstInfo -> TyCon
540 -- Gets the type constructor for a simple instance declaration,
541 -- i.e. one of the form instance (...) => C (T a b c) where ...
542 simpleInstInfoTyCon inst = tcTyConAppTyCon (simpleInstInfoTy inst)
545 Make a name for the dict fun for an instance decl. It's an *external*
546 name, like otber top-level names, and hence must be made with newGlobalBinder.
549 newDFunName :: Class -> [Type] -> SrcLoc -> TcM Name
550 newDFunName clas (ty:_) loc
551 = do { index <- nextDFunIndex
552 ; is_boot <- tcIsHsBoot
554 ; let info_string = occNameString (getOccName clas) ++
555 occNameString (getDFunTyKey ty)
556 dfun_occ = mkDFunOcc info_string is_boot index
558 ; newGlobalBinder mod dfun_occ Nothing loc }
560 newDFunName clas [] loc = pprPanic "newDFunName" (ppr clas <+> ppr loc)
564 %************************************************************************
568 %************************************************************************
571 pprBinders :: [Name] -> SDoc
572 -- Used in error messages
573 -- Use quotes for a single one; they look a bit "busy" for several
574 pprBinders [bndr] = quotes (ppr bndr)
575 pprBinders bndrs = pprWithCommas ppr bndrs
578 = failWithTc (ptext SLIT("GHC internal error:") <+> quotes (ppr name) <+>
579 ptext SLIT("is not in scope"))
581 wrongThingErr expected thing name
582 = failWithTc (pprTcTyThingCategory thing <+> quotes (ppr name) <+>
583 ptext SLIT("used as a") <+> text expected)