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,
20 tcExtendTyVarEnv, tcExtendTyVarEnv2,
21 tcExtendIdEnv, tcExtendIdEnv1, tcExtendIdEnv2,
22 tcLookup, tcLookupLocated, tcLookupLocalIds,
23 tcLookupId, tcLookupTyVar,
24 lclEnvElts, getInLocalScope, findGlobals,
27 tcExtendRecEnv, -- For knot-tying
32 -- Global type variables
35 -- Template Haskell stuff
36 checkWellStaged, spliceOK, bracketOK, tcMetaTy, thLevel,
43 newLocalName, newDFunName
46 #include "HsVersions.h"
48 import HsSyn ( LRuleDecl, LHsBinds, LSig, pprLHsBinds )
49 import TcIface ( tcImportDecl )
51 import TcMType ( zonkTcType, zonkTcTyVar, zonkTcTyVarsAndFV )
52 import TcType ( Type, TcKind, TcTyVar, TcTyVarSet,
53 tyVarsOfType, tyVarsOfTypes, tcSplitDFunTy, mkGenTyConApp,
54 getDFunTyKey, tcTyConAppTyCon,
55 tidyOpenType, tidyOpenTyVar, pprTyThingCategory
57 import qualified Type ( getTyVar_maybe )
58 import Id ( idName, isLocalId )
59 import Var ( TyVar, Id, idType )
62 import RdrName ( extendLocalRdrEnv )
63 import DataCon ( DataCon )
64 import TyCon ( TyCon )
65 import Class ( Class )
66 import Name ( Name, NamedThing(..), getSrcLoc, mkInternalName, nameIsLocalOrFrom )
68 import OccName ( mkDFunOcc, occNameString )
69 import HscTypes ( DFunId, extendTypeEnvList, lookupType,
70 TyThing(..), tyThingId, tyThingDataCon,
71 ExternalPackageState(..) )
73 import SrcLoc ( SrcLoc, Located(..) )
78 %************************************************************************
82 %************************************************************************
84 Using the Located versions (eg. tcLookupLocatedGlobal) is preferred,
85 unless you know that the SrcSpan in the monad is already set to the
89 tcLookupLocatedGlobal :: Located Name -> TcM TyThing
90 -- c.f. IfaceEnvEnv.tcIfaceGlobal
91 tcLookupLocatedGlobal name
92 = addLocM tcLookupGlobal name
94 tcLookupGlobal :: Name -> TcM TyThing
96 = do { env <- getGblEnv
97 ; if nameIsLocalOrFrom (tcg_mod env) name
99 then -- It's defined in this module
100 case lookupNameEnv (tcg_type_env env) name of
101 Just thing -> return thing
102 Nothing -> notFound name -- Panic!
104 else do -- It's imported
105 { (eps,hpt) <- getEpsAndHpt
106 ; case lookupType hpt (eps_PTE eps) name of
107 Just thing -> return thing
108 Nothing -> do { traceIf (text "tcLookupGlobal" <+> ppr name)
109 ; initIfaceTcRn (tcImportDecl name) }
114 tcLookupGlobalId :: Name -> TcM Id
115 -- Never used for Haskell-source DataCons, hence no ADataCon case
116 tcLookupGlobalId name
117 = tcLookupGlobal name `thenM` \ thing ->
118 return (tyThingId thing)
120 tcLookupDataCon :: Name -> TcM DataCon
121 tcLookupDataCon con_name
122 = tcLookupGlobal con_name `thenM` \ thing ->
123 return (tyThingDataCon thing)
125 tcLookupClass :: Name -> TcM Class
127 = tcLookupGlobal name `thenM` \ thing ->
129 AClass cls -> return cls
130 other -> wrongThingErr "class" (AGlobal thing) name
132 tcLookupTyCon :: Name -> TcM TyCon
134 = tcLookupGlobal name `thenM` \ thing ->
136 ATyCon tc -> return tc
137 other -> wrongThingErr "type constructor" (AGlobal thing) name
139 tcLookupLocatedGlobalId :: Located Name -> TcM Id
140 tcLookupLocatedGlobalId = addLocM tcLookupId
142 tcLookupLocatedClass :: Located Name -> TcM Class
143 tcLookupLocatedClass = addLocM tcLookupClass
145 tcLookupLocatedTyCon :: Located Name -> TcM TyCon
146 tcLookupLocatedTyCon = addLocM tcLookupTyCon
149 %************************************************************************
151 Extending the global environment
153 %************************************************************************
157 tcExtendGlobalEnv :: [TyThing] -> TcM r -> TcM r
158 -- Given a mixture of Ids, TyCons, Classes, all from the
159 -- module being compiled, extend the global environment
160 tcExtendGlobalEnv things thing_inside
161 = do { env <- getGblEnv
162 ; let ge' = extendTypeEnvList (tcg_type_env env) things
163 ; setGblEnv (env {tcg_type_env = ge'}) thing_inside }
165 tcExtendGlobalValEnv :: [Id] -> TcM a -> TcM a
166 -- Same deal as tcExtendGlobalEnv, but for Ids
167 tcExtendGlobalValEnv ids thing_inside
168 = tcExtendGlobalEnv [AnId id | id <- ids] thing_inside
172 tcExtendRecEnv :: [(Name,TyThing)] -> TcM r -> TcM r
173 -- Extend the global environments for the type/class knot tying game
174 tcExtendRecEnv gbl_stuff thing_inside
175 = updGblEnv upd thing_inside
177 upd env = env { tcg_type_env = extend (tcg_type_env env) }
178 extend env = extendNameEnvList env gbl_stuff
182 %************************************************************************
184 \subsection{The local environment}
186 %************************************************************************
189 tcLookupLocated :: Located Name -> TcM TcTyThing
190 tcLookupLocated = addLocM tcLookup
192 tcLookup :: Name -> TcM TcTyThing
194 = getLclEnv `thenM` \ local_env ->
195 case lookupNameEnv (tcl_env local_env) name of
196 Just thing -> returnM thing
197 Nothing -> tcLookupGlobal name `thenM` \ thing ->
198 returnM (AGlobal thing)
200 tcLookupTyVar :: Name -> TcM Id
202 = tcLookup name `thenM` \ thing ->
204 ATyVar tv -> returnM tv
205 other -> pprPanic "tcLookupTyVar" (ppr name)
207 tcLookupId :: Name -> TcM Id
208 -- Used when we aren't interested in the binding level
209 -- Never a DataCon. (Why does that matter? see TcExpr.tcId)
211 = tcLookup name `thenM` \ thing ->
213 ATcId tc_id _ _ -> returnM tc_id
214 AGlobal (AnId id) -> returnM id
215 other -> pprPanic "tcLookupId" (ppr name)
217 tcLookupLocalIds :: [Name] -> TcM [TcId]
218 -- We expect the variables to all be bound, and all at
219 -- the same level as the lookup. Only used in one place...
221 = getLclEnv `thenM` \ env ->
222 returnM (map (lookup (tcl_env env) (thLevel (tcl_th_ctxt env))) ns)
225 = case lookupNameEnv lenv name of
226 Just (ATcId id lvl1 _) -> ASSERT( lvl == lvl1 ) id
227 other -> pprPanic "tcLookupLocalIds" (ppr name)
229 lclEnvElts :: TcLclEnv -> [TcTyThing]
230 lclEnvElts env = nameEnvElts (tcl_env env)
232 getInLocalScope :: TcM (Name -> Bool)
234 getInLocalScope = getLclEnv `thenM` \ env ->
236 lcl_env = tcl_env env
238 return (`elemNameEnv` lcl_env)
242 tcExtendKindEnv :: [(Name, TcKind)] -> TcM r -> TcM r
243 tcExtendKindEnv things thing_inside
244 = updLclEnv upd thing_inside
246 upd lcl_env = lcl_env { tcl_env = extend (tcl_env lcl_env) }
247 extend env = extendNameEnvList env [(n, AThing k) | (n,k) <- things]
249 tcExtendTyVarEnv :: [TyVar] -> TcM r -> TcM r
250 tcExtendTyVarEnv tvs thing_inside
251 = tc_extend_tv_env [(getName tv, ATyVar tv) | tv <- tvs] tvs thing_inside
253 tcExtendTyVarEnv2 :: [(TyVar,TcTyVar)] -> TcM r -> TcM r
254 tcExtendTyVarEnv2 tv_pairs thing_inside
255 = tc_extend_tv_env [(getName tv1, ATyVar tv2) | (tv1,tv2) <- tv_pairs]
256 [tv | (_,tv) <- tv_pairs]
259 tc_extend_tv_env binds tyvars thing_inside
260 = getLclEnv `thenM` \ env@(TcLclEnv {tcl_env = le,
262 tcl_rdr = rdr_env}) ->
264 le' = extendNameEnvList le binds
265 rdr_env' = extendLocalRdrEnv rdr_env (map fst binds)
266 new_tv_set = mkVarSet tyvars
268 -- It's important to add the in-scope tyvars to the global tyvar set
270 -- f (_::r) = let g y = y::r in ...
271 -- Here, g mustn't be generalised. This is also important during
272 -- class and instance decls, when we mustn't generalise the class tyvars
273 -- when typechecking the methods.
274 tc_extend_gtvs gtvs new_tv_set `thenM` \ gtvs' ->
275 setLclEnv (env {tcl_env = le', tcl_tyvars = gtvs', tcl_rdr = rdr_env'}) thing_inside
280 tcExtendIdEnv :: [TcId] -> TcM a -> TcM a
281 -- Invariant: the TcIds are fully zonked. Reasons:
282 -- (a) The kinds of the forall'd type variables are defaulted
283 -- (see Kind.defaultKind, done in zonkQuantifiedTyVar)
284 -- (b) There are no via-Indirect occurrences of the bound variables
285 -- in the types, because instantiation does not look through such things
286 -- (c) The call to tyVarsOfTypes is ok without looking through refs
287 tcExtendIdEnv ids thing_inside = tcExtendIdEnv2 [(idName id, id) | id <- ids] thing_inside
289 tcExtendIdEnv1 :: Name -> TcId -> TcM a -> TcM a
290 tcExtendIdEnv1 name id thing_inside = tcExtendIdEnv2 [(name,id)] thing_inside
292 tcExtendIdEnv2 :: [(Name,TcId)] -> TcM a -> TcM a
293 -- Invariant: the TcIds are fully zonked (see tcExtendIdEnv above)
294 tcExtendIdEnv2 names_w_ids thing_inside
295 = getLclEnv `thenM` \ env ->
297 extra_global_tyvars = tyVarsOfTypes [idType id | (name,id) <- names_w_ids]
298 th_lvl = thLevel (tcl_th_ctxt env)
299 proc_lvl = proc_level (tcl_arrow_ctxt env)
300 extra_env = [(name, ATcId id th_lvl proc_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)
347 = zonkTcTyVar tv `thenM` \ tv_ty ->
348 if ignore_it tv_ty then
349 returnM (tidy_env, Nothing)
351 (tidy_env1, tv1) = tidyOpenTyVar tidy_env tv
352 (tidy_env2, tidy_ty) = tidyOpenType tidy_env1 tv_ty
353 msg = sep [ppr tv1 <+> eq_stuff, nest 2 bound_at]
355 eq_stuff | Just tv' <- Type.getTyVar_maybe tv_ty,
357 | otherwise = equals <+> ppr tidy_ty
358 -- It's ok to use Type.getTyVar_maybe because ty is zonked by now
359 bound_at = ptext SLIT("bound at:") <+> ppr (getSrcLoc tv)
361 returnM (tidy_env2, 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 %************************************************************************
414 Arrow notation proc levels
416 %************************************************************************
419 checkProcLevel :: TcId -> ProcLevel -> TcM ()
420 checkProcLevel id id_lvl
421 = do { banned <- getBannedProcLevels
422 ; checkTc (not (id_lvl `elem` banned))
423 (procLevelErr id id_lvl) }
425 procLevelErr id id_lvl
426 = hang (ptext SLIT("Command-bound variable") <+> quotes (ppr id) <+> ptext SLIT("is not in scope here"))
427 4 (ptext SLIT("Reason: it is used in the left argument of (-<)"))
431 %************************************************************************
435 %************************************************************************
438 instance Outputable ThStage where
439 ppr Comp = text "Comp"
440 ppr (Brack l _ _) = text "Brack" <+> int l
441 ppr (Splice l) = text "Splice" <+> int l
444 thLevel :: ThStage -> ThLevel
445 thLevel Comp = topLevel
446 thLevel (Splice l) = l
447 thLevel (Brack l _ _) = l
450 checkWellStaged :: SDoc -- What the stage check is for
451 -> ThLevel -- Binding level
452 -> ThStage -- Use stage
453 -> TcM () -- Fail if badly staged, adding an error
454 checkWellStaged pp_thing bind_lvl use_stage
455 | bind_lvl <= use_lvl -- OK!
458 | bind_lvl == topLevel -- GHC restriction on top level splices
460 sep [ptext SLIT("GHC stage restriction:") <+> pp_thing,
461 nest 2 (ptext SLIT("is used in a top-level splice, and must be imported, not defined locally"))]
463 | otherwise -- Badly staged
465 ptext SLIT("Stage error:") <+> pp_thing <+>
466 hsep [ptext SLIT("is bound at stage") <+> ppr bind_lvl,
467 ptext SLIT("but used at stage") <+> ppr use_lvl]
469 use_lvl = thLevel use_stage
472 topIdLvl :: Id -> ThLevel
473 -- Globals may either be imported, or may be from an earlier "chunk"
474 -- (separated by declaration splices) of this module. The former
475 -- *can* be used inside a top-level splice, but the latter cannot.
476 -- Hence we give the former impLevel, but the latter topLevel
480 -- By the time we are prcessing the $(f x), the binding for "x"
481 -- will be in the global env, not the local one.
482 topIdLvl id | isLocalId id = topLevel
483 | otherwise = impLevel
485 -- Indicates the legal transitions on bracket( [| |] ).
486 bracketOK :: ThStage -> Maybe ThLevel
487 bracketOK (Brack _ _ _) = Nothing -- Bracket illegal inside a bracket
488 bracketOK stage = (Just (thLevel stage + 1))
490 -- Indicates the legal transitions on splice($).
491 spliceOK :: ThStage -> Maybe ThLevel
492 spliceOK (Splice _) = Nothing -- Splice illegal inside splice
493 spliceOK stage = Just (thLevel stage - 1)
495 tcMetaTy :: Name -> TcM Type
496 -- Given the name of a Template Haskell data type,
498 -- E.g. given the name "Expr" return the type "Expr"
500 = tcLookupTyCon tc_name `thenM` \ t ->
501 returnM (mkGenTyConApp t [])
502 -- Use mkGenTyConApp because it might be a synonym
506 %************************************************************************
508 \subsection{Making new Ids}
510 %************************************************************************
515 newLocalName :: Name -> TcM Name
516 newLocalName name -- Make a clone
517 = newUnique `thenM` \ uniq ->
518 returnM (mkInternalName uniq (getOccName name) (getSrcLoc name))
521 Make a name for the dict fun for an instance decl. It's a *local*
522 name for the moment. The CoreTidy pass will externalise it. Even in
523 --make and ghci stuff, we rebuild the instance environment each time,
524 so the dfun id is internal to begin with, and external when compiling
528 newDFunName :: Class -> [Type] -> SrcLoc -> TcM Name
529 newDFunName clas (ty:_) loc
530 = newUnique `thenM` \ uniq ->
531 returnM (mkInternalName uniq (mkDFunOcc dfun_string) loc)
533 -- Any string that is somewhat unique will do
534 dfun_string = occNameString (getOccName clas) ++ occNameString (getDFunTyKey ty)
536 newDFunName clas [] loc = pprPanic "newDFunName" (ppr clas <+> ppr loc)
540 %************************************************************************
542 \subsection{The InstInfo type}
544 %************************************************************************
546 The InstInfo type summarises the information in an instance declaration
548 instance c => k (t tvs) where b
550 It is used just for *local* instance decls (not ones from interface files).
551 But local instance decls includes
554 as well as explicit user written ones.
559 iDFunId :: DFunId, -- The dfun id
560 iBinds :: InstBindings
564 = VanillaInst -- The normal case
565 (LHsBinds Name) -- Bindings
566 [LSig Name] -- User pragmas recorded for generating
567 -- specialised instances
569 | NewTypeDerived -- Used for deriving instances of newtypes, where the
570 [Type] -- witness dictionary is identical to the argument
571 -- dictionary. Hence no bindings, no pragmas
572 -- The [Type] are the representation types
573 -- See notes in TcDeriv
575 pprInstInfo info = vcat [ptext SLIT("InstInfo:") <+> ppr (idType (iDFunId info))]
577 pprInstInfoDetails info = pprInstInfo info $$ nest 2 (details (iBinds info))
579 details (VanillaInst b _) = pprLHsBinds b
580 details (NewTypeDerived _) = text "Derived from the representation type"
582 simpleInstInfoTy :: InstInfo -> Type
583 simpleInstInfoTy info = case tcSplitDFunTy (idType (iDFunId info)) of
584 (_, _, _, [ty]) -> ty
586 simpleInstInfoTyCon :: InstInfo -> TyCon
587 -- Gets the type constructor for a simple instance declaration,
588 -- i.e. one of the form instance (...) => C (T a b c) where ...
589 simpleInstInfoTyCon inst = tcTyConAppTyCon (simpleInstInfoTy inst)
593 %************************************************************************
597 %************************************************************************
601 = failWithTc (ptext SLIT("GHC internal error:") <+> quotes (ppr name) <+>
602 ptext SLIT("is not in scope"))
604 wrongThingErr expected thing name
605 = failWithTc (pp_thing thing <+> quotes (ppr name) <+>
606 ptext SLIT("used as a") <+> text expected)
608 pp_thing (AGlobal thing) = pprTyThingCategory thing
609 pp_thing (ATyVar _) = ptext SLIT("Type variable")
610 pp_thing (ATcId _ _ _) = ptext SLIT("Local identifier")