3 TyThing(..), TcTyThing(..), TcId,
5 -- Instance environment, and InstInfo type
6 InstInfo(..), pprInstInfo, pprInstInfoDetails,
7 simpleInstInfoTy, simpleInstInfoTyCon,
13 tcLookupLocatedGlobal, tcLookupGlobal,
14 tcLookupGlobalId, tcLookupTyCon, tcLookupClass, tcLookupDataCon,
15 tcLookupLocatedGlobalId, tcLookupLocatedTyCon,
16 tcLookupLocatedClass, tcLookupLocatedDataCon,
22 tcExtendTyVarEnv, tcExtendTyVarEnv2,
23 tcExtendLocalValEnv, tcExtendLocalValEnv2,
24 tcLookup, tcLookupLocated, tcLookupLocalIds,
25 tcLookupId, tcLookupTyVar,
26 lclEnvElts, getInLocalScope, findGlobals,
28 tcExtendRecEnv, -- For knot-tying
33 -- Global type variables
36 -- Template Haskell stuff
37 checkWellStaged, spliceOK, bracketOK, tcMetaTy, thLevel,
44 newLocalName, newDFunName
47 #include "HsVersions.h"
49 import HsSyn ( LRuleDecl, , HsTyVarBndr(..), LHsTyVarBndr, LHsBinds,
51 import TcIface ( tcImportDecl )
53 import TcMType ( zonkTcType, zonkTcTyVar, zonkTcTyVarsAndFV )
54 import TcType ( Type, TcTyVar, TcTyVarSet,
55 tyVarsOfType, tyVarsOfTypes, tcSplitDFunTy, mkGenTyConApp,
56 getDFunTyKey, tcTyConAppTyCon, tyVarBindingInfo,
57 tidyOpenType, tidyOpenTyVar
59 import qualified Type ( getTyVar_maybe )
60 import Id ( idName, isLocalId )
61 import Var ( TyVar, Id, mkTyVar, idType )
64 import RdrName ( extendLocalRdrEnv )
65 import DataCon ( DataCon )
66 import TyCon ( TyCon )
67 import Class ( Class )
68 import Name ( Name, NamedThing(..), getSrcLoc, mkInternalName, nameIsLocalOrFrom )
70 import OccName ( mkDFunOcc, occNameString )
71 import HscTypes ( DFunId, extendTypeEnvList, lookupType,
72 TyThing(..), tyThingId, tyThingTyCon, tyThingClass, tyThingDataCon,
73 ExternalPackageState(..) )
75 import SrcLoc ( SrcLoc, Located(..) )
77 import Maybe ( isJust )
81 %************************************************************************
85 %************************************************************************
87 Using the Located versions (eg. tcLookupLocatedGlobal) is preferred,
88 unless you know that the SrcSpan in the monad is already set to the
92 tcLookupLocatedGlobal :: Located Name -> TcM TyThing
93 -- c.f. IfaceEnvEnv.tcIfaceGlobal
94 tcLookupLocatedGlobal name
95 = addLocM tcLookupGlobal name
97 tcLookupGlobal :: Name -> TcM TyThing
99 = do { env <- getGblEnv
100 ; if nameIsLocalOrFrom (tcg_mod env) name
102 then -- It's defined in this module
103 case lookupNameEnv (tcg_type_env env) name of
104 Just thing -> return thing
105 Nothing -> notFound "tcLookupGlobal" name
107 else do -- It's imported
110 ; case lookupType hpt (eps_PTE eps) name of
111 Just thing -> return thing
112 Nothing -> do { traceIf (text "tcLookupGlobal" <+> ppr name)
113 ; initIfaceTcRn (tcImportDecl name) }
118 tcLookupGlobalId :: Name -> TcM Id
119 -- Never used for Haskell-source DataCons, hence no ADataCon case
120 tcLookupGlobalId name
121 = tcLookupGlobal name `thenM` \ thing ->
122 return (tyThingId thing)
124 tcLookupDataCon :: Name -> TcM DataCon
125 tcLookupDataCon con_name
126 = tcLookupGlobal con_name `thenM` \ thing ->
127 return (tyThingDataCon thing)
129 tcLookupClass :: Name -> TcM Class
131 = tcLookupGlobal name `thenM` \ thing ->
132 return (tyThingClass thing)
134 tcLookupTyCon :: Name -> TcM TyCon
136 = tcLookupGlobal name `thenM` \ thing ->
137 return (tyThingTyCon thing)
139 tcLookupLocatedGlobalId :: Located Name -> TcM Id
140 tcLookupLocatedGlobalId = addLocM tcLookupId
142 tcLookupLocatedDataCon :: Located Name -> TcM DataCon
143 tcLookupLocatedDataCon = addLocM tcLookupDataCon
145 tcLookupLocatedClass :: Located Name -> TcM Class
146 tcLookupLocatedClass = addLocM tcLookupClass
148 tcLookupLocatedTyCon :: Located Name -> TcM TyCon
149 tcLookupLocatedTyCon = addLocM tcLookupTyCon
152 %************************************************************************
154 Extending the global environment
156 %************************************************************************
160 tcExtendGlobalEnv :: [TyThing] -> TcM r -> TcM r
161 -- Given a mixture of Ids, TyCons, Classes, all from the
162 -- module being compiled, extend the global environment
163 tcExtendGlobalEnv things thing_inside
164 = do { env <- getGblEnv
165 ; let ge' = extendTypeEnvList (tcg_type_env env) things
166 ; setGblEnv (env {tcg_type_env = ge'}) thing_inside }
168 tcExtendGlobalValEnv :: [Id] -> TcM a -> TcM a
169 -- Same deal as tcExtendGlobalEnv, but for Ids
170 tcExtendGlobalValEnv ids thing_inside
171 = tcExtendGlobalEnv [AnId id | id <- ids] thing_inside
174 A variety of global lookups, when we know what we are looking for.
177 getInGlobalScope :: TcM (Name -> Bool)
178 -- Get all things in the global environment; used for deciding what
179 -- rules to suck in. Anything defined in this module (nameIsLocalOrFrom)
180 -- is certainly in the envt, so we don't bother to look.
182 = do { mod <- getModule
185 ; return (\n -> nameIsLocalOrFrom mod n ||
186 isJust (lookupType hpt (eps_PTE eps) n)) }
191 tcExtendRecEnv :: [(Name,TyThing)] -- Global bindings
192 -> [(Name,TcTyThing)] -- Local bindings
194 -- Extend both local and global environments for the type/class knot tying game
195 tcExtendRecEnv gbl_stuff lcl_stuff thing_inside
196 = do { (gbl_env, lcl_env) <- getEnvs
197 ; let { ge' = extendNameEnvList (tcg_type_env gbl_env) gbl_stuff
198 ; le' = extendNameEnvList (tcl_env lcl_env) lcl_stuff }
199 ; setEnvs (gbl_env {tcg_type_env = ge'}, lcl_env {tcl_env = le'})
204 %************************************************************************
206 \subsection{The local environment}
208 %************************************************************************
211 tcLookupLocated :: Located Name -> TcM TcTyThing
212 tcLookupLocated = addLocM tcLookup
214 tcLookup :: Name -> TcM TcTyThing
216 = getLclEnv `thenM` \ local_env ->
217 case lookupNameEnv (tcl_env local_env) name of
218 Just thing -> returnM thing
219 Nothing -> tcLookupGlobal name `thenM` \ thing ->
220 returnM (AGlobal thing)
222 tcLookupTyVar :: Name -> TcM Id
224 = tcLookup name `thenM` \ thing ->
226 ATyVar tv -> returnM tv
227 other -> pprPanic "tcLookupTyVar" (ppr name)
229 tcLookupId :: Name -> TcM Id
230 -- Used when we aren't interested in the binding level
231 -- Never a DataCon. (Why does that matter? see TcExpr.tcId)
233 = tcLookup name `thenM` \ thing ->
235 ATcId tc_id _ _ -> returnM tc_id
236 AGlobal (AnId id) -> returnM id
237 other -> pprPanic "tcLookupId" (ppr name)
239 tcLookupLocalIds :: [Name] -> TcM [TcId]
240 -- We expect the variables to all be bound, and all at
241 -- the same level as the lookup. Only used in one place...
243 = getLclEnv `thenM` \ env ->
244 returnM (map (lookup (tcl_env env) (thLevel (tcl_th_ctxt env))) ns)
247 = case lookupNameEnv lenv name of
248 Just (ATcId id lvl1 _) -> ASSERT( lvl == lvl1 ) id
249 other -> pprPanic "tcLookupLocalIds" (ppr name)
251 lclEnvElts :: TcLclEnv -> [TcTyThing]
252 lclEnvElts env = nameEnvElts (tcl_env env)
254 getInLocalScope :: TcM (Name -> Bool)
256 getInLocalScope = getLclEnv `thenM` \ env ->
258 lcl_env = tcl_env env
260 return (`elemNameEnv` lcl_env)
264 tcExtendTyVarKindEnv :: [LHsTyVarBndr Name] -> TcM r -> TcM r
265 -- The tyvars are all kinded
266 tcExtendTyVarKindEnv tvs 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 [(n, ATyVar (mkTyVar n k))
271 | L _ (KindedTyVar n k) <- tvs]
272 -- No need to extend global tyvars for kind checking
274 tcExtendTyVarEnv :: [TyVar] -> TcM r -> TcM r
275 tcExtendTyVarEnv tvs thing_inside
276 = tc_extend_tv_env [(getName tv, ATyVar tv) | tv <- tvs] tvs thing_inside
278 tcExtendTyVarEnv2 :: [(TyVar,TcTyVar)] -> TcM r -> TcM r
279 tcExtendTyVarEnv2 tv_pairs thing_inside
280 = tc_extend_tv_env [(getName tv1, ATyVar tv2) | (tv1,tv2) <- tv_pairs]
281 [tv | (_,tv) <- tv_pairs]
284 tc_extend_tv_env binds tyvars thing_inside
285 = getLclEnv `thenM` \ env@(TcLclEnv {tcl_env = le,
287 tcl_rdr = rdr_env}) ->
289 le' = extendNameEnvList le binds
290 rdr_env' = extendLocalRdrEnv rdr_env (map fst binds)
291 new_tv_set = mkVarSet tyvars
293 -- It's important to add the in-scope tyvars to the global tyvar set
295 -- f (_::r) = let g y = y::r in ...
296 -- Here, g mustn't be generalised. This is also important during
297 -- class and instance decls, when we mustn't generalise the class tyvars
298 -- when typechecking the methods.
299 tc_extend_gtvs gtvs new_tv_set `thenM` \ gtvs' ->
300 setLclEnv (env {tcl_env = le', tcl_tyvars = gtvs', tcl_rdr = rdr_env'}) thing_inside
305 tcExtendLocalValEnv :: [TcId] -> TcM a -> TcM a
306 tcExtendLocalValEnv ids thing_inside
307 = getLclEnv `thenM` \ env ->
309 extra_global_tyvars = tyVarsOfTypes [idType id | id <- ids]
310 th_lvl = thLevel (tcl_th_ctxt env)
311 proc_lvl = proc_level (tcl_arrow_ctxt env)
312 extra_env = [(idName id, ATcId id th_lvl proc_lvl) | id <- ids]
313 le' = extendNameEnvList (tcl_env env) extra_env
314 rdr_env' = extendLocalRdrEnv (tcl_rdr env) (map idName ids)
316 tc_extend_gtvs (tcl_tyvars env) extra_global_tyvars `thenM` \ gtvs' ->
317 setLclEnv (env {tcl_env = le', tcl_tyvars = gtvs', tcl_rdr = rdr_env'}) thing_inside
319 tcExtendLocalValEnv2 :: [(Name,TcId)] -> TcM a -> TcM a
320 tcExtendLocalValEnv2 names_w_ids thing_inside
321 = getLclEnv `thenM` \ env ->
323 extra_global_tyvars = tyVarsOfTypes [idType id | (name,id) <- names_w_ids]
324 th_lvl = thLevel (tcl_th_ctxt env)
325 proc_lvl = proc_level (tcl_arrow_ctxt env)
326 extra_env = [(name, ATcId id th_lvl proc_lvl) | (name,id) <- names_w_ids]
327 le' = extendNameEnvList (tcl_env env) extra_env
328 rdr_env' = extendLocalRdrEnv (tcl_rdr env) (map fst names_w_ids)
330 tc_extend_gtvs (tcl_tyvars env) extra_global_tyvars `thenM` \ gtvs' ->
331 setLclEnv (env {tcl_env = le', tcl_tyvars = gtvs', tcl_rdr = rdr_env'}) thing_inside
336 -----------------------
337 -- findGlobals looks at the value environment and finds values
338 -- whose types mention the offending type variable. It has to be
339 -- careful to zonk the Id's type first, so it has to be in the monad.
340 -- We must be careful to pass it a zonked type variable, too.
342 findGlobals :: TcTyVarSet
344 -> TcM (TidyEnv, [SDoc])
346 findGlobals tvs tidy_env
347 = getLclEnv `thenM` \ lcl_env ->
348 go tidy_env [] (lclEnvElts lcl_env)
350 go tidy_env acc [] = returnM (tidy_env, acc)
351 go tidy_env acc (thing : things)
352 = find_thing ignore_it tidy_env thing `thenM` \ (tidy_env1, maybe_doc) ->
354 Just d -> go tidy_env1 (d:acc) things
355 Nothing -> go tidy_env1 acc things
357 ignore_it ty = not (tvs `intersectsVarSet` tyVarsOfType ty)
359 -----------------------
360 find_thing ignore_it tidy_env (ATcId id _ _)
361 = zonkTcType (idType id) `thenM` \ id_ty ->
362 if ignore_it id_ty then
363 returnM (tidy_env, Nothing)
365 (tidy_env', tidy_ty) = tidyOpenType tidy_env id_ty
366 msg = sep [ppr id <+> dcolon <+> ppr tidy_ty,
367 nest 2 (parens (ptext SLIT("bound at") <+>
368 ppr (getSrcLoc id)))]
370 returnM (tidy_env', Just msg)
372 find_thing ignore_it tidy_env (ATyVar tv)
373 = zonkTcTyVar tv `thenM` \ tv_ty ->
374 if ignore_it tv_ty then
375 returnM (tidy_env, Nothing)
377 (tidy_env1, tv1) = tidyOpenTyVar tidy_env tv
378 (tidy_env2, tidy_ty) = tidyOpenType tidy_env1 tv_ty
379 msg = sep [ppr tv1 <+> eq_stuff, nest 2 bound_at]
381 eq_stuff | Just tv' <- Type.getTyVar_maybe tv_ty,
383 | otherwise = equals <+> ppr tidy_ty
384 -- It's ok to use Type.getTyVar_maybe because ty is zonked by now
386 bound_at = tyVarBindingInfo tv
388 returnM (tidy_env2, Just msg)
392 %************************************************************************
394 \subsection{The global tyvars}
396 %************************************************************************
399 tc_extend_gtvs gtvs extra_global_tvs
400 = readMutVar gtvs `thenM` \ global_tvs ->
401 newMutVar (global_tvs `unionVarSet` extra_global_tvs)
404 @tcGetGlobalTyVars@ returns a fully-zonked set of tyvars free in the environment.
405 To improve subsequent calls to the same function it writes the zonked set back into
409 tcGetGlobalTyVars :: TcM TcTyVarSet
411 = getLclEnv `thenM` \ (TcLclEnv {tcl_tyvars = gtv_var}) ->
412 readMutVar gtv_var `thenM` \ gbl_tvs ->
413 zonkTcTyVarsAndFV (varSetElems gbl_tvs) `thenM` \ gbl_tvs' ->
414 writeMutVar gtv_var gbl_tvs' `thenM_`
419 %************************************************************************
423 %************************************************************************
426 tcExtendRules :: [LRuleDecl Id] -> TcM a -> TcM a
427 -- Just pop the new rules into the EPS and envt resp
428 -- All the rules come from an interface file, not soruce
429 -- Nevertheless, some may be for this module, if we read
430 -- its interface instead of its source code
431 tcExtendRules lcl_rules thing_inside
432 = do { env <- getGblEnv
434 env' = env { tcg_rules = lcl_rules ++ tcg_rules env }
435 ; setGblEnv env' thing_inside }
439 %************************************************************************
441 Arrow notation proc levels
443 %************************************************************************
446 checkProcLevel :: TcId -> ProcLevel -> TcM ()
447 checkProcLevel id id_lvl
448 = do { banned <- getBannedProcLevels
449 ; checkTc (not (id_lvl `elem` banned))
450 (procLevelErr id id_lvl) }
452 procLevelErr id id_lvl
453 = hang (ptext SLIT("Command-bound variable") <+> quotes (ppr id) <+> ptext SLIT("is not in scope here"))
454 4 (ptext SLIT("Reason: it is used in the left argument of (-<)"))
458 %************************************************************************
462 %************************************************************************
465 instance Outputable ThStage where
466 ppr Comp = text "Comp"
467 ppr (Brack l _ _) = text "Brack" <+> int l
468 ppr (Splice l) = text "Splice" <+> int l
471 thLevel :: ThStage -> ThLevel
472 thLevel Comp = topLevel
473 thLevel (Splice l) = l
474 thLevel (Brack l _ _) = l
477 checkWellStaged :: SDoc -- What the stage check is for
478 -> ThLevel -- Binding level
479 -> ThStage -- Use stage
480 -> TcM () -- Fail if badly staged, adding an error
481 checkWellStaged pp_thing bind_lvl use_stage
482 | bind_lvl <= use_lvl -- OK!
485 | bind_lvl == topLevel -- GHC restriction on top level splices
487 sep [ptext SLIT("GHC stage restriction:") <+> pp_thing,
488 nest 2 (ptext SLIT("is used in a top-level splice, and must be imported, not defined locally"))]
490 | otherwise -- Badly staged
492 ptext SLIT("Stage error:") <+> pp_thing <+>
493 hsep [ptext SLIT("is bound at stage") <+> ppr bind_lvl,
494 ptext SLIT("but used at stage") <+> ppr use_lvl]
496 use_lvl = thLevel use_stage
499 topIdLvl :: Id -> ThLevel
500 -- Globals may either be imported, or may be from an earlier "chunk"
501 -- (separated by declaration splices) of this module. The former
502 -- *can* be used inside a top-level splice, but the latter cannot.
503 -- Hence we give the former impLevel, but the latter topLevel
507 -- By the time we are prcessing the $(f x), the binding for "x"
508 -- will be in the global env, not the local one.
509 topIdLvl id | isLocalId id = topLevel
510 | otherwise = impLevel
512 -- Indicates the legal transitions on bracket( [| |] ).
513 bracketOK :: ThStage -> Maybe ThLevel
514 bracketOK (Brack _ _ _) = Nothing -- Bracket illegal inside a bracket
515 bracketOK stage = (Just (thLevel stage + 1))
517 -- Indicates the legal transitions on splice($).
518 spliceOK :: ThStage -> Maybe ThLevel
519 spliceOK (Splice _) = Nothing -- Splice illegal inside splice
520 spliceOK stage = Just (thLevel stage - 1)
522 tcMetaTy :: Name -> TcM Type
523 -- Given the name of a Template Haskell data type,
525 -- E.g. given the name "Expr" return the type "Expr"
527 = tcLookupTyCon tc_name `thenM` \ t ->
528 returnM (mkGenTyConApp t [])
529 -- Use mkGenTyConApp because it might be a synonym
533 %************************************************************************
535 \subsection{Making new Ids}
537 %************************************************************************
542 newLocalName :: Name -> TcM Name
543 newLocalName name -- Make a clone
544 = newUnique `thenM` \ uniq ->
545 returnM (mkInternalName uniq (getOccName name) (getSrcLoc name))
548 Make a name for the dict fun for an instance decl. It's a *local*
549 name for the moment. The CoreTidy pass will externalise it. Even in
550 --make and ghci stuff, we rebuild the instance environment each time,
551 so the dfun id is internal to begin with, and external when compiling
555 newDFunName :: Class -> [Type] -> SrcLoc -> TcM Name
556 newDFunName clas (ty:_) loc
557 = newUnique `thenM` \ uniq ->
558 returnM (mkInternalName uniq (mkDFunOcc dfun_string) loc)
560 -- Any string that is somewhat unique will do
561 dfun_string = occNameString (getOccName clas) ++ occNameString (getDFunTyKey ty)
563 newDFunName clas [] loc = pprPanic "newDFunName" (ppr clas <+> ppr loc)
567 %************************************************************************
569 \subsection{The InstInfo type}
571 %************************************************************************
573 The InstInfo type summarises the information in an instance declaration
575 instance c => k (t tvs) where b
577 It is used just for *local* instance decls (not ones from interface files).
578 But local instance decls includes
581 as well as explicit user written ones.
586 iDFunId :: DFunId, -- The dfun id
587 iBinds :: InstBindings
591 = VanillaInst -- The normal case
592 (LHsBinds Name) -- Bindings
593 [LSig Name] -- User pragmas recorded for generating
594 -- specialised instances
596 | NewTypeDerived -- Used for deriving instances of newtypes, where the
597 [Type] -- witness dictionary is identical to the argument
598 -- dictionary. Hence no bindings, no pragmas
599 -- The [Type] are the representation types
600 -- See notes in TcDeriv
602 pprInstInfo info = vcat [ptext SLIT("InstInfo:") <+> ppr (idType (iDFunId info))]
604 pprInstInfoDetails info = pprInstInfo info $$ nest 2 (details (iBinds info))
606 details (VanillaInst b _) = ppr b
607 details (NewTypeDerived _) = text "Derived from the representation type"
609 simpleInstInfoTy :: InstInfo -> Type
610 simpleInstInfoTy info = case tcSplitDFunTy (idType (iDFunId info)) of
611 (_, _, _, [ty]) -> ty
613 simpleInstInfoTyCon :: InstInfo -> TyCon
614 -- Gets the type constructor for a simple instance declaration,
615 -- i.e. one of the form instance (...) => C (T a b c) where ...
616 simpleInstInfoTyCon inst = tcTyConAppTyCon (simpleInstInfoTy inst)
620 %************************************************************************
624 %************************************************************************
627 notFound wheRe name = failWithTc (text wheRe <> colon <+> quotes (ppr name) <+>
628 ptext SLIT("is not in scope"))