Add nakedSubstTy and use it in TcHsType.tcInferApps
[ghc.git] / compiler / typecheck / TcEnv.hs
1 -- (c) The University of Glasgow 2006
2 {-# LANGUAGE CPP, FlexibleInstances #-}
3 {-# LANGUAGE FlexibleContexts #-}
4 {-# OPTIONS_GHC -fno-warn-orphans #-} -- instance MonadThings is necessarily an
5 -- orphan
6 {-# LANGUAGE UndecidableInstances #-} -- Note [Pass sensitive types]
7 -- in module PlaceHolder
8
9 module TcEnv(
10 TyThing(..), TcTyThing(..), TcId,
11
12 -- Instance environment, and InstInfo type
13 InstInfo(..), iDFunId, pprInstInfoDetails,
14 simpleInstInfoClsTy, simpleInstInfoTy, simpleInstInfoTyCon,
15 InstBindings(..),
16
17 -- Global environment
18 tcExtendGlobalEnv, tcExtendTyConEnv,
19 tcExtendGlobalEnvImplicit, setGlobalTypeEnv,
20 tcExtendGlobalValEnv,
21 tcLookupLocatedGlobal, tcLookupGlobal,
22 tcLookupTyCon, tcLookupClass,
23 tcLookupDataCon, tcLookupPatSyn, tcLookupConLike,
24 tcLookupLocatedGlobalId, tcLookupLocatedTyCon,
25 tcLookupLocatedClass, tcLookupAxiom,
26 lookupGlobal, ioLookupDataCon,
27
28 -- Local environment
29 tcExtendKindEnv, tcExtendKindEnvList,
30 tcExtendTyVarEnv, tcExtendNameTyVarEnv,
31 tcExtendLetEnv, tcExtendSigIds, tcExtendRecIds,
32 tcExtendIdEnv, tcExtendIdEnv1, tcExtendIdEnv2,
33 tcExtendBinderStack, tcExtendLocalTypeEnv,
34 isTypeClosedLetBndr,
35
36 tcLookup, tcLookupLocated, tcLookupLocalIds,
37 tcLookupId, tcLookupIdMaybe, tcLookupTyVar,
38 tcLookupLcl_maybe,
39 getInLocalScope,
40 wrongThingErr, pprBinders,
41
42 tcAddDataFamConPlaceholders, tcAddPatSynPlaceholders,
43 getTypeSigNames,
44 tcExtendRecEnv, -- For knot-tying
45
46 -- Tidying
47 tcInitTidyEnv, tcInitOpenTidyEnv,
48
49 -- Instances
50 tcLookupInstance, tcGetInstEnvs,
51
52 -- Rules
53 tcExtendRules,
54
55 -- Defaults
56 tcGetDefaultTys,
57
58 -- Global type variables
59 tcGetGlobalTyCoVars,
60
61 -- Template Haskell stuff
62 checkWellStaged, tcMetaTy, thLevel,
63 topIdLvl, isBrackStage,
64
65 -- New Ids
66 newDFunName, newDFunName', newFamInstTyConName,
67 newFamInstAxiomName,
68 mkStableIdFromString, mkStableIdFromName,
69 mkWrapperName
70 ) where
71
72 #include "HsVersions.h"
73
74 import GhcPrelude
75
76 import HsSyn
77 import IfaceEnv
78 import TcRnMonad
79 import TcMType
80 import TcType
81 import LoadIface
82 import PrelNames
83 import TysWiredIn
84 import Id
85 import Var
86 import VarSet
87 import RdrName
88 import InstEnv
89 import DataCon ( DataCon )
90 import PatSyn ( PatSyn )
91 import ConLike
92 import TyCon
93 import Type
94 import CoAxiom
95 import Class
96 import Name
97 import NameSet
98 import NameEnv
99 import VarEnv
100 import HscTypes
101 import DynFlags
102 import SrcLoc
103 import BasicTypes hiding( SuccessFlag(..) )
104 import Module
105 import Outputable
106 import Encoding
107 import FastString
108 import ListSetOps
109 import ErrUtils
110 import Util
111 import Maybes( MaybeErr(..), orElse )
112 import qualified GHC.LanguageExtensions as LangExt
113
114 import Data.IORef
115 import Data.List
116 import Control.Monad
117
118 {- *********************************************************************
119 * *
120 An IO interface to looking up globals
121 * *
122 ********************************************************************* -}
123
124 lookupGlobal :: HscEnv -> Name -> IO TyThing
125 -- A variant of lookupGlobal_maybe for the clients which are not
126 -- interested in recovering from lookup failure and accept panic.
127 lookupGlobal hsc_env name
128 = do {
129 mb_thing <- lookupGlobal_maybe hsc_env name
130 ; case mb_thing of
131 Succeeded thing -> return thing
132 Failed msg -> pprPanic "lookupGlobal" msg
133 }
134
135 lookupGlobal_maybe :: HscEnv -> Name -> IO (MaybeErr MsgDoc TyThing)
136 -- This may look up an Id that one one has previously looked up.
137 -- If so, we are going to read its interface file, and add its bindings
138 -- to the ExternalPackageTable.
139 lookupGlobal_maybe hsc_env name
140 = do { -- Try local envt
141 let mod = icInteractiveModule (hsc_IC hsc_env)
142 dflags = hsc_dflags hsc_env
143 tcg_semantic_mod = canonicalizeModuleIfHome dflags mod
144
145 ; if nameIsLocalOrFrom tcg_semantic_mod name
146 then (return
147 (Failed (text "Can't find local name: " <+> ppr name)))
148 -- Internal names can happen in GHCi
149 else
150 -- Try home package table and external package table
151 lookupImported_maybe hsc_env name
152 }
153
154 lookupImported_maybe :: HscEnv -> Name -> IO (MaybeErr MsgDoc TyThing)
155 -- Returns (Failed err) if we can't find the interface file for the thing
156 lookupImported_maybe hsc_env name
157 = do { mb_thing <- lookupTypeHscEnv hsc_env name
158 ; case mb_thing of
159 Just thing -> return (Succeeded thing)
160 Nothing -> importDecl_maybe hsc_env name
161 }
162
163 importDecl_maybe :: HscEnv -> Name -> IO (MaybeErr MsgDoc TyThing)
164 importDecl_maybe hsc_env name
165 | Just thing <- wiredInNameTyThing_maybe name
166 = do { when (needWiredInHomeIface thing)
167 (initIfaceLoad hsc_env (loadWiredInHomeIface name))
168 -- See Note [Loading instances for wired-in things]
169 ; return (Succeeded thing) }
170 | otherwise
171 = initIfaceLoad hsc_env (importDecl name)
172
173 ioLookupDataCon :: HscEnv -> Name -> IO DataCon
174 ioLookupDataCon hsc_env name = do
175 mb_thing <- ioLookupDataCon_maybe hsc_env name
176 case mb_thing of
177 Succeeded thing -> return thing
178 Failed msg -> pprPanic "lookupDataConIO" msg
179
180 ioLookupDataCon_maybe :: HscEnv -> Name -> IO (MaybeErr MsgDoc DataCon)
181 ioLookupDataCon_maybe hsc_env name = do
182 thing <- lookupGlobal hsc_env name
183 return $ case thing of
184 AConLike (RealDataCon con) -> Succeeded con
185 _ -> Failed $
186 pprTcTyThingCategory (AGlobal thing) <+> quotes (ppr name) <+>
187 text "used as a data constructor"
188
189 {-
190 ************************************************************************
191 * *
192 * tcLookupGlobal *
193 * *
194 ************************************************************************
195
196 Using the Located versions (eg. tcLookupLocatedGlobal) is preferred,
197 unless you know that the SrcSpan in the monad is already set to the
198 span of the Name.
199 -}
200
201
202 tcLookupLocatedGlobal :: Located Name -> TcM TyThing
203 -- c.f. IfaceEnvEnv.tcIfaceGlobal
204 tcLookupLocatedGlobal name
205 = addLocM tcLookupGlobal name
206
207 tcLookupGlobal :: Name -> TcM TyThing
208 -- The Name is almost always an ExternalName, but not always
209 -- In GHCi, we may make command-line bindings (ghci> let x = True)
210 -- that bind a GlobalId, but with an InternalName
211 tcLookupGlobal name
212 = do { -- Try local envt
213 env <- getGblEnv
214 ; case lookupNameEnv (tcg_type_env env) name of {
215 Just thing -> return thing ;
216 Nothing ->
217
218 -- Should it have been in the local envt?
219 -- (NB: use semantic mod here, since names never use
220 -- identity module, see Note [Identity versus semantic module].)
221 if nameIsLocalOrFrom (tcg_semantic_mod env) name
222 then notFound name -- Internal names can happen in GHCi
223 else
224
225 -- Try home package table and external package table
226 do { mb_thing <- tcLookupImported_maybe name
227 ; case mb_thing of
228 Succeeded thing -> return thing
229 Failed msg -> failWithTc msg
230 }}}
231
232 tcLookupDataCon :: Name -> TcM DataCon
233 tcLookupDataCon name = do
234 thing <- tcLookupGlobal name
235 case thing of
236 AConLike (RealDataCon con) -> return con
237 _ -> wrongThingErr "data constructor" (AGlobal thing) name
238
239 tcLookupPatSyn :: Name -> TcM PatSyn
240 tcLookupPatSyn name = do
241 thing <- tcLookupGlobal name
242 case thing of
243 AConLike (PatSynCon ps) -> return ps
244 _ -> wrongThingErr "pattern synonym" (AGlobal thing) name
245
246 tcLookupConLike :: Name -> TcM ConLike
247 tcLookupConLike name = do
248 thing <- tcLookupGlobal name
249 case thing of
250 AConLike cl -> return cl
251 _ -> wrongThingErr "constructor-like thing" (AGlobal thing) name
252
253 tcLookupClass :: Name -> TcM Class
254 tcLookupClass name = do
255 thing <- tcLookupGlobal name
256 case thing of
257 ATyCon tc | Just cls <- tyConClass_maybe tc -> return cls
258 _ -> wrongThingErr "class" (AGlobal thing) name
259
260 tcLookupTyCon :: Name -> TcM TyCon
261 tcLookupTyCon name = do
262 thing <- tcLookupGlobal name
263 case thing of
264 ATyCon tc -> return tc
265 _ -> wrongThingErr "type constructor" (AGlobal thing) name
266
267 tcLookupAxiom :: Name -> TcM (CoAxiom Branched)
268 tcLookupAxiom name = do
269 thing <- tcLookupGlobal name
270 case thing of
271 ACoAxiom ax -> return ax
272 _ -> wrongThingErr "axiom" (AGlobal thing) name
273
274 tcLookupLocatedGlobalId :: Located Name -> TcM Id
275 tcLookupLocatedGlobalId = addLocM tcLookupId
276
277 tcLookupLocatedClass :: Located Name -> TcM Class
278 tcLookupLocatedClass = addLocM tcLookupClass
279
280 tcLookupLocatedTyCon :: Located Name -> TcM TyCon
281 tcLookupLocatedTyCon = addLocM tcLookupTyCon
282
283 -- Find the instance that exactly matches a type class application. The class arguments must be precisely
284 -- the same as in the instance declaration (modulo renaming & casts).
285 --
286 tcLookupInstance :: Class -> [Type] -> TcM ClsInst
287 tcLookupInstance cls tys
288 = do { instEnv <- tcGetInstEnvs
289 ; case lookupUniqueInstEnv instEnv cls tys of
290 Left err -> failWithTc $ text "Couldn't match instance:" <+> err
291 Right (inst, tys)
292 | uniqueTyVars tys -> return inst
293 | otherwise -> failWithTc errNotExact
294 }
295 where
296 errNotExact = text "Not an exact match (i.e., some variables get instantiated)"
297
298 uniqueTyVars tys = all isTyVarTy tys
299 && hasNoDups (map (getTyVar "tcLookupInstance") tys)
300
301 tcGetInstEnvs :: TcM InstEnvs
302 -- Gets both the external-package inst-env
303 -- and the home-pkg inst env (includes module being compiled)
304 tcGetInstEnvs = do { eps <- getEps
305 ; env <- getGblEnv
306 ; return (InstEnvs { ie_global = eps_inst_env eps
307 , ie_local = tcg_inst_env env
308 , ie_visible = tcVisibleOrphanMods env }) }
309
310 instance MonadThings (IOEnv (Env TcGblEnv TcLclEnv)) where
311 lookupThing = tcLookupGlobal
312
313 {-
314 ************************************************************************
315 * *
316 Extending the global environment
317 * *
318 ************************************************************************
319 -}
320
321 setGlobalTypeEnv :: TcGblEnv -> TypeEnv -> TcM TcGblEnv
322 -- Use this to update the global type env
323 -- It updates both * the normal tcg_type_env field
324 -- * the tcg_type_env_var field seen by interface files
325 setGlobalTypeEnv tcg_env new_type_env
326 = do { -- Sync the type-envt variable seen by interface files
327 writeMutVar (tcg_type_env_var tcg_env) new_type_env
328 ; return (tcg_env { tcg_type_env = new_type_env }) }
329
330
331 tcExtendGlobalEnvImplicit :: [TyThing] -> TcM r -> TcM r
332 -- Just extend the global environment with some TyThings
333 -- Do not extend tcg_tcs, tcg_patsyns etc
334 tcExtendGlobalEnvImplicit things thing_inside
335 = do { tcg_env <- getGblEnv
336 ; let ge' = extendTypeEnvList (tcg_type_env tcg_env) things
337 ; tcg_env' <- setGlobalTypeEnv tcg_env ge'
338 ; setGblEnv tcg_env' thing_inside }
339
340 tcExtendGlobalEnv :: [TyThing] -> TcM r -> TcM r
341 -- Given a mixture of Ids, TyCons, Classes, all defined in the
342 -- module being compiled, extend the global environment
343 tcExtendGlobalEnv things thing_inside
344 = do { env <- getGblEnv
345 ; let env' = env { tcg_tcs = [tc | ATyCon tc <- things] ++ tcg_tcs env,
346 tcg_patsyns = [ps | AConLike (PatSynCon ps) <- things] ++ tcg_patsyns env }
347 ; setGblEnv env' $
348 tcExtendGlobalEnvImplicit things thing_inside
349 }
350
351 tcExtendTyConEnv :: [TyCon] -> TcM r -> TcM r
352 -- Given a mixture of Ids, TyCons, Classes, all defined in the
353 -- module being compiled, extend the global environment
354 tcExtendTyConEnv tycons thing_inside
355 = do { env <- getGblEnv
356 ; let env' = env { tcg_tcs = tycons ++ tcg_tcs env }
357 ; setGblEnv env' $
358 tcExtendGlobalEnvImplicit (map ATyCon tycons) thing_inside
359 }
360
361 tcExtendGlobalValEnv :: [Id] -> TcM a -> TcM a
362 -- Same deal as tcExtendGlobalEnv, but for Ids
363 tcExtendGlobalValEnv ids thing_inside
364 = tcExtendGlobalEnvImplicit [AnId id | id <- ids] thing_inside
365
366 tcExtendRecEnv :: [(Name,TyThing)] -> TcM r -> TcM r
367 -- Extend the global environments for the type/class knot tying game
368 -- Just like tcExtendGlobalEnv, except the argument is a list of pairs
369 tcExtendRecEnv gbl_stuff thing_inside
370 = do { tcg_env <- getGblEnv
371 ; let ge' = extendNameEnvList (tcg_type_env tcg_env) gbl_stuff
372 ; tcg_env' <- setGlobalTypeEnv tcg_env ge'
373 ; setGblEnv tcg_env' thing_inside }
374
375 {-
376 ************************************************************************
377 * *
378 \subsection{The local environment}
379 * *
380 ************************************************************************
381 -}
382
383 tcLookupLocated :: Located Name -> TcM TcTyThing
384 tcLookupLocated = addLocM tcLookup
385
386 tcLookupLcl_maybe :: Name -> TcM (Maybe TcTyThing)
387 tcLookupLcl_maybe name
388 = do { local_env <- getLclTypeEnv
389 ; return (lookupNameEnv local_env name) }
390
391 tcLookup :: Name -> TcM TcTyThing
392 tcLookup name = do
393 local_env <- getLclTypeEnv
394 case lookupNameEnv local_env name of
395 Just thing -> return thing
396 Nothing -> AGlobal <$> tcLookupGlobal name
397
398 tcLookupTyVar :: Name -> TcM TcTyVar
399 tcLookupTyVar name
400 = do { thing <- tcLookup name
401 ; case thing of
402 ATyVar _ tv -> return tv
403 _ -> pprPanic "tcLookupTyVar" (ppr name) }
404
405 tcLookupId :: Name -> TcM Id
406 -- Used when we aren't interested in the binding level, nor refinement.
407 -- The "no refinement" part means that we return the un-refined Id regardless
408 --
409 -- The Id is never a DataCon. (Why does that matter? see TcExpr.tcId)
410 tcLookupId name = do
411 thing <- tcLookupIdMaybe name
412 case thing of
413 Just id -> return id
414 _ -> pprPanic "tcLookupId" (ppr name)
415
416 tcLookupIdMaybe :: Name -> TcM (Maybe Id)
417 tcLookupIdMaybe name
418 = do { thing <- tcLookup name
419 ; case thing of
420 ATcId { tct_id = id} -> return $ Just id
421 AGlobal (AnId id) -> return $ Just id
422 _ -> return Nothing }
423
424 tcLookupLocalIds :: [Name] -> TcM [TcId]
425 -- We expect the variables to all be bound, and all at
426 -- the same level as the lookup. Only used in one place...
427 tcLookupLocalIds ns
428 = do { env <- getLclEnv
429 ; return (map (lookup (tcl_env env)) ns) }
430 where
431 lookup lenv name
432 = case lookupNameEnv lenv name of
433 Just (ATcId { tct_id = id }) -> id
434 _ -> pprPanic "tcLookupLocalIds" (ppr name)
435
436 getInLocalScope :: TcM (Name -> Bool)
437 getInLocalScope = do { lcl_env <- getLclTypeEnv
438 ; return (`elemNameEnv` lcl_env) }
439
440 tcExtendKindEnvList :: [(Name, TcTyThing)] -> TcM r -> TcM r
441 -- Used only during kind checking, for TcThings that are
442 -- ATcTyCon or APromotionErr
443 -- No need to update the global tyvars, or tcl_th_bndrs, or tcl_rdr
444 tcExtendKindEnvList things thing_inside
445 = do { traceTc "tcExtendKindEnvList" (ppr things)
446 ; updLclEnv upd_env thing_inside }
447 where
448 upd_env env = env { tcl_env = extendNameEnvList (tcl_env env) things }
449
450 tcExtendKindEnv :: NameEnv TcTyThing -> TcM r -> TcM r
451 -- A variant of tcExtendKindEvnList
452 tcExtendKindEnv extra_env thing_inside
453 = do { traceTc "tcExtendKindEnv" (ppr extra_env)
454 ; updLclEnv upd_env thing_inside }
455 where
456 upd_env env = env { tcl_env = tcl_env env `plusNameEnv` extra_env }
457
458 -----------------------
459 -- Scoped type and kind variables
460 -- Before using this function, consider using TcHsType.scopeTyVars, which
461 -- bumps the TcLevel and thus prevents any of these TyVars from appearing
462 -- in kinds of tyvars in an outer scope.
463 -- Indeed, you should always use scopeTyVars unless some other code nearby
464 -- bumps the TcLevel.
465 tcExtendTyVarEnv :: [TyVar] -> TcM r -> TcM r
466 tcExtendTyVarEnv tvs thing_inside
467 = tcExtendNameTyVarEnv (mkTyVarNamePairs tvs) thing_inside
468
469 -- Before using this function, consider using TcHsType.scopeTyVars2, which
470 -- bumps the TcLevel and thus prevents any of these TyVars from appearing
471 -- in kinds of tyvars in an outer scope.
472 tcExtendNameTyVarEnv :: [(Name,TcTyVar)] -> TcM r -> TcM r
473 tcExtendNameTyVarEnv binds thing_inside
474 -- this should be used only for explicitly mentioned scoped variables.
475 -- thus, no coercion variables
476 = do { tc_extend_local_env NotTopLevel
477 [(name, ATyVar name tv) | (name, tv) <- binds] $
478 tcExtendBinderStack tv_binds $
479 thing_inside }
480 where
481 tv_binds :: [TcBinder]
482 tv_binds = [TcTvBndr name tv | (name,tv) <- binds]
483
484 isTypeClosedLetBndr :: Id -> Bool
485 -- See Note [Bindings with closed types] in TcRnTypes
486 isTypeClosedLetBndr = noFreeVarsOfType . idType
487
488 tcExtendRecIds :: [(Name, TcId)] -> TcM a -> TcM a
489 -- Used for binding the recurive uses of Ids in a binding
490 -- both top-level value bindings and and nested let/where-bindings
491 -- Does not extend the TcBinderStack
492 tcExtendRecIds pairs thing_inside
493 = tc_extend_local_env NotTopLevel
494 [ (name, ATcId { tct_id = let_id
495 , tct_info = NonClosedLet emptyNameSet False })
496 | (name, let_id) <- pairs ] $
497 thing_inside
498
499 tcExtendSigIds :: TopLevelFlag -> [TcId] -> TcM a -> TcM a
500 -- Used for binding the Ids that have a complete user type signature
501 -- Does not extend the TcBinderStack
502 tcExtendSigIds top_lvl sig_ids thing_inside
503 = tc_extend_local_env top_lvl
504 [ (idName id, ATcId { tct_id = id
505 , tct_info = info })
506 | id <- sig_ids
507 , let closed = isTypeClosedLetBndr id
508 info = NonClosedLet emptyNameSet closed ]
509 thing_inside
510
511
512 tcExtendLetEnv :: TopLevelFlag -> TcSigFun -> IsGroupClosed
513 -> [TcId] -> TcM a -> TcM a
514 -- Used for both top-level value bindings and and nested let/where-bindings
515 -- Adds to the TcBinderStack too
516 tcExtendLetEnv top_lvl sig_fn (IsGroupClosed fvs fv_type_closed)
517 ids thing_inside
518 = tcExtendBinderStack [TcIdBndr id top_lvl | id <- ids] $
519 tc_extend_local_env top_lvl
520 [ (idName id, ATcId { tct_id = id
521 , tct_info = mk_tct_info id })
522 | id <- ids ]
523 thing_inside
524 where
525 mk_tct_info id
526 | type_closed && isEmptyNameSet rhs_fvs = ClosedLet
527 | otherwise = NonClosedLet rhs_fvs type_closed
528 where
529 name = idName id
530 rhs_fvs = lookupNameEnv fvs name `orElse` emptyNameSet
531 type_closed = isTypeClosedLetBndr id &&
532 (fv_type_closed || hasCompleteSig sig_fn name)
533
534 tcExtendIdEnv :: [TcId] -> TcM a -> TcM a
535 -- For lambda-bound and case-bound Ids
536 -- Extends the TcBinderStack as well
537 tcExtendIdEnv ids thing_inside
538 = tcExtendIdEnv2 [(idName id, id) | id <- ids] thing_inside
539
540 tcExtendIdEnv1 :: Name -> TcId -> TcM a -> TcM a
541 -- Exactly like tcExtendIdEnv2, but for a single (name,id) pair
542 tcExtendIdEnv1 name id thing_inside
543 = tcExtendIdEnv2 [(name,id)] thing_inside
544
545 tcExtendIdEnv2 :: [(Name,TcId)] -> TcM a -> TcM a
546 tcExtendIdEnv2 names_w_ids thing_inside
547 = tcExtendBinderStack [ TcIdBndr mono_id NotTopLevel
548 | (_,mono_id) <- names_w_ids ] $
549 tc_extend_local_env NotTopLevel
550 [ (name, ATcId { tct_id = id
551 , tct_info = NotLetBound })
552 | (name,id) <- names_w_ids]
553 thing_inside
554
555 tc_extend_local_env :: TopLevelFlag -> [(Name, TcTyThing)] -> TcM a -> TcM a
556 tc_extend_local_env top_lvl extra_env thing_inside
557 -- Precondition: the argument list extra_env has TcTyThings
558 -- that ATcId or ATyVar, but nothing else
559 --
560 -- Invariant: the ATcIds are fully zonked. Reasons:
561 -- (a) The kinds of the forall'd type variables are defaulted
562 -- (see Kind.defaultKind, done in zonkQuantifiedTyVar)
563 -- (b) There are no via-Indirect occurrences of the bound variables
564 -- in the types, because instantiation does not look through such things
565 -- (c) The call to tyCoVarsOfTypes is ok without looking through refs
566
567 -- The second argument of type TyVarSet is a set of type variables
568 -- that are bound together with extra_env and should not be regarded
569 -- as free in the types of extra_env.
570 = do { traceTc "tc_extend_local_env" (ppr extra_env)
571 ; env0 <- getLclEnv
572 ; env1 <- tcExtendLocalTypeEnv env0 extra_env
573 ; stage <- getStage
574 ; let env2 = extend_local_env (top_lvl, thLevel stage) extra_env env1
575 ; setLclEnv env2 thing_inside }
576 where
577 extend_local_env :: (TopLevelFlag, ThLevel) -> [(Name, TcTyThing)] -> TcLclEnv -> TcLclEnv
578 -- Extend the local LocalRdrEnv and Template Haskell staging env simultaneously
579 -- Reason for extending LocalRdrEnv: after running a TH splice we need
580 -- to do renaming.
581 extend_local_env thlvl pairs env@(TcLclEnv { tcl_rdr = rdr_env
582 , tcl_th_bndrs = th_bndrs })
583 = env { tcl_rdr = extendLocalRdrEnvList rdr_env
584 [ n | (n, _) <- pairs, isInternalName n ]
585 -- The LocalRdrEnv contains only non-top-level names
586 -- (GlobalRdrEnv handles the top level)
587 , tcl_th_bndrs = extendNameEnvList th_bndrs -- We only track Ids in tcl_th_bndrs
588 [(n, thlvl) | (n, ATcId {}) <- pairs] }
589
590 tcExtendLocalTypeEnv :: TcLclEnv -> [(Name, TcTyThing)] -> TcM TcLclEnv
591 tcExtendLocalTypeEnv lcl_env@(TcLclEnv { tcl_env = lcl_type_env }) tc_ty_things
592 | isEmptyVarSet extra_tvs
593 = return (lcl_env { tcl_env = extendNameEnvList lcl_type_env tc_ty_things })
594 | otherwise
595 = do { global_tvs <- readMutVar (tcl_tyvars lcl_env)
596 ; new_g_var <- newMutVar (global_tvs `unionVarSet` extra_tvs)
597 ; return (lcl_env { tcl_tyvars = new_g_var
598 , tcl_env = extendNameEnvList lcl_type_env tc_ty_things } ) }
599 where
600 extra_tvs = foldr get_tvs emptyVarSet tc_ty_things
601
602 get_tvs (_, ATcId { tct_id = id, tct_info = closed }) tvs
603 = case closed of
604 ClosedLet -> ASSERT2( is_closed_type, ppr id $$ ppr (idType id) )
605 tvs
606 _other -> tvs `unionVarSet` id_tvs
607 where
608 id_tvs = tyCoVarsOfType (idType id)
609 is_closed_type = not (anyVarSet isTyVar id_tvs)
610 -- We only care about being closed wrt /type/ variables
611 -- E.g. a top-level binding might have a type like
612 -- foo :: t |> co
613 -- where co :: * ~ *
614 -- or some other as-yet-unsolved kind coercion
615
616 get_tvs (_, ATyVar _ tv) tvs -- See Note [Global TyVars]
617 = tvs `unionVarSet` tyCoVarsOfType (tyVarKind tv) `extendVarSet` tv
618
619 get_tvs (_, ATcTyCon tc) tvs = tvs `unionVarSet` tyCoVarsOfType (tyConKind tc)
620
621 get_tvs (_, AGlobal {}) tvs = tvs
622 get_tvs (_, APromotionErr {}) tvs = tvs
623
624 -- Note [Global TyVars]
625 -- It's important to add the in-scope tyvars to the global tyvar set
626 -- as well. Consider
627 -- f (_::r) = let g y = y::r in ...
628 -- Here, g mustn't be generalised. This is also important during
629 -- class and instance decls, when we mustn't generalise the class tyvars
630 -- when typechecking the methods.
631 --
632 -- Nor must we generalise g over any kind variables free in r's kind
633
634
635 {- *********************************************************************
636 * *
637 The TcBinderStack
638 * *
639 ********************************************************************* -}
640
641 tcExtendBinderStack :: [TcBinder] -> TcM a -> TcM a
642 tcExtendBinderStack bndrs thing_inside
643 = do { traceTc "tcExtendBinderStack" (ppr bndrs)
644 ; updLclEnv (\env -> env { tcl_bndrs = bndrs ++ tcl_bndrs env })
645 thing_inside }
646
647 tcInitTidyEnv :: TcM TidyEnv
648 -- We initialise the "tidy-env", used for tidying types before printing,
649 -- by building a reverse map from the in-scope type variables to the
650 -- OccName that the programmer originally used for them
651 tcInitTidyEnv
652 = do { lcl_env <- getLclEnv
653 ; go emptyTidyEnv (tcl_bndrs lcl_env) }
654 where
655 go (env, subst) []
656 = return (env, subst)
657 go (env, subst) (b : bs)
658 | TcTvBndr name tyvar <- b
659 = do { let (env', occ') = tidyOccName env (nameOccName name)
660 name' = tidyNameOcc name occ'
661 tyvar1 = setTyVarName tyvar name'
662 ; tyvar2 <- zonkTcTyVarToTyVar tyvar1
663 -- Be sure to zonk here! Tidying applies to zonked
664 -- types, so if we don't zonk we may create an
665 -- ill-kinded type (Trac #14175)
666 ; go (env', extendVarEnv subst tyvar tyvar2) bs }
667 | otherwise
668 = go (env, subst) bs
669
670 -- | Get a 'TidyEnv' that includes mappings for all vars free in the given
671 -- type. Useful when tidying open types.
672 tcInitOpenTidyEnv :: [TyCoVar] -> TcM TidyEnv
673 tcInitOpenTidyEnv tvs
674 = do { env1 <- tcInitTidyEnv
675 ; let env2 = tidyFreeTyCoVars env1 tvs
676 ; return env2 }
677
678
679
680 {- *********************************************************************
681 * *
682 Adding placeholders
683 * *
684 ********************************************************************* -}
685
686 tcAddDataFamConPlaceholders :: [LInstDecl GhcRn] -> TcM a -> TcM a
687 -- See Note [AFamDataCon: not promoting data family constructors]
688 tcAddDataFamConPlaceholders inst_decls thing_inside
689 = tcExtendKindEnvList [ (con, APromotionErr FamDataConPE)
690 | lid <- inst_decls, con <- get_cons lid ]
691 thing_inside
692 -- Note [AFamDataCon: not promoting data family constructors]
693 where
694 -- get_cons extracts the *constructor* bindings of the declaration
695 get_cons :: LInstDecl GhcRn -> [Name]
696 get_cons (L _ (TyFamInstD {})) = []
697 get_cons (L _ (DataFamInstD { dfid_inst = fid })) = get_fi_cons fid
698 get_cons (L _ (ClsInstD { cid_inst = ClsInstDecl { cid_datafam_insts = fids } }))
699 = concatMap (get_fi_cons . unLoc) fids
700 get_cons (L _ (ClsInstD _ (XClsInstDecl _))) = panic "get_cons"
701 get_cons (L _ (XInstDecl _)) = panic "get_cons"
702
703 get_fi_cons :: DataFamInstDecl GhcRn -> [Name]
704 get_fi_cons (DataFamInstDecl { dfid_eqn = HsIB { hsib_body =
705 FamEqn { feqn_rhs = HsDataDefn { dd_cons = cons } }}})
706 = map unLoc $ concatMap (getConNames . unLoc) cons
707 get_fi_cons (DataFamInstDecl { dfid_eqn = HsIB { hsib_body =
708 FamEqn { feqn_rhs = XHsDataDefn _ }}})
709 = panic "get_fi_cons"
710 get_fi_cons (DataFamInstDecl (HsIB _ (XFamEqn _))) = panic "get_fi_cons"
711 get_fi_cons (DataFamInstDecl (XHsImplicitBndrs _)) = panic "get_fi_cons"
712
713
714 tcAddPatSynPlaceholders :: [PatSynBind GhcRn GhcRn] -> TcM a -> TcM a
715 -- See Note [Don't promote pattern synonyms]
716 tcAddPatSynPlaceholders pat_syns thing_inside
717 = tcExtendKindEnvList [ (name, APromotionErr PatSynPE)
718 | PSB{ psb_id = L _ name } <- pat_syns ]
719 thing_inside
720
721 getTypeSigNames :: [LSig GhcRn] -> NameSet
722 -- Get the names that have a user type sig
723 getTypeSigNames sigs
724 = foldr get_type_sig emptyNameSet sigs
725 where
726 get_type_sig :: LSig GhcRn -> NameSet -> NameSet
727 get_type_sig sig ns =
728 case sig of
729 L _ (TypeSig _ names _) -> extendNameSetList ns (map unLoc names)
730 L _ (PatSynSig _ names _) -> extendNameSetList ns (map unLoc names)
731 _ -> ns
732
733
734 {- Note [AFamDataCon: not promoting data family constructors]
735 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
736 Consider
737 data family T a
738 data instance T Int = MkT
739 data Proxy (a :: k)
740 data S = MkS (Proxy 'MkT)
741
742 Is it ok to use the promoted data family instance constructor 'MkT' in
743 the data declaration for S (where both declarations live in the same module)?
744 No, we don't allow this. It *might* make sense, but at least it would mean that
745 we'd have to interleave typechecking instances and data types, whereas at
746 present we do data types *then* instances.
747
748 So to check for this we put in the TcLclEnv a binding for all the family
749 constructors, bound to AFamDataCon, so that if we trip over 'MkT' when
750 type checking 'S' we'll produce a decent error message.
751
752 Trac #12088 describes this limitation. Of course, when MkT and S live in
753 different modules then all is well.
754
755 Note [Don't promote pattern synonyms]
756 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
757 We never promote pattern synonyms.
758
759 Consider this (Trac #11265):
760 pattern A = True
761 instance Eq A
762 We want a civilised error message from the occurrence of 'A'
763 in the instance, yet 'A' really has not yet been type checked.
764
765 Similarly (Trac #9161)
766 {-# LANGUAGE PatternSynonyms, DataKinds #-}
767 pattern A = ()
768 b :: A
769 b = undefined
770 Here, the type signature for b mentions A. But A is a pattern
771 synonym, which is typechecked as part of a group of bindings (for very
772 good reasons; a view pattern in the RHS may mention a value binding).
773 It is entirely reasonable to reject this, but to do so we need A to be
774 in the kind environment when kind-checking the signature for B.
775
776 Hence tcAddPatSynPlaceholers adds a binding
777 A -> APromotionErr PatSynPE
778 to the environment. Then TcHsType.tcTyVar will find A in the kind
779 environment, and will give a 'wrongThingErr' as a result. But the
780 lookup of A won't fail.
781
782
783 ************************************************************************
784 * *
785 \subsection{Rules}
786 * *
787 ************************************************************************
788 -}
789
790 tcExtendRules :: [LRuleDecl GhcTc] -> TcM a -> TcM a
791 -- Just pop the new rules into the EPS and envt resp
792 -- All the rules come from an interface file, not source
793 -- Nevertheless, some may be for this module, if we read
794 -- its interface instead of its source code
795 tcExtendRules lcl_rules thing_inside
796 = do { env <- getGblEnv
797 ; let
798 env' = env { tcg_rules = lcl_rules ++ tcg_rules env }
799 ; setGblEnv env' thing_inside }
800
801 {-
802 ************************************************************************
803 * *
804 Meta level
805 * *
806 ************************************************************************
807 -}
808
809 checkWellStaged :: SDoc -- What the stage check is for
810 -> ThLevel -- Binding level (increases inside brackets)
811 -> ThLevel -- Use stage
812 -> TcM () -- Fail if badly staged, adding an error
813 checkWellStaged pp_thing bind_lvl use_lvl
814 | use_lvl >= bind_lvl -- OK! Used later than bound
815 = return () -- E.g. \x -> [| $(f x) |]
816
817 | bind_lvl == outerLevel -- GHC restriction on top level splices
818 = stageRestrictionError pp_thing
819
820 | otherwise -- Badly staged
821 = failWithTc $ -- E.g. \x -> $(f x)
822 text "Stage error:" <+> pp_thing <+>
823 hsep [text "is bound at stage" <+> ppr bind_lvl,
824 text "but used at stage" <+> ppr use_lvl]
825
826 stageRestrictionError :: SDoc -> TcM a
827 stageRestrictionError pp_thing
828 = failWithTc $
829 sep [ text "GHC stage restriction:"
830 , nest 2 (vcat [ pp_thing <+> text "is used in a top-level splice, quasi-quote, or annotation,"
831 , text "and must be imported, not defined locally"])]
832
833 topIdLvl :: Id -> ThLevel
834 -- Globals may either be imported, or may be from an earlier "chunk"
835 -- (separated by declaration splices) of this module. The former
836 -- *can* be used inside a top-level splice, but the latter cannot.
837 -- Hence we give the former impLevel, but the latter topLevel
838 -- E.g. this is bad:
839 -- x = [| foo |]
840 -- $( f x )
841 -- By the time we are prcessing the $(f x), the binding for "x"
842 -- will be in the global env, not the local one.
843 topIdLvl id | isLocalId id = outerLevel
844 | otherwise = impLevel
845
846 tcMetaTy :: Name -> TcM Type
847 -- Given the name of a Template Haskell data type,
848 -- return the type
849 -- E.g. given the name "Expr" return the type "Expr"
850 tcMetaTy tc_name = do
851 t <- tcLookupTyCon tc_name
852 return (mkTyConApp t [])
853
854 isBrackStage :: ThStage -> Bool
855 isBrackStage (Brack {}) = True
856 isBrackStage _other = False
857
858 {-
859 ************************************************************************
860 * *
861 getDefaultTys
862 * *
863 ************************************************************************
864 -}
865
866 tcGetDefaultTys :: TcM ([Type], -- Default types
867 (Bool, -- True <=> Use overloaded strings
868 Bool)) -- True <=> Use extended defaulting rules
869 tcGetDefaultTys
870 = do { dflags <- getDynFlags
871 ; let ovl_strings = xopt LangExt.OverloadedStrings dflags
872 extended_defaults = xopt LangExt.ExtendedDefaultRules dflags
873 -- See also Trac #1974
874 flags = (ovl_strings, extended_defaults)
875
876 ; mb_defaults <- getDeclaredDefaultTys
877 ; case mb_defaults of {
878 Just tys -> return (tys, flags) ;
879 -- User-supplied defaults
880 Nothing -> do
881
882 -- No use-supplied default
883 -- Use [Integer, Double], plus modifications
884 { integer_ty <- tcMetaTy integerTyConName
885 ; list_ty <- tcMetaTy listTyConName
886 ; checkWiredInTyCon doubleTyCon
887 ; let deflt_tys = opt_deflt extended_defaults [unitTy, list_ty]
888 -- Note [Extended defaults]
889 ++ [integer_ty, doubleTy]
890 ++ opt_deflt ovl_strings [stringTy]
891 ; return (deflt_tys, flags) } } }
892 where
893 opt_deflt True xs = xs
894 opt_deflt False _ = []
895
896 {-
897 Note [Extended defaults]
898 ~~~~~~~~~~~~~~~~~~~~~
899 In interative mode (or with -XExtendedDefaultRules) we add () as the first type we
900 try when defaulting. This has very little real impact, except in the following case.
901 Consider:
902 Text.Printf.printf "hello"
903 This has type (forall a. IO a); it prints "hello", and returns 'undefined'. We don't
904 want the GHCi repl loop to try to print that 'undefined'. The neatest thing is to
905 default the 'a' to (), rather than to Integer (which is what would otherwise happen;
906 and then GHCi doesn't attempt to print the (). So in interactive mode, we add
907 () to the list of defaulting types. See Trac #1200.
908
909 Additionally, the list type [] is added as a default specialization for
910 Traversable and Foldable. As such the default default list now has types of
911 varying kinds, e.g. ([] :: * -> *) and (Integer :: *).
912
913 ************************************************************************
914 * *
915 \subsection{The InstInfo type}
916 * *
917 ************************************************************************
918
919 The InstInfo type summarises the information in an instance declaration
920
921 instance c => k (t tvs) where b
922
923 It is used just for *local* instance decls (not ones from interface files).
924 But local instance decls includes
925 - derived ones
926 - generic ones
927 as well as explicit user written ones.
928 -}
929
930 data InstInfo a
931 = InstInfo
932 { iSpec :: ClsInst -- Includes the dfun id
933 , iBinds :: InstBindings a
934 }
935
936 iDFunId :: InstInfo a -> DFunId
937 iDFunId info = instanceDFunId (iSpec info)
938
939 data InstBindings a
940 = InstBindings
941 { ib_tyvars :: [Name] -- Names of the tyvars from the instance head
942 -- that are lexically in scope in the bindings
943 -- Must correspond 1-1 with the forall'd tyvars
944 -- of the dfun Id. When typechecking, we are
945 -- going to extend the typechecker's envt with
946 -- ib_tyvars -> dfun_forall_tyvars
947
948 , ib_binds :: LHsBinds a -- Bindings for the instance methods
949
950 , ib_pragmas :: [LSig a] -- User pragmas recorded for generating
951 -- specialised instances
952
953 , ib_extensions :: [LangExt.Extension] -- Any extra extensions that should
954 -- be enabled when type-checking
955 -- this instance; needed for
956 -- GeneralizedNewtypeDeriving
957
958 , ib_derived :: Bool
959 -- True <=> This code was generated by GHC from a deriving clause
960 -- or standalone deriving declaration
961 -- Used only to improve error messages
962 }
963
964 instance (OutputableBndrId (GhcPass a))
965 => Outputable (InstInfo (GhcPass a)) where
966 ppr = pprInstInfoDetails
967
968 pprInstInfoDetails :: (OutputableBndrId (GhcPass a))
969 => InstInfo (GhcPass a) -> SDoc
970 pprInstInfoDetails info
971 = hang (pprInstanceHdr (iSpec info) <+> text "where")
972 2 (details (iBinds info))
973 where
974 details (InstBindings { ib_binds = b }) = pprLHsBinds b
975
976 simpleInstInfoClsTy :: InstInfo a -> (Class, Type)
977 simpleInstInfoClsTy info = case instanceHead (iSpec info) of
978 (_, cls, [ty]) -> (cls, ty)
979 _ -> panic "simpleInstInfoClsTy"
980
981 simpleInstInfoTy :: InstInfo a -> Type
982 simpleInstInfoTy info = snd (simpleInstInfoClsTy info)
983
984 simpleInstInfoTyCon :: InstInfo a -> TyCon
985 -- Gets the type constructor for a simple instance declaration,
986 -- i.e. one of the form instance (...) => C (T a b c) where ...
987 simpleInstInfoTyCon inst = tcTyConAppTyCon (simpleInstInfoTy inst)
988
989 -- | Make a name for the dict fun for an instance decl. It's an *external*
990 -- name, like other top-level names, and hence must be made with
991 -- newGlobalBinder.
992 newDFunName :: Class -> [Type] -> SrcSpan -> TcM Name
993 newDFunName clas tys loc
994 = do { is_boot <- tcIsHsBootOrSig
995 ; mod <- getModule
996 ; let info_string = occNameString (getOccName clas) ++
997 concatMap (occNameString.getDFunTyKey) tys
998 ; dfun_occ <- chooseUniqueOccTc (mkDFunOcc info_string is_boot)
999 ; newGlobalBinder mod dfun_occ loc }
1000
1001 -- | Special case of 'newDFunName' to generate dict fun name for a single TyCon.
1002 newDFunName' :: Class -> TyCon -> TcM Name
1003 newDFunName' clas tycon -- Just a simple wrapper
1004 = do { loc <- getSrcSpanM -- The location of the instance decl,
1005 -- not of the tycon
1006 ; newDFunName clas [mkTyConApp tycon []] loc }
1007 -- The type passed to newDFunName is only used to generate
1008 -- a suitable string; hence the empty type arg list
1009
1010 {-
1011 Make a name for the representation tycon of a family instance. It's an
1012 *external* name, like other top-level names, and hence must be made with
1013 newGlobalBinder.
1014 -}
1015
1016 newFamInstTyConName :: Located Name -> [Type] -> TcM Name
1017 newFamInstTyConName (L loc name) tys = mk_fam_inst_name id loc name [tys]
1018
1019 newFamInstAxiomName :: Located Name -> [[Type]] -> TcM Name
1020 newFamInstAxiomName (L loc name) branches
1021 = mk_fam_inst_name mkInstTyCoOcc loc name branches
1022
1023 mk_fam_inst_name :: (OccName -> OccName) -> SrcSpan -> Name -> [[Type]] -> TcM Name
1024 mk_fam_inst_name adaptOcc loc tc_name tyss
1025 = do { mod <- getModule
1026 ; let info_string = occNameString (getOccName tc_name) ++
1027 intercalate "|" ty_strings
1028 ; occ <- chooseUniqueOccTc (mkInstTyTcOcc info_string)
1029 ; newGlobalBinder mod (adaptOcc occ) loc }
1030 where
1031 ty_strings = map (concatMap (occNameString . getDFunTyKey)) tyss
1032
1033 {-
1034 Stable names used for foreign exports and annotations.
1035 For stable names, the name must be unique (see #1533). If the
1036 same thing has several stable Ids based on it, the
1037 top-level bindings generated must not have the same name.
1038 Hence we create an External name (doesn't change), and we
1039 append a Unique to the string right here.
1040 -}
1041
1042 mkStableIdFromString :: String -> Type -> SrcSpan -> (OccName -> OccName) -> TcM TcId
1043 mkStableIdFromString str sig_ty loc occ_wrapper = do
1044 uniq <- newUnique
1045 mod <- getModule
1046 name <- mkWrapperName "stable" str
1047 let occ = mkVarOccFS name :: OccName
1048 gnm = mkExternalName uniq mod (occ_wrapper occ) loc :: Name
1049 id = mkExportedVanillaId gnm sig_ty :: Id
1050 return id
1051
1052 mkStableIdFromName :: Name -> Type -> SrcSpan -> (OccName -> OccName) -> TcM TcId
1053 mkStableIdFromName nm = mkStableIdFromString (getOccString nm)
1054
1055 mkWrapperName :: (MonadIO m, HasDynFlags m, HasModule m)
1056 => String -> String -> m FastString
1057 mkWrapperName what nameBase
1058 = do dflags <- getDynFlags
1059 thisMod <- getModule
1060 let -- Note [Generating fresh names for ccall wrapper]
1061 wrapperRef = nextWrapperNum dflags
1062 pkg = unitIdString (moduleUnitId thisMod)
1063 mod = moduleNameString (moduleName thisMod)
1064 wrapperNum <- liftIO $ atomicModifyIORef' wrapperRef $ \mod_env ->
1065 let num = lookupWithDefaultModuleEnv mod_env 0 thisMod
1066 mod_env' = extendModuleEnv mod_env thisMod (num+1)
1067 in (mod_env', num)
1068 let components = [what, show wrapperNum, pkg, mod, nameBase]
1069 return $ mkFastString $ zEncodeString $ intercalate ":" components
1070
1071 {-
1072 Note [Generating fresh names for FFI wrappers]
1073
1074 We used to use a unique, rather than nextWrapperNum, to distinguish
1075 between FFI wrapper functions. However, the wrapper names that we
1076 generate are external names. This means that if a call to them ends up
1077 in an unfolding, then we can't alpha-rename them, and thus if the
1078 unique randomly changes from one compile to another then we get a
1079 spurious ABI change (#4012).
1080
1081 The wrapper counter has to be per-module, not global, so that the number we end
1082 up using is not dependent on the modules compiled before the current one.
1083 -}
1084
1085 {-
1086 ************************************************************************
1087 * *
1088 \subsection{Errors}
1089 * *
1090 ************************************************************************
1091 -}
1092
1093 pprBinders :: [Name] -> SDoc
1094 -- Used in error messages
1095 -- Use quotes for a single one; they look a bit "busy" for several
1096 pprBinders [bndr] = quotes (ppr bndr)
1097 pprBinders bndrs = pprWithCommas ppr bndrs
1098
1099 notFound :: Name -> TcM TyThing
1100 notFound name
1101 = do { lcl_env <- getLclEnv
1102 ; let stage = tcl_th_ctxt lcl_env
1103 ; case stage of -- See Note [Out of scope might be a staging error]
1104 Splice {}
1105 | isUnboundName name -> failM -- If the name really isn't in scope
1106 -- don't report it again (Trac #11941)
1107 | otherwise -> stageRestrictionError (quotes (ppr name))
1108 _ -> failWithTc $
1109 vcat[text "GHC internal error:" <+> quotes (ppr name) <+>
1110 text "is not in scope during type checking, but it passed the renamer",
1111 text "tcl_env of environment:" <+> ppr (tcl_env lcl_env)]
1112 -- Take care: printing the whole gbl env can
1113 -- cause an infinite loop, in the case where we
1114 -- are in the middle of a recursive TyCon/Class group;
1115 -- so let's just not print it! Getting a loop here is
1116 -- very unhelpful, because it hides one compiler bug with another
1117 }
1118
1119 wrongThingErr :: String -> TcTyThing -> Name -> TcM a
1120 -- It's important that this only calls pprTcTyThingCategory, which in
1121 -- turn does not look at the details of the TcTyThing.
1122 -- See Note [Placeholder PatSyn kinds] in TcBinds
1123 wrongThingErr expected thing name
1124 = failWithTc (pprTcTyThingCategory thing <+> quotes (ppr name) <+>
1125 text "used as a" <+> text expected)
1126
1127 {- Note [Out of scope might be a staging error]
1128 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1129 Consider
1130 x = 3
1131 data T = MkT $(foo x)
1132
1133 where 'foo' is imported from somewhere.
1134
1135 This is really a staging error, because we can't run code involving 'x'.
1136 But in fact the type checker processes types first, so 'x' won't even be
1137 in the type envt when we look for it in $(foo x). So inside splices we
1138 report something missing from the type env as a staging error.
1139 See Trac #5752 and #5795.
1140 -}