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,
29 tcExtendRecEnv, -- For knot-tying
34 -- Global type variables
37 -- Template Haskell stuff
38 checkWellStaged, spliceOK, bracketOK, tcMetaTy, thLevel,
45 newLocalName, newDFunName
48 #include "HsVersions.h"
50 import HsSyn ( LRuleDecl, LHsBinds, LSig )
51 import TcIface ( tcImportDecl )
53 import TcMType ( zonkTcType, zonkTcTyVar, zonkTcTyVarsAndFV )
54 import TcType ( Type, TcKind, 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, 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, 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 ->
133 AClass cls -> return cls
134 other -> wrongThingErr "class" (AGlobal thing) name
136 tcLookupTyCon :: Name -> TcM TyCon
138 = tcLookupGlobal name `thenM` \ thing ->
140 ATyCon tc -> return tc
141 other -> wrongThingErr "type constructor" (AGlobal thing) name
143 tcLookupLocatedGlobalId :: Located Name -> TcM Id
144 tcLookupLocatedGlobalId = addLocM tcLookupId
146 tcLookupLocatedDataCon :: Located Name -> TcM DataCon
147 tcLookupLocatedDataCon = addLocM tcLookupDataCon
149 tcLookupLocatedClass :: Located Name -> TcM Class
150 tcLookupLocatedClass = addLocM tcLookupClass
152 tcLookupLocatedTyCon :: Located Name -> TcM TyCon
153 tcLookupLocatedTyCon = addLocM tcLookupTyCon
156 %************************************************************************
158 Extending the global environment
160 %************************************************************************
164 tcExtendGlobalEnv :: [TyThing] -> TcM r -> TcM r
165 -- Given a mixture of Ids, TyCons, Classes, all from the
166 -- module being compiled, extend the global environment
167 tcExtendGlobalEnv things thing_inside
168 = do { env <- getGblEnv
169 ; let ge' = extendTypeEnvList (tcg_type_env env) things
170 ; setGblEnv (env {tcg_type_env = ge'}) thing_inside }
172 tcExtendGlobalValEnv :: [Id] -> TcM a -> TcM a
173 -- Same deal as tcExtendGlobalEnv, but for Ids
174 tcExtendGlobalValEnv ids thing_inside
175 = tcExtendGlobalEnv [AnId id | id <- ids] thing_inside
178 A variety of global lookups, when we know what we are looking for.
181 getInGlobalScope :: TcM (Name -> Bool)
182 -- Get all things in the global environment; used for deciding what
183 -- rules to suck in. Anything defined in this module (nameIsLocalOrFrom)
184 -- is certainly in the envt, so we don't bother to look.
186 = do { mod <- getModule
189 ; return (\n -> nameIsLocalOrFrom mod n ||
190 isJust (lookupType hpt (eps_PTE eps) n)) }
195 tcExtendRecEnv :: [(Name,TyThing)] -> TcM r -> TcM r
196 -- Extend the global environments for the type/class knot tying game
197 tcExtendRecEnv gbl_stuff thing_inside
198 = updGblEnv upd thing_inside
200 upd env = env { tcg_type_env = extend (tcg_type_env env) }
201 extend env = extendNameEnvList env gbl_stuff
205 %************************************************************************
207 \subsection{The local environment}
209 %************************************************************************
212 tcLookupLocated :: Located Name -> TcM TcTyThing
213 tcLookupLocated = addLocM tcLookup
215 tcLookup :: Name -> TcM TcTyThing
217 = getLclEnv `thenM` \ local_env ->
218 case lookupNameEnv (tcl_env local_env) name of
219 Just thing -> returnM thing
220 Nothing -> tcLookupGlobal name `thenM` \ thing ->
221 returnM (AGlobal thing)
223 tcLookupTyVar :: Name -> TcM Id
225 = tcLookup name `thenM` \ thing ->
227 ATyVar tv -> returnM tv
228 other -> pprPanic "tcLookupTyVar" (ppr name)
230 tcLookupId :: Name -> TcM Id
231 -- Used when we aren't interested in the binding level
232 -- Never a DataCon. (Why does that matter? see TcExpr.tcId)
234 = tcLookup name `thenM` \ thing ->
236 ATcId tc_id _ _ -> returnM tc_id
237 AGlobal (AnId id) -> returnM id
238 other -> pprPanic "tcLookupId" (ppr name)
240 tcLookupLocalIds :: [Name] -> TcM [TcId]
241 -- We expect the variables to all be bound, and all at
242 -- the same level as the lookup. Only used in one place...
244 = getLclEnv `thenM` \ env ->
245 returnM (map (lookup (tcl_env env) (thLevel (tcl_th_ctxt env))) ns)
248 = case lookupNameEnv lenv name of
249 Just (ATcId id lvl1 _) -> ASSERT( lvl == lvl1 ) id
250 other -> pprPanic "tcLookupLocalIds" (ppr name)
252 lclEnvElts :: TcLclEnv -> [TcTyThing]
253 lclEnvElts env = nameEnvElts (tcl_env env)
255 getInLocalScope :: TcM (Name -> Bool)
257 getInLocalScope = getLclEnv `thenM` \ env ->
259 lcl_env = tcl_env env
261 return (`elemNameEnv` lcl_env)
265 tcExtendKindEnv :: [(Name, TcKind)] -> TcM r -> TcM r
266 tcExtendKindEnv things 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, AThing k) | (n,k) <- things]
272 tcExtendTyVarEnv :: [TyVar] -> TcM r -> TcM r
273 tcExtendTyVarEnv tvs thing_inside
274 = tc_extend_tv_env [(getName tv, ATyVar tv) | tv <- tvs] tvs thing_inside
276 tcExtendTyVarEnv2 :: [(TyVar,TcTyVar)] -> TcM r -> TcM r
277 tcExtendTyVarEnv2 tv_pairs thing_inside
278 = tc_extend_tv_env [(getName tv1, ATyVar tv2) | (tv1,tv2) <- tv_pairs]
279 [tv | (_,tv) <- tv_pairs]
282 tc_extend_tv_env binds tyvars thing_inside
283 = getLclEnv `thenM` \ env@(TcLclEnv {tcl_env = le,
285 tcl_rdr = rdr_env}) ->
287 le' = extendNameEnvList le binds
288 rdr_env' = extendLocalRdrEnv rdr_env (map fst binds)
289 new_tv_set = mkVarSet tyvars
291 -- It's important to add the in-scope tyvars to the global tyvar set
293 -- f (_::r) = let g y = y::r in ...
294 -- Here, g mustn't be generalised. This is also important during
295 -- class and instance decls, when we mustn't generalise the class tyvars
296 -- when typechecking the methods.
297 tc_extend_gtvs gtvs new_tv_set `thenM` \ gtvs' ->
298 setLclEnv (env {tcl_env = le', tcl_tyvars = gtvs', tcl_rdr = rdr_env'}) thing_inside
303 tcExtendLocalValEnv :: [TcId] -> TcM a -> TcM a
304 tcExtendLocalValEnv ids thing_inside
305 = getLclEnv `thenM` \ env ->
307 extra_global_tyvars = tyVarsOfTypes [idType id | id <- ids]
308 th_lvl = thLevel (tcl_th_ctxt env)
309 proc_lvl = proc_level (tcl_arrow_ctxt env)
310 extra_env = [(idName id, ATcId id th_lvl proc_lvl) | id <- ids]
311 le' = extendNameEnvList (tcl_env env) extra_env
312 rdr_env' = extendLocalRdrEnv (tcl_rdr env) (map idName ids)
314 tc_extend_gtvs (tcl_tyvars env) extra_global_tyvars `thenM` \ gtvs' ->
315 setLclEnv (env {tcl_env = le', tcl_tyvars = gtvs', tcl_rdr = rdr_env'}) thing_inside
317 tcExtendLocalValEnv2 :: [(Name,TcId)] -> TcM a -> TcM a
318 tcExtendLocalValEnv2 names_w_ids thing_inside
319 = getLclEnv `thenM` \ env ->
321 extra_global_tyvars = tyVarsOfTypes [idType id | (name,id) <- names_w_ids]
322 th_lvl = thLevel (tcl_th_ctxt env)
323 proc_lvl = proc_level (tcl_arrow_ctxt env)
324 extra_env = [(name, ATcId id th_lvl proc_lvl) | (name,id) <- names_w_ids]
325 le' = extendNameEnvList (tcl_env env) extra_env
326 rdr_env' = extendLocalRdrEnv (tcl_rdr env) (map fst names_w_ids)
328 tc_extend_gtvs (tcl_tyvars env) extra_global_tyvars `thenM` \ gtvs' ->
329 setLclEnv (env {tcl_env = le', tcl_tyvars = gtvs', tcl_rdr = rdr_env'}) thing_inside
334 -----------------------
335 -- findGlobals looks at the value environment and finds values
336 -- whose types mention the offending type variable. It has to be
337 -- careful to zonk the Id's type first, so it has to be in the monad.
338 -- We must be careful to pass it a zonked type variable, too.
340 findGlobals :: TcTyVarSet
342 -> TcM (TidyEnv, [SDoc])
344 findGlobals tvs tidy_env
345 = getLclEnv `thenM` \ lcl_env ->
346 go tidy_env [] (lclEnvElts lcl_env)
348 go tidy_env acc [] = returnM (tidy_env, acc)
349 go tidy_env acc (thing : things)
350 = find_thing ignore_it tidy_env thing `thenM` \ (tidy_env1, maybe_doc) ->
352 Just d -> go tidy_env1 (d:acc) things
353 Nothing -> go tidy_env1 acc things
355 ignore_it ty = not (tvs `intersectsVarSet` tyVarsOfType ty)
357 -----------------------
358 find_thing ignore_it tidy_env (ATcId id _ _)
359 = zonkTcType (idType id) `thenM` \ id_ty ->
360 if ignore_it id_ty then
361 returnM (tidy_env, Nothing)
363 (tidy_env', tidy_ty) = tidyOpenType tidy_env id_ty
364 msg = sep [ppr id <+> dcolon <+> ppr tidy_ty,
365 nest 2 (parens (ptext SLIT("bound at") <+>
366 ppr (getSrcLoc id)))]
368 returnM (tidy_env', Just msg)
370 find_thing ignore_it tidy_env (ATyVar tv)
371 = zonkTcTyVar tv `thenM` \ tv_ty ->
372 if ignore_it tv_ty then
373 returnM (tidy_env, Nothing)
375 (tidy_env1, tv1) = tidyOpenTyVar tidy_env tv
376 (tidy_env2, tidy_ty) = tidyOpenType tidy_env1 tv_ty
377 msg = sep [ppr tv1 <+> eq_stuff, nest 2 bound_at]
379 eq_stuff | Just tv' <- Type.getTyVar_maybe tv_ty,
381 | otherwise = equals <+> ppr tidy_ty
382 -- It's ok to use Type.getTyVar_maybe because ty is zonked by now
384 bound_at = tyVarBindingInfo tv
386 returnM (tidy_env2, Just msg)
390 %************************************************************************
392 \subsection{The global tyvars}
394 %************************************************************************
397 tc_extend_gtvs gtvs extra_global_tvs
398 = readMutVar gtvs `thenM` \ global_tvs ->
399 newMutVar (global_tvs `unionVarSet` extra_global_tvs)
402 @tcGetGlobalTyVars@ returns a fully-zonked set of tyvars free in the environment.
403 To improve subsequent calls to the same function it writes the zonked set back into
407 tcGetGlobalTyVars :: TcM TcTyVarSet
409 = getLclEnv `thenM` \ (TcLclEnv {tcl_tyvars = gtv_var}) ->
410 readMutVar gtv_var `thenM` \ gbl_tvs ->
411 zonkTcTyVarsAndFV (varSetElems gbl_tvs) `thenM` \ gbl_tvs' ->
412 writeMutVar gtv_var gbl_tvs' `thenM_`
417 %************************************************************************
421 %************************************************************************
424 tcExtendRules :: [LRuleDecl Id] -> TcM a -> TcM a
425 -- Just pop the new rules into the EPS and envt resp
426 -- All the rules come from an interface file, not soruce
427 -- Nevertheless, some may be for this module, if we read
428 -- its interface instead of its source code
429 tcExtendRules lcl_rules thing_inside
430 = do { env <- getGblEnv
432 env' = env { tcg_rules = lcl_rules ++ tcg_rules env }
433 ; setGblEnv env' thing_inside }
437 %************************************************************************
439 Arrow notation proc levels
441 %************************************************************************
444 checkProcLevel :: TcId -> ProcLevel -> TcM ()
445 checkProcLevel id id_lvl
446 = do { banned <- getBannedProcLevels
447 ; checkTc (not (id_lvl `elem` banned))
448 (procLevelErr id id_lvl) }
450 procLevelErr id id_lvl
451 = hang (ptext SLIT("Command-bound variable") <+> quotes (ppr id) <+> ptext SLIT("is not in scope here"))
452 4 (ptext SLIT("Reason: it is used in the left argument of (-<)"))
456 %************************************************************************
460 %************************************************************************
463 instance Outputable ThStage where
464 ppr Comp = text "Comp"
465 ppr (Brack l _ _) = text "Brack" <+> int l
466 ppr (Splice l) = text "Splice" <+> int l
469 thLevel :: ThStage -> ThLevel
470 thLevel Comp = topLevel
471 thLevel (Splice l) = l
472 thLevel (Brack l _ _) = l
475 checkWellStaged :: SDoc -- What the stage check is for
476 -> ThLevel -- Binding level
477 -> ThStage -- Use stage
478 -> TcM () -- Fail if badly staged, adding an error
479 checkWellStaged pp_thing bind_lvl use_stage
480 | bind_lvl <= use_lvl -- OK!
483 | bind_lvl == topLevel -- GHC restriction on top level splices
485 sep [ptext SLIT("GHC stage restriction:") <+> pp_thing,
486 nest 2 (ptext SLIT("is used in a top-level splice, and must be imported, not defined locally"))]
488 | otherwise -- Badly staged
490 ptext SLIT("Stage error:") <+> pp_thing <+>
491 hsep [ptext SLIT("is bound at stage") <+> ppr bind_lvl,
492 ptext SLIT("but used at stage") <+> ppr use_lvl]
494 use_lvl = thLevel use_stage
497 topIdLvl :: Id -> ThLevel
498 -- Globals may either be imported, or may be from an earlier "chunk"
499 -- (separated by declaration splices) of this module. The former
500 -- *can* be used inside a top-level splice, but the latter cannot.
501 -- Hence we give the former impLevel, but the latter topLevel
505 -- By the time we are prcessing the $(f x), the binding for "x"
506 -- will be in the global env, not the local one.
507 topIdLvl id | isLocalId id = topLevel
508 | otherwise = impLevel
510 -- Indicates the legal transitions on bracket( [| |] ).
511 bracketOK :: ThStage -> Maybe ThLevel
512 bracketOK (Brack _ _ _) = Nothing -- Bracket illegal inside a bracket
513 bracketOK stage = (Just (thLevel stage + 1))
515 -- Indicates the legal transitions on splice($).
516 spliceOK :: ThStage -> Maybe ThLevel
517 spliceOK (Splice _) = Nothing -- Splice illegal inside splice
518 spliceOK stage = Just (thLevel stage - 1)
520 tcMetaTy :: Name -> TcM Type
521 -- Given the name of a Template Haskell data type,
523 -- E.g. given the name "Expr" return the type "Expr"
525 = tcLookupTyCon tc_name `thenM` \ t ->
526 returnM (mkGenTyConApp t [])
527 -- Use mkGenTyConApp because it might be a synonym
531 %************************************************************************
533 \subsection{Making new Ids}
535 %************************************************************************
540 newLocalName :: Name -> TcM Name
541 newLocalName name -- Make a clone
542 = newUnique `thenM` \ uniq ->
543 returnM (mkInternalName uniq (getOccName name) (getSrcLoc name))
546 Make a name for the dict fun for an instance decl. It's a *local*
547 name for the moment. The CoreTidy pass will externalise it. Even in
548 --make and ghci stuff, we rebuild the instance environment each time,
549 so the dfun id is internal to begin with, and external when compiling
553 newDFunName :: Class -> [Type] -> SrcLoc -> TcM Name
554 newDFunName clas (ty:_) loc
555 = newUnique `thenM` \ uniq ->
556 returnM (mkInternalName uniq (mkDFunOcc dfun_string) loc)
558 -- Any string that is somewhat unique will do
559 dfun_string = occNameString (getOccName clas) ++ occNameString (getDFunTyKey ty)
561 newDFunName clas [] loc = pprPanic "newDFunName" (ppr clas <+> ppr loc)
565 %************************************************************************
567 \subsection{The InstInfo type}
569 %************************************************************************
571 The InstInfo type summarises the information in an instance declaration
573 instance c => k (t tvs) where b
575 It is used just for *local* instance decls (not ones from interface files).
576 But local instance decls includes
579 as well as explicit user written ones.
584 iDFunId :: DFunId, -- The dfun id
585 iBinds :: InstBindings
589 = VanillaInst -- The normal case
590 (LHsBinds Name) -- Bindings
591 [LSig Name] -- User pragmas recorded for generating
592 -- specialised instances
594 | NewTypeDerived -- Used for deriving instances of newtypes, where the
595 [Type] -- witness dictionary is identical to the argument
596 -- dictionary. Hence no bindings, no pragmas
597 -- The [Type] are the representation types
598 -- See notes in TcDeriv
600 pprInstInfo info = vcat [ptext SLIT("InstInfo:") <+> ppr (idType (iDFunId info))]
602 pprInstInfoDetails info = pprInstInfo info $$ nest 2 (details (iBinds info))
604 details (VanillaInst b _) = ppr b
605 details (NewTypeDerived _) = text "Derived from the representation type"
607 simpleInstInfoTy :: InstInfo -> Type
608 simpleInstInfoTy info = case tcSplitDFunTy (idType (iDFunId info)) of
609 (_, _, _, [ty]) -> ty
611 simpleInstInfoTyCon :: InstInfo -> TyCon
612 -- Gets the type constructor for a simple instance declaration,
613 -- i.e. one of the form instance (...) => C (T a b c) where ...
614 simpleInstInfoTyCon inst = tcTyConAppTyCon (simpleInstInfoTy inst)
618 %************************************************************************
622 %************************************************************************
625 notFound wheRe name = failWithTc (text wheRe <> colon <+> quotes (ppr name) <+>
626 ptext SLIT("is not in scope"))
628 wrongThingErr expected thing name
629 = failWithTc (pp_thing thing <+> quotes (ppr name) <+>
630 ptext SLIT("used as a") <+> text expected)
632 pp_thing (AGlobal (ATyCon _)) = ptext SLIT("Type constructor")
633 pp_thing (AGlobal (AClass _)) = ptext SLIT("Class")
634 pp_thing (AGlobal (AnId _)) = ptext SLIT("Identifier")
635 pp_thing (AGlobal (ADataCon _)) = ptext SLIT("Data constructor")
636 pp_thing (ATyVar _) = ptext SLIT("Type variable")
637 pp_thing (ATcId _ _ _) = ptext SLIT("Local identifier")