3 TyThing(..), TcTyThing(..), TcId,
5 -- Instance environment, and InstInfo type
6 InstInfo(..), iDFunId, pprInstInfo, pprInstInfoDetails,
7 simpleInstInfoClsTy, simpleInstInfoTy, simpleInstInfoTyCon,
13 tcLookupLocatedGlobal, tcLookupGlobal,
14 tcLookupField, tcLookupTyCon, tcLookupClass, tcLookupDataCon,
15 tcLookupLocatedGlobalId, tcLookupLocatedTyCon,
19 tcExtendKindEnv, tcExtendKindEnvTvs,
20 tcExtendTyVarEnv, tcExtendTyVarEnv2,
21 tcExtendIdEnv, tcExtendIdEnv1, tcExtendIdEnv2,
22 tcLookup, tcLookupLocated, tcLookupLocalIds,
23 tcLookupId, tcLookupTyVar, getScopedTyVarBinds,
24 lclEnvElts, getInLocalScope, findGlobals,
25 wrongThingErr, pprBinders,
28 tcExtendRecEnv, -- For knot-tying
33 -- Global type variables
36 -- Template Haskell stuff
37 checkWellStaged, spliceOK, bracketOK, tcMetaTy, thLevel,
41 newLocalName, newDFunName
44 #include "HsVersions.h"
46 import HsSyn ( LRuleDecl, LHsBinds, LSig,
47 LHsTyVarBndr, HsTyVarBndr(..), pprLHsBinds,
49 import TcIface ( tcImportDecl )
50 import IfaceEnv ( newGlobalBinder )
52 import TcMType ( zonkTcType, zonkTcTyVarsAndFV )
53 import TcType ( Type, TcKind, TcTyVar, TcTyVarSet, TcType,
54 substTy, tyVarsOfType, tcTyVarsOfTypes, mkTyConApp,
55 getDFunTyKey, tcTyConAppTyCon, tcGetTyVar, mkTyVarTy,
56 tidyOpenType, isRefineableTy
58 import TcGadt ( Refinement, refineType )
59 import qualified Type ( getTyVar_maybe )
60 import Id ( idName, isLocalId )
61 import Var ( TyVar, Id, idType, tyVarName )
64 import RdrName ( extendLocalRdrEnv )
65 import InstEnv ( Instance, DFunId, instanceDFunId, instanceHead )
66 import DataCon ( DataCon )
67 import TyCon ( TyCon )
68 import Class ( Class )
69 import Name ( Name, NamedThing(..), getSrcLoc, nameModule )
70 import PrelNames ( thFAKE )
72 import OccName ( mkDFunOcc, occNameString )
73 import HscTypes ( extendTypeEnvList, lookupType, TyThing(..), 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
96 -- The Name is almost always an ExternalName, but not always
97 -- In GHCi, we may make command-line bindings (ghci> let x = True)
98 -- that bind a GlobalId, but with an InternalName
100 = do { env <- getGblEnv
103 ; case lookupNameEnv (tcg_type_env env) name of {
104 Just thing -> return thing ;
108 { (eps,hpt) <- getEpsAndHpt
110 ; case lookupType dflags hpt (eps_PTE eps) name of {
111 Just thing -> return thing ;
114 -- Should it have been in the local envt?
115 { let mod = nameModule name
116 ; if mod == tcg_mod env || mod == thFAKE then
117 notFound name -- It should be local, so panic
118 -- The thFAKE possibility is because it
119 -- might be in a declaration bracket
121 tcImportDecl name -- Go find it in an interface
124 tcLookupField :: Name -> TcM Id -- Returns the selector Id
126 = tcLookupGlobal name `thenM` \ thing ->
129 other -> wrongThingErr "field name" (AGlobal thing) name
131 tcLookupDataCon :: Name -> TcM DataCon
133 = tcLookupGlobal name `thenM` \ thing ->
135 ADataCon con -> return con
136 other -> wrongThingErr "data constructor" (AGlobal thing) name
138 tcLookupClass :: Name -> TcM Class
140 = tcLookupGlobal name `thenM` \ thing ->
142 AClass cls -> return cls
143 other -> wrongThingErr "class" (AGlobal thing) name
145 tcLookupTyCon :: Name -> TcM TyCon
147 = tcLookupGlobal name `thenM` \ thing ->
149 ATyCon tc -> return tc
150 other -> wrongThingErr "type constructor" (AGlobal thing) name
152 tcLookupLocatedGlobalId :: Located Name -> TcM Id
153 tcLookupLocatedGlobalId = addLocM tcLookupId
155 tcLookupLocatedClass :: Located Name -> TcM Class
156 tcLookupLocatedClass = addLocM tcLookupClass
158 tcLookupLocatedTyCon :: Located Name -> TcM TyCon
159 tcLookupLocatedTyCon = addLocM tcLookupTyCon
162 %************************************************************************
164 Extending the global environment
166 %************************************************************************
170 tcExtendGlobalEnv :: [TyThing] -> TcM r -> TcM r
171 -- Given a mixture of Ids, TyCons, Classes, all from the
172 -- module being compiled, extend the global environment
173 tcExtendGlobalEnv things thing_inside
174 = do { env <- getGblEnv
175 ; let ge' = extendTypeEnvList (tcg_type_env env) things
176 ; setGblEnv (env {tcg_type_env = ge'}) thing_inside }
178 tcExtendGlobalValEnv :: [Id] -> TcM a -> TcM a
179 -- Same deal as tcExtendGlobalEnv, but for Ids
180 tcExtendGlobalValEnv ids thing_inside
181 = tcExtendGlobalEnv [AnId id | id <- ids] thing_inside
185 tcExtendRecEnv :: [(Name,TyThing)] -> TcM r -> TcM r
186 -- Extend the global environments for the type/class knot tying game
187 tcExtendRecEnv gbl_stuff thing_inside
188 = updGblEnv upd thing_inside
190 upd env = env { tcg_type_env = extend (tcg_type_env env) }
191 extend env = extendNameEnvList env gbl_stuff
195 %************************************************************************
197 \subsection{The local environment}
199 %************************************************************************
202 tcLookupLocated :: Located Name -> TcM TcTyThing
203 tcLookupLocated = addLocM tcLookup
205 tcLookup :: Name -> TcM TcTyThing
207 = getLclEnv `thenM` \ local_env ->
208 case lookupNameEnv (tcl_env local_env) name of
209 Just thing -> returnM thing
210 Nothing -> tcLookupGlobal name `thenM` \ thing ->
211 returnM (AGlobal thing)
213 tcLookupTyVar :: Name -> TcM TcTyVar
215 = tcLookup name `thenM` \ thing ->
217 ATyVar _ ty -> return (tcGetTyVar "tcLookupTyVar" ty)
218 other -> pprPanic "tcLookupTyVar" (ppr name)
220 tcLookupId :: Name -> TcM Id
221 -- Used when we aren't interested in the binding level, nor refinement.
222 -- The "no refinement" part means that we return the un-refined Id regardless
224 -- The Id is never a DataCon. (Why does that matter? see TcExpr.tcId)
226 = tcLookup name `thenM` \ thing ->
228 ATcId { tct_id = id} -> returnM id
229 AGlobal (AnId id) -> returnM id
230 other -> pprPanic "tcLookupId" (ppr name)
232 tcLookupLocalIds :: [Name] -> TcM [TcId]
233 -- We expect the variables to all be bound, and all at
234 -- the same level as the lookup. Only used in one place...
236 = getLclEnv `thenM` \ env ->
237 returnM (map (lookup (tcl_env env) (thLevel (tcl_th_ctxt env))) ns)
240 = case lookupNameEnv lenv name of
241 Just (ATcId { tct_id = id, tct_level = lvl1 })
242 -> ASSERT( lvl == lvl1 ) id
243 other -> pprPanic "tcLookupLocalIds" (ppr name)
245 lclEnvElts :: TcLclEnv -> [TcTyThing]
246 lclEnvElts env = nameEnvElts (tcl_env env)
248 getInLocalScope :: TcM (Name -> Bool)
250 getInLocalScope = getLclEnv `thenM` \ env ->
252 lcl_env = tcl_env env
254 return (`elemNameEnv` lcl_env)
258 tcExtendKindEnv :: [(Name, TcKind)] -> TcM r -> TcM r
259 tcExtendKindEnv things thing_inside
260 = updLclEnv upd thing_inside
262 upd lcl_env = lcl_env { tcl_env = extend (tcl_env lcl_env) }
263 extend env = extendNameEnvList env [(n, AThing k) | (n,k) <- things]
265 tcExtendKindEnvTvs :: [LHsTyVarBndr Name] -> TcM r -> TcM r
266 tcExtendKindEnvTvs bndrs thing_inside
267 = updLclEnv upd thing_inside
269 upd lcl_env = lcl_env { tcl_env = extend (tcl_env lcl_env) }
270 extend env = extendNameEnvList env pairs
271 pairs = [(n, AThing k) | L _ (KindedTyVar n k) <- bndrs]
273 tcExtendTyVarEnv :: [TyVar] -> TcM r -> TcM r
274 tcExtendTyVarEnv tvs thing_inside
275 = tcExtendTyVarEnv2 [(tyVarName tv, mkTyVarTy tv) | tv <- tvs] thing_inside
277 tcExtendTyVarEnv2 :: [(Name,TcType)] -> TcM r -> TcM r
278 tcExtendTyVarEnv2 binds thing_inside
279 = getLclEnv `thenM` \ env@(TcLclEnv {tcl_env = le,
281 tcl_rdr = rdr_env}) ->
283 rdr_env' = extendLocalRdrEnv rdr_env (map fst binds)
284 new_tv_set = tcTyVarsOfTypes (map snd binds)
285 le' = extendNameEnvList le [(name, ATyVar name ty) | (name, ty) <- binds]
287 -- It's important to add the in-scope tyvars to the global tyvar set
289 -- f (_::r) = let g y = y::r in ...
290 -- Here, g mustn't be generalised. This is also important during
291 -- class and instance decls, when we mustn't generalise the class tyvars
292 -- when typechecking the methods.
293 tc_extend_gtvs gtvs new_tv_set `thenM` \ gtvs' ->
294 setLclEnv (env {tcl_env = le', tcl_tyvars = gtvs', tcl_rdr = rdr_env'}) thing_inside
296 getScopedTyVarBinds :: TcM [(Name, TcType)]
298 = do { lcl_env <- getLclEnv
299 ; return [(name, ty) | ATyVar name ty <- nameEnvElts (tcl_env lcl_env)] }
304 tcExtendIdEnv :: [TcId] -> TcM a -> TcM a
305 -- Invariant: the TcIds are fully zonked. Reasons:
306 -- (a) The kinds of the forall'd type variables are defaulted
307 -- (see Kind.defaultKind, done in zonkQuantifiedTyVar)
308 -- (b) There are no via-Indirect occurrences of the bound variables
309 -- in the types, because instantiation does not look through such things
310 -- (c) The call to tyVarsOfTypes is ok without looking through refs
311 tcExtendIdEnv ids thing_inside = tcExtendIdEnv2 [(idName id, id) | id <- ids] thing_inside
313 tcExtendIdEnv1 :: Name -> TcId -> TcM a -> TcM a
314 tcExtendIdEnv1 name id thing_inside = tcExtendIdEnv2 [(name,id)] thing_inside
316 tcExtendIdEnv2 :: [(Name,TcId)] -> TcM a -> TcM a
317 -- Invariant: the TcIds are fully zonked (see tcExtendIdEnv above)
318 tcExtendIdEnv2 names_w_ids thing_inside
319 = getLclEnv `thenM` \ env ->
321 extra_global_tyvars = tcTyVarsOfTypes [idType id | (_,id) <- names_w_ids]
322 th_lvl = thLevel (tcl_th_ctxt env)
323 extra_env = [ (name, ATcId { tct_id = id,
326 tct_co = if isRefineableTy id_ty
329 | (name,id) <- names_w_ids, let id_ty = idType id]
330 le' = extendNameEnvList (tcl_env env) extra_env
331 rdr_env' = extendLocalRdrEnv (tcl_rdr env) [name | (name,_) <- names_w_ids]
333 traceTc (text "env2") `thenM_`
334 traceTc (text "env3" <+> ppr extra_env) `thenM_`
335 tc_extend_gtvs (tcl_tyvars env) extra_global_tyvars `thenM` \ gtvs' ->
336 (traceTc (text "env4") `thenM_`
337 setLclEnv (env {tcl_env = le', tcl_tyvars = gtvs', tcl_rdr = rdr_env'}) thing_inside)
342 -----------------------
343 -- findGlobals looks at the value environment and finds values
344 -- whose types mention the offending type variable. It has to be
345 -- careful to zonk the Id's type first, so it has to be in the monad.
346 -- We must be careful to pass it a zonked type variable, too.
348 findGlobals :: TcTyVarSet
350 -> TcM (TidyEnv, [SDoc])
352 findGlobals tvs tidy_env
353 = getLclEnv `thenM` \ lcl_env ->
354 go tidy_env [] (lclEnvElts lcl_env)
356 go tidy_env acc [] = returnM (tidy_env, acc)
357 go tidy_env acc (thing : things)
358 = find_thing ignore_it tidy_env thing `thenM` \ (tidy_env1, maybe_doc) ->
360 Just d -> go tidy_env1 (d:acc) things
361 Nothing -> go tidy_env1 acc things
363 ignore_it ty = not (tvs `intersectsVarSet` tyVarsOfType ty)
365 -----------------------
366 find_thing ignore_it tidy_env (ATcId { tct_id = id })
367 = zonkTcType (idType id) `thenM` \ id_ty ->
368 if ignore_it id_ty then
369 returnM (tidy_env, Nothing)
371 (tidy_env', tidy_ty) = tidyOpenType tidy_env id_ty
372 msg = sep [ppr id <+> dcolon <+> ppr tidy_ty,
373 nest 2 (parens (ptext SLIT("bound at") <+>
374 ppr (getSrcLoc id)))]
376 returnM (tidy_env', Just msg)
378 find_thing ignore_it tidy_env (ATyVar tv ty)
379 = zonkTcType ty `thenM` \ tv_ty ->
380 if ignore_it tv_ty then
381 returnM (tidy_env, Nothing)
383 -- The name tv is scoped, so we don't need to tidy it
384 (tidy_env1, tidy_ty) = tidyOpenType tidy_env tv_ty
385 msg = sep [ptext SLIT("Scoped type variable") <+> quotes (ppr tv) <+> eq_stuff, nest 2 bound_at]
387 eq_stuff | Just tv' <- Type.getTyVar_maybe tv_ty,
388 getOccName tv == getOccName tv' = empty
389 | otherwise = equals <+> ppr tidy_ty
390 -- It's ok to use Type.getTyVar_maybe because ty is zonked by now
391 bound_at = parens $ ptext SLIT("bound at:") <+> ppr (getSrcLoc tv)
393 returnM (tidy_env1, Just msg)
395 find_thing _ _ thing = pprPanic "find_thing" (ppr thing)
399 refineEnvironment :: Refinement -> TcM a -> TcM a
400 -- I don't think I have to refine the set of global type variables in scope
401 -- Reason: the refinement never increases that set
402 refineEnvironment reft thing_inside
403 = do { env <- getLclEnv
404 ; let le' = mapNameEnv refine (tcl_env env)
405 ; setLclEnv (env {tcl_env = le'}) thing_inside }
407 refine elt@(ATcId { tct_co = Just co, tct_type = ty })
408 = let (co', ty') = refineType reft ty
409 in elt { tct_co = Just (co' <.> co), tct_type = ty' }
410 refine (ATyVar tv ty) = ATyVar tv (snd (refineType reft ty))
411 -- Ignore the coercion that refineType returns
415 %************************************************************************
417 \subsection{The global tyvars}
419 %************************************************************************
422 tc_extend_gtvs gtvs extra_global_tvs
423 = readMutVar gtvs `thenM` \ global_tvs ->
424 newMutVar (global_tvs `unionVarSet` extra_global_tvs)
427 @tcGetGlobalTyVars@ returns a fully-zonked set of tyvars free in the environment.
428 To improve subsequent calls to the same function it writes the zonked set back into
432 tcGetGlobalTyVars :: TcM TcTyVarSet
434 = getLclEnv `thenM` \ (TcLclEnv {tcl_tyvars = gtv_var}) ->
435 readMutVar gtv_var `thenM` \ gbl_tvs ->
436 zonkTcTyVarsAndFV (varSetElems gbl_tvs) `thenM` \ gbl_tvs' ->
437 writeMutVar gtv_var gbl_tvs' `thenM_`
442 %************************************************************************
446 %************************************************************************
449 tcExtendRules :: [LRuleDecl Id] -> TcM a -> TcM a
450 -- Just pop the new rules into the EPS and envt resp
451 -- All the rules come from an interface file, not soruce
452 -- Nevertheless, some may be for this module, if we read
453 -- its interface instead of its source code
454 tcExtendRules lcl_rules thing_inside
455 = do { env <- getGblEnv
457 env' = env { tcg_rules = lcl_rules ++ tcg_rules env }
458 ; setGblEnv env' thing_inside }
462 %************************************************************************
466 %************************************************************************
469 instance Outputable ThStage where
470 ppr Comp = text "Comp"
471 ppr (Brack l _ _) = text "Brack" <+> int l
472 ppr (Splice l) = text "Splice" <+> int l
475 thLevel :: ThStage -> ThLevel
476 thLevel Comp = topLevel
477 thLevel (Splice l) = l
478 thLevel (Brack l _ _) = l
481 checkWellStaged :: SDoc -- What the stage check is for
482 -> ThLevel -- Binding level
483 -> ThStage -- Use stage
484 -> TcM () -- Fail if badly staged, adding an error
485 checkWellStaged pp_thing bind_lvl use_stage
486 | bind_lvl <= use_lvl -- OK!
489 | bind_lvl == topLevel -- GHC restriction on top level splices
491 sep [ptext SLIT("GHC stage restriction:") <+> pp_thing,
492 nest 2 (ptext SLIT("is used in a top-level splice, and must be imported, not defined locally"))]
494 | otherwise -- Badly staged
496 ptext SLIT("Stage error:") <+> pp_thing <+>
497 hsep [ptext SLIT("is bound at stage") <+> ppr bind_lvl,
498 ptext SLIT("but used at stage") <+> ppr use_lvl]
500 use_lvl = thLevel use_stage
503 topIdLvl :: Id -> ThLevel
504 -- Globals may either be imported, or may be from an earlier "chunk"
505 -- (separated by declaration splices) of this module. The former
506 -- *can* be used inside a top-level splice, but the latter cannot.
507 -- Hence we give the former impLevel, but the latter topLevel
511 -- By the time we are prcessing the $(f x), the binding for "x"
512 -- will be in the global env, not the local one.
513 topIdLvl id | isLocalId id = topLevel
514 | otherwise = impLevel
516 -- Indicates the legal transitions on bracket( [| |] ).
517 bracketOK :: ThStage -> Maybe ThLevel
518 bracketOK (Brack _ _ _) = Nothing -- Bracket illegal inside a bracket
519 bracketOK stage = Just (thLevel stage + 1)
521 -- Indicates the legal transitions on splice($).
522 spliceOK :: ThStage -> Maybe ThLevel
523 spliceOK (Splice _) = Nothing -- Splice illegal inside splice
524 spliceOK stage = Just (thLevel stage - 1)
526 tcMetaTy :: Name -> TcM Type
527 -- Given the name of a Template Haskell data type,
529 -- E.g. given the name "Expr" return the type "Expr"
531 = tcLookupTyCon tc_name `thenM` \ t ->
532 returnM (mkTyConApp t [])
536 %************************************************************************
538 \subsection{The InstInfo type}
540 %************************************************************************
542 The InstInfo type summarises the information in an instance declaration
544 instance c => k (t tvs) where b
546 It is used just for *local* instance decls (not ones from interface files).
547 But local instance decls includes
550 as well as explicit user written ones.
555 iSpec :: Instance, -- Includes the dfun id. Its forall'd type
556 iBinds :: InstBindings -- variables scope over the stuff in InstBindings!
559 iDFunId :: InstInfo -> DFunId
560 iDFunId info = instanceDFunId (iSpec info)
563 = VanillaInst -- The normal case
564 (LHsBinds Name) -- Bindings
565 [LSig Name] -- User pragmas recorded for generating
566 -- specialised instances
569 TyCon -- tycon for the newtype
570 -- Used for deriving instances of newtypes, where the
571 [Type] -- witness dictionary is identical to the argument
572 -- dictionary. Hence no bindings, no pragmas
573 -- The [Type] are the representation types
574 -- See notes in TcDeriv
576 pprInstInfo info = vcat [ptext SLIT("InstInfo:") <+> ppr (idType (iDFunId info))]
578 pprInstInfoDetails info = pprInstInfo info $$ nest 2 (details (iBinds info))
580 details (VanillaInst b _) = pprLHsBinds b
581 details (NewTypeDerived _ _) = text "Derived from the representation type"
583 simpleInstInfoClsTy :: InstInfo -> (Class, Type)
584 simpleInstInfoClsTy info = case instanceHead (iSpec info) of
585 (_, _, cls, [ty]) -> (cls, ty)
587 simpleInstInfoTy :: InstInfo -> Type
588 simpleInstInfoTy info = snd (simpleInstInfoClsTy info)
590 simpleInstInfoTyCon :: InstInfo -> TyCon
591 -- Gets the type constructor for a simple instance declaration,
592 -- i.e. one of the form instance (...) => C (T a b c) where ...
593 simpleInstInfoTyCon inst = tcTyConAppTyCon (simpleInstInfoTy inst)
596 Make a name for the dict fun for an instance decl. It's an *external*
597 name, like otber top-level names, and hence must be made with newGlobalBinder.
600 newDFunName :: Class -> [Type] -> SrcLoc -> TcM Name
601 newDFunName clas (ty:_) loc
602 = do { index <- nextDFunIndex
603 ; is_boot <- tcIsHsBoot
605 ; let info_string = occNameString (getOccName clas) ++
606 occNameString (getDFunTyKey ty)
607 dfun_occ = mkDFunOcc info_string is_boot index
609 ; newGlobalBinder mod dfun_occ Nothing loc }
611 newDFunName clas [] loc = pprPanic "newDFunName" (ppr clas <+> ppr loc)
615 %************************************************************************
619 %************************************************************************
622 pprBinders :: [Name] -> SDoc
623 -- Used in error messages
624 -- Use quotes for a single one; they look a bit "busy" for several
625 pprBinders [bndr] = quotes (ppr bndr)
626 pprBinders bndrs = pprWithCommas ppr bndrs
629 = failWithTc (ptext SLIT("GHC internal error:") <+> quotes (ppr name) <+>
630 ptext SLIT("is not in scope"))
632 wrongThingErr expected thing name
633 = failWithTc (pprTcTyThingCategory thing <+> quotes (ppr name) <+>
634 ptext SLIT("used as a") <+> text expected)