3 TyThing(..), TyThingDetails(..), TcTyThing(..), TcId,
5 -- Instance environment, and InstInfo type
6 tcGetInstEnv, tcSetInstEnv,
7 InstInfo(..), pprInstInfo, pprInstInfoDetails,
8 simpleInstInfoTy, simpleInstInfoTyCon,
14 tcExtendGlobalTypeEnv,
15 tcLookupTyCon, tcLookupClass, tcLookupDataCon,
16 tcLookupGlobal_maybe, tcLookupGlobal, tcLookupGlobalId,
21 tcExtendTyVarEnv, tcExtendTyVarEnv2,
22 tcExtendLocalValEnv, tcExtendLocalValEnv2,
23 tcLookup, tcLookupLocalIds, tcLookup_maybe,
24 tcLookupId, tcLookupIdLvl,
25 getLclEnvElts, getInLocalScope,
28 -- Instance environment
29 tcExtendLocalInstEnv, tcExtendInstEnv,
34 -- Global type variables
37 -- Random useful things
38 RecTcGblEnv, tcLookupRecId_maybe,
40 -- Template Haskell stuff
41 wellStaged, spliceOK, bracketOK, tcMetaTy, metaLevel,
44 newLocalName, newDFunName,
50 #include "HsVersions.h"
52 import RnHsSyn ( RenamedMonoBinds, RenamedSig )
53 import HsSyn ( RuleDecl(..), ifaceRuleDeclName )
55 import TcMType ( zonkTcType, zonkTcTyVar, zonkTcTyVarsAndFV )
56 import TcType ( Type, ThetaType, TcKind, TcTyVar, TcTyVarSet,
57 tyVarsOfType, tyVarsOfTypes, tcSplitDFunTy, mkGenTyConApp,
58 getDFunTyKey, tcTyConAppTyCon, tyVarBindingInfo,
59 tidyOpenType, tidyOpenTyVar
61 import qualified Type ( getTyVar_maybe )
62 import Rules ( extendRuleBase )
63 import Id ( idName, isDataConWrapId_maybe )
64 import Var ( TyVar, Id, idType )
67 import CoreSyn ( IdCoreRule )
68 import DataCon ( DataCon )
69 import TyCon ( TyCon, DataConDetails )
70 import Class ( Class, ClassOpItem )
71 import Name ( Name, NamedThing(..),
72 getSrcLoc, mkInternalName, nameIsLocalOrFrom
75 import OccName ( mkDFunOcc, occNameString )
76 import HscTypes ( DFunId, TypeEnv, extendTypeEnvList,
77 TyThing(..), ExternalPackageState(..) )
78 import Rules ( RuleBase )
79 import BasicTypes ( EP )
80 import Module ( Module )
81 import InstEnv ( InstEnv, extendInstEnv )
82 import Maybes ( seqMaybe )
83 import SrcLoc ( SrcLoc )
85 import Maybe ( isJust )
86 import List ( partition )
90 %************************************************************************
94 %************************************************************************
97 instance Outputable Stage where
98 ppr Comp = text "Comp"
99 ppr (Brack l _ _) = text "Brack" <+> int l
100 ppr (Splice l) = text "Splice" <+> int l
103 metaLevel :: Stage -> Level
104 metaLevel Comp = topLevel
105 metaLevel (Splice l) = l
106 metaLevel (Brack l _ _) = l
108 wellStaged :: Level -- Binding level
109 -> Level -- Use level
111 wellStaged bind_stage use_stage
112 = bind_stage <= use_stage
114 -- Indicates the legal transitions on bracket( [| |] ).
115 bracketOK :: Stage -> Maybe Level
116 bracketOK (Brack _ _ _) = Nothing -- Bracket illegal inside a bracket
117 bracketOK stage = (Just (metaLevel stage + 1))
119 -- Indicates the legal transitions on splice($).
120 spliceOK :: Stage -> Maybe Level
121 spliceOK (Splice _) = Nothing -- Splice illegal inside splice
122 spliceOK stage = Just (metaLevel stage - 1)
124 tcMetaTy :: Name -> TcM Type
125 -- Given the name of a Template Haskell data type,
127 -- E.g. given the name "Expr" return the type "Expr"
129 = tcLookupTyCon tc_name `thenM` \ t ->
130 returnM (mkGenTyConApp t [])
131 -- Use mkGenTyConApp because it might be a synonym
135 %************************************************************************
137 \subsection{TyThingDetails}
139 %************************************************************************
141 This data type is used to help tie the knot
142 when type checking type and class declarations
145 data TyThingDetails = SynTyDetails Type
146 | DataTyDetails ThetaType (DataConDetails DataCon) [Id] (Maybe (EP Id))
147 | ClassDetails ThetaType [Id] [ClassOpItem] DataCon Name
148 -- The Name is the Name of the implicit TyCon for the class
149 | ForeignTyDetails -- Nothing yet
153 %************************************************************************
155 \subsection{Basic lookups}
157 %************************************************************************
160 type RecTcGblEnv = TcGblEnv
161 -- This environment is used for getting the 'right' IdInfo
162 -- on imported things and for looking up Ids in unfoldings
163 -- The environment doesn't have any local Ids in it
165 tcLookupRecId_maybe :: RecTcGblEnv -> Name -> Maybe Id
166 tcLookupRecId_maybe env name = case lookup_global env name of
167 Just (AnId id) -> Just id
171 %************************************************************************
173 \subsection{Making new Ids}
175 %************************************************************************
180 newLocalName :: Name -> TcM Name
181 newLocalName name -- Make a clone
182 = newUnique `thenM` \ uniq ->
183 returnM (mkInternalName uniq (getOccName name) (getSrcLoc name))
186 Make a name for the dict fun for an instance decl.
187 It's a *local* name for the moment. The CoreTidy pass
191 newDFunName :: Class -> [Type] -> SrcLoc -> TcM Name
192 newDFunName clas (ty:_) loc
193 = newUnique `thenM` \ uniq ->
194 returnM (mkInternalName uniq (mkDFunOcc dfun_string) loc)
196 -- Any string that is somewhat unique will do
197 dfun_string = occNameString (getOccName clas) ++ occNameString (getDFunTyKey ty)
199 newDFunName clas [] loc = pprPanic "newDFunName" (ppr clas <+> ppr loc)
203 isLocalThing :: NamedThing a => Module -> a -> Bool
204 isLocalThing mod thing = nameIsLocalOrFrom mod (getName thing)
207 %************************************************************************
209 \subsection{The global environment}
211 %************************************************************************
214 tcExtendGlobalEnv :: [TyThing] -> TcM r -> TcM r
215 -- Given a mixture of Ids, TyCons, Classes, perhaps from the
216 -- module being compiled, perhaps from a package module,
217 -- extend the global environment, and update the EPS
218 tcExtendGlobalEnv things thing_inside
222 ; let mod = tcg_mod env
223 (lcl_things, pkg_things) = partition (isLocalThing mod) things
224 ge' = extendTypeEnvList (tcg_type_env env) lcl_things
225 eps' = eps { eps_PTE = extendTypeEnvList (eps_PTE eps) pkg_things }
226 ist' = mkImpTypeEnv eps' hpt
228 ; setGblEnv (env {tcg_type_env = ge', tcg_ist = ist'}) thing_inside }
230 tcExtendGlobalValEnv :: [Id] -> TcM a -> TcM a
231 -- Same deal as tcExtendGlobalEnv, but for Ids
232 tcExtendGlobalValEnv ids thing_inside
233 = tcExtendGlobalEnv [AnId id | id <- ids] thing_inside
235 tcExtendGlobalTypeEnv :: TypeEnv -> TcM r -> TcM r
236 -- Top-level things of the interactive context
237 -- No need to extend the package env
238 tcExtendGlobalTypeEnv extra_env thing_inside
239 = do { env <- getGblEnv
240 ; let ge' = tcg_type_env env `plusNameEnv` extra_env
241 ; setGblEnv (env {tcg_type_env = ge'}) thing_inside }
246 lookup_global :: TcGblEnv -> Name -> Maybe TyThing
247 -- Try the global envt and then the global symbol table
248 lookup_global env name
249 = lookupNameEnv (tcg_type_env env) name
253 tcLookupGlobal_maybe :: Name -> TcRn m (Maybe TyThing)
254 tcLookupGlobal_maybe name
255 = getGblEnv `thenM` \ env ->
256 returnM (lookup_global env name)
259 A variety of global lookups, when we know what we are looking for.
262 tcLookupGlobal :: Name -> TcM TyThing
264 = tcLookupGlobal_maybe name `thenM` \ maybe_thing ->
266 Just thing -> returnM thing
267 other -> notFound "tcLookupGlobal" name
269 tcLookupGlobalId :: Name -> TcM Id
270 tcLookupGlobalId name
271 = tcLookupGlobal_maybe name `thenM` \ maybe_thing ->
273 Just (AnId id) -> returnM id
274 other -> notFound "tcLookupGlobal" name
276 tcLookupDataCon :: Name -> TcM DataCon
277 tcLookupDataCon con_name
278 = tcLookupGlobalId con_name `thenM` \ con_id ->
279 case isDataConWrapId_maybe con_id of
280 Just data_con -> returnM data_con
281 Nothing -> failWithTc (badCon con_id)
283 tcLookupClass :: Name -> TcM Class
285 = tcLookupGlobal_maybe name `thenM` \ maybe_clas ->
287 Just (AClass clas) -> returnM clas
288 other -> notFound "tcLookupClass" name
290 tcLookupTyCon :: Name -> TcM TyCon
292 = tcLookupGlobal_maybe name `thenM` \ maybe_tc ->
294 Just (ATyCon tc) -> returnM tc
295 other -> notFound "tcLookupTyCon" name
298 getInGlobalScope :: TcRn m (Name -> Bool)
299 getInGlobalScope = do { gbl_env <- getGblEnv ;
300 return (\n -> isJust (lookup_global gbl_env n)) }
304 %************************************************************************
306 \subsection{The local environment}
308 %************************************************************************
311 tcLookup_maybe :: Name -> TcM (Maybe TcTyThing)
313 = getLclEnv `thenM` \ local_env ->
314 case lookupNameEnv (tcl_env local_env) name of
315 Just thing -> returnM (Just thing)
316 Nothing -> tcLookupGlobal_maybe name `thenM` \ mb_res ->
317 returnM (case mb_res of
318 Just thing -> Just (AGlobal thing)
321 tcLookup :: Name -> TcM TcTyThing
323 = tcLookup_maybe name `thenM` \ maybe_thing ->
325 Just thing -> returnM thing
326 other -> notFound "tcLookup" name
327 -- Extract the IdInfo from an IfaceSig imported from an interface file
329 tcLookupId :: Name -> TcM Id
330 -- Used when we aren't interested in the binding level
332 = tcLookup name `thenM` \ thing ->
334 ATcId tc_id lvl -> returnM tc_id
335 AGlobal (AnId id) -> returnM id
336 other -> pprPanic "tcLookupId" (ppr name)
338 tcLookupIdLvl :: Name -> TcM (Id, Level)
340 = tcLookup name `thenM` \ thing ->
342 ATcId tc_id lvl -> returnM (tc_id, lvl)
343 AGlobal (AnId id) -> returnM (id, impLevel)
344 other -> pprPanic "tcLookupIdLvl" (ppr name)
346 tcLookupLocalIds :: [Name] -> TcM [TcId]
347 -- We expect the variables to all be bound, and all at
348 -- the same level as the lookup. Only used in one place...
350 = getLclEnv `thenM` \ env ->
351 returnM (map (lookup (tcl_env env) (metaLevel (tcl_level env))) ns)
354 = case lookupNameEnv lenv name of
355 Just (ATcId id lvl1) -> ASSERT( lvl == lvl1 ) id
356 other -> pprPanic "tcLookupLocalIds" (ppr name)
358 getLclEnvElts :: TcM [TcTyThing]
359 getLclEnvElts = getLclEnv `thenM` \ env ->
360 return (nameEnvElts (tcl_env env))
362 getInLocalScope :: TcM (Name -> Bool)
364 getInLocalScope = getLclEnv `thenM` \ env ->
366 lcl_env = tcl_env env
368 return (`elemNameEnv` lcl_env)
372 tcExtendKindEnv :: [(Name,TcKind)] -> TcM r -> TcM r
373 tcExtendKindEnv pairs thing_inside
374 = updLclEnv upd thing_inside
376 upd lcl_env = lcl_env { tcl_env = extend (tcl_env lcl_env) }
377 extend env = extendNameEnvList env [(n, AThing k) | (n,k) <- pairs]
378 -- No need to extend global tyvars for kind checking
380 tcExtendTyVarEnv :: [TyVar] -> TcM r -> TcM r
381 tcExtendTyVarEnv tvs thing_inside
382 = tc_extend_tv_env [(getName tv, ATyVar tv) | tv <- tvs] tvs thing_inside
384 tcExtendTyVarEnv2 :: [(TyVar,TcTyVar)] -> TcM r -> TcM r
385 tcExtendTyVarEnv2 tv_pairs thing_inside
386 = tc_extend_tv_env [(getName tv1, ATyVar tv2) | (tv1,tv2) <- tv_pairs]
387 [tv | (_,tv) <- tv_pairs]
390 tc_extend_tv_env binds tyvars thing_inside
391 = getLclEnv `thenM` \ env@(TcLclEnv {tcl_env = le, tcl_tyvars = gtvs}) ->
393 le' = extendNameEnvList le binds
394 new_tv_set = mkVarSet tyvars
396 -- It's important to add the in-scope tyvars to the global tyvar set
398 -- f (x::r) = let g y = y::r in ...
399 -- Here, g mustn't be generalised. This is also important during
400 -- class and instance decls, when we mustn't generalise the class tyvars
401 -- when typechecking the methods.
402 tc_extend_gtvs gtvs new_tv_set `thenM` \ gtvs' ->
403 setLclEnv (env {tcl_env = le', tcl_tyvars = gtvs'}) thing_inside
408 tcExtendLocalValEnv :: [TcId] -> TcM a -> TcM a
409 tcExtendLocalValEnv ids thing_inside
410 = getLclEnv `thenM` \ env ->
412 extra_global_tyvars = tyVarsOfTypes [idType id | id <- ids]
413 lvl = metaLevel (tcl_level env)
414 extra_env = [(idName id, ATcId id lvl) | id <- ids]
415 le' = extendNameEnvList (tcl_env env) extra_env
417 tc_extend_gtvs (tcl_tyvars env) extra_global_tyvars `thenM` \ gtvs' ->
418 setLclEnv (env {tcl_env = le', tcl_tyvars = gtvs'}) thing_inside
420 tcExtendLocalValEnv2 :: [(Name,TcId)] -> TcM a -> TcM a
421 tcExtendLocalValEnv2 names_w_ids thing_inside
422 = getLclEnv `thenM` \ env ->
424 extra_global_tyvars = tyVarsOfTypes [idType id | (name,id) <- names_w_ids]
425 lvl = metaLevel (tcl_level env)
426 extra_env = [(name, ATcId id lvl) | (name,id) <- names_w_ids]
427 le' = extendNameEnvList (tcl_env env) extra_env
429 tc_extend_gtvs (tcl_tyvars env) extra_global_tyvars `thenM` \ gtvs' ->
430 setLclEnv (env {tcl_env = le', tcl_tyvars = gtvs'}) thing_inside
435 -----------------------
436 -- findGlobals looks at the value environment and finds values
437 -- whose types mention the offending type variable. It has to be
438 -- careful to zonk the Id's type first, so it has to be in the monad.
439 -- We must be careful to pass it a zonked type variable, too.
441 findGlobals :: TcTyVarSet
443 -> TcM (TidyEnv, [SDoc])
445 findGlobals tvs tidy_env
446 = getLclEnvElts `thenM` \ lcl_env ->
447 go tidy_env [] lcl_env
449 go tidy_env acc [] = returnM (tidy_env, acc)
450 go tidy_env acc (thing : things)
451 = find_thing ignore_it tidy_env thing `thenM` \ (tidy_env1, maybe_doc) ->
453 Just d -> go tidy_env1 (d:acc) things
454 Nothing -> go tidy_env1 acc things
456 ignore_it ty = not (tvs `intersectsVarSet` tyVarsOfType ty)
458 -----------------------
459 find_thing ignore_it tidy_env (ATcId id _)
460 = zonkTcType (idType id) `thenM` \ id_ty ->
461 if ignore_it id_ty then
462 returnM (tidy_env, Nothing)
464 (tidy_env', tidy_ty) = tidyOpenType tidy_env id_ty
465 msg = sep [ppr id <+> dcolon <+> ppr tidy_ty,
466 nest 2 (parens (ptext SLIT("bound at") <+>
467 ppr (getSrcLoc id)))]
469 returnM (tidy_env', Just msg)
471 find_thing ignore_it tidy_env (ATyVar tv)
472 = zonkTcTyVar tv `thenM` \ tv_ty ->
473 if ignore_it tv_ty then
474 returnM (tidy_env, Nothing)
476 (tidy_env1, tv1) = tidyOpenTyVar tidy_env tv
477 (tidy_env2, tidy_ty) = tidyOpenType tidy_env1 tv_ty
478 msg = sep [ppr tv1 <+> eq_stuff, nest 2 bound_at]
480 eq_stuff | Just tv' <- Type.getTyVar_maybe tv_ty, tv == tv' = empty
481 | otherwise = equals <+> ppr tv_ty
482 -- It's ok to use Type.getTyVar_maybe because ty is zonked by now
484 bound_at = tyVarBindingInfo tv
486 returnM (tidy_env2, Just msg)
490 %************************************************************************
492 \subsection{The global tyvars}
494 %************************************************************************
497 tc_extend_gtvs gtvs extra_global_tvs
498 = readMutVar gtvs `thenM` \ global_tvs ->
499 newMutVar (global_tvs `unionVarSet` extra_global_tvs)
502 @tcGetGlobalTyVars@ returns a fully-zonked set of tyvars free in the environment.
503 To improve subsequent calls to the same function it writes the zonked set back into
507 tcGetGlobalTyVars :: TcM TcTyVarSet
509 = getLclEnv `thenM` \ (TcLclEnv {tcl_tyvars = gtv_var}) ->
510 readMutVar gtv_var `thenM` \ gbl_tvs ->
511 zonkTcTyVarsAndFV (varSetElems gbl_tvs) `thenM` \ gbl_tvs' ->
512 writeMutVar gtv_var gbl_tvs' `thenM_`
517 %************************************************************************
519 \subsection{The instance environment}
521 %************************************************************************
524 tcGetInstEnv :: TcM InstEnv
525 tcGetInstEnv = getGblEnv `thenM` \ env ->
526 returnM (tcg_inst_env env)
528 tcSetInstEnv :: InstEnv -> TcM a -> TcM a
529 tcSetInstEnv ie thing_inside
530 = getGblEnv `thenM` \ env ->
531 setGblEnv (env {tcg_inst_env = ie}) thing_inside
533 tcExtendInstEnv :: [DFunId] -> TcM a -> TcM a
534 -- Add instances from local or imported
535 -- instances, and refresh the instance-env cache
536 tcExtendInstEnv dfuns thing_inside
537 = do { dflags <- getDOpts
541 -- Extend the total inst-env with the new dfuns
542 (inst_env', errs) = extendInstEnv dflags (tcg_inst_env env) dfuns
544 -- Sort the ones from this module from the others
545 (lcl_dfuns, pkg_dfuns) = partition (isLocalThing mod) dfuns
548 -- And add the pieces to the right places
549 (eps_inst_env', _) = extendInstEnv dflags (eps_inst_env eps) pkg_dfuns
550 eps' = eps { eps_inst_env = eps_inst_env' }
552 env' = env { tcg_inst_env = inst_env',
553 tcg_insts = lcl_dfuns ++ tcg_insts env }
558 ; setGblEnv env' thing_inside }
560 tcExtendLocalInstEnv :: [InstInfo] -> TcM a -> TcM a
561 -- Special case for local instance decls
562 tcExtendLocalInstEnv infos thing_inside
563 = do { dflags <- getDOpts
566 dfuns = map iDFunId infos
567 (inst_env', errs) = extendInstEnv dflags (tcg_inst_env env) dfuns
568 env' = env { tcg_inst_env = inst_env',
569 tcg_insts = dfuns ++ tcg_insts env }
572 ; setGblEnv env' thing_inside }
575 = traceTc (text "Adding instances:" <+> vcat (map pp dfuns))
577 pp dfun = ppr dfun <+> dcolon <+> ppr (idType dfun)
581 %************************************************************************
585 %************************************************************************
588 tcExtendRules :: [RuleDecl Id] -> TcM a -> TcM a
589 -- Just pop the new rules into the EPS and envt resp
590 -- All the rules come from an interface file, not soruce
591 -- Nevertheless, some may be for this module, if we read
592 -- its interface instead of its source code
593 tcExtendRules rules thing_inside
597 (lcl_rules, pkg_rules) = partition is_local_rule rules
598 is_local_rule = isLocalThing mod . ifaceRuleDeclName
601 core_rules = [(id,rule) | IfaceRuleOut id rule <- pkg_rules]
602 eps' = eps { eps_rule_base = addIfaceRules (eps_rule_base eps) core_rules }
603 -- All the rules from an interface are of the IfaceRuleOut form
605 env' = env { tcg_rules = lcl_rules ++ tcg_rules env }
608 ; setGblEnv env' thing_inside }
610 addIfaceRules :: RuleBase -> [IdCoreRule] -> RuleBase
611 addIfaceRules rule_base rules
612 = foldl extendRuleBase rule_base rules
616 %************************************************************************
618 \subsection{The InstInfo type}
620 %************************************************************************
622 The InstInfo type summarises the information in an instance declaration
624 instance c => k (t tvs) where b
626 It is used just for *local* instance decls (not ones from interface files).
627 But local instance decls includes
630 as well as explicit user written ones.
635 iDFunId :: DFunId, -- The dfun id
636 iBinds :: InstBindings
640 = VanillaInst -- The normal case
641 RenamedMonoBinds -- Bindings
642 [RenamedSig] -- User pragmas recorded for generating
643 -- specialised instances
645 | NewTypeDerived -- Used for deriving instances of newtypes, where the
646 [Type] -- witness dictionary is identical to the argument
647 -- dictionary. Hence no bindings, no pragmas
648 -- The [Type] are the representation types
649 -- See notes in TcDeriv
651 pprInstInfo info = vcat [ptext SLIT("InstInfo:") <+> ppr (idType (iDFunId info))]
653 pprInstInfoDetails (InstInfo { iBinds = VanillaInst b _ }) = ppr b
654 pprInstInfoDetails (InstInfo { iBinds = NewTypeDerived _}) = text "Derived from the representation type"
656 simpleInstInfoTy :: InstInfo -> Type
657 simpleInstInfoTy info = case tcSplitDFunTy (idType (iDFunId info)) of
658 (_, _, _, [ty]) -> ty
660 simpleInstInfoTyCon :: InstInfo -> TyCon
661 -- Gets the type constructor for a simple instance declaration,
662 -- i.e. one of the form instance (...) => C (T a b c) where ...
663 simpleInstInfoTyCon inst = tcTyConAppTyCon (simpleInstInfoTy inst)
667 %************************************************************************
671 %************************************************************************
674 badCon con_id = quotes (ppr con_id) <+> ptext SLIT("is not a data constructor")
676 notFound wheRe name = failWithTc (text wheRe <> colon <+> quotes (ppr name) <+>
677 ptext SLIT("is not in scope"))