2 (c) The University of Glasgow 2006
3 (c) The AQUA Project, Glasgow University, 1996-1998
6 TcTyClsDecls: Typecheck type and class declarations
9 {-# LANGUAGE CPP, TupleSections, MultiWayIf #-}
10 {-# LANGUAGE TypeFamilies #-}
13 tcTyAndClassDecls
, tcAddImplicits
,
15 -- Functions used by TcInstDcls to check
16 -- data/type family instance declarations
17 kcDataDefn
, tcConDecls
, dataDeclChecks
, checkValidTyCon
,
18 tcFamTyPats
, tcTyFamInstEqn
,
19 tcAddTyFamInstCtxt
, tcMkDataFamInstCtxt
, tcAddDataFamInstCtxt
,
20 wrongKindOfFamily
, dataConCtxt
23 #include
"HsVersions.h"
36 import {-# SOURCE #-} TcInstDcls
( tcInstDecls1
)
37 import TcDeriv
(DerivInfo
)
38 import TcEvidence
( tcCoercionKind
, isEmptyTcEvBinds
)
39 import TcUnify
( checkConstraints
)
42 import TysWiredIn
( unitTy
)
44 import RnEnv
( lookupConstructorFields
)
49 import TyCoRep
-- for checkValidRoles
73 import qualified GHC
.LanguageExtensions
as LangExt
77 import Data
.List
.NonEmpty
( NonEmpty
(..) )
80 ************************************************************************
82 \subsection{Type checking for type and class declarations}
84 ************************************************************************
86 Note [Grouping of type and class declarations]
87 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
88 tcTyAndClassDecls is called on a list of `TyClGroup`s. Each group is a strongly
89 connected component of mutually dependent types and classes. We kind check and
90 type check each group separately to enhance kind polymorphism. Take the
96 If we were to kind check the two declarations together, we would give Id the
97 kind * -> *, since we apply it to an Int in the definition of X. But we can do
98 better than that, since Id really is kind polymorphic, and should get kind
99 forall (k::*). k -> k. Since it does not depend on anything else, it can be
100 kind-checked by itself, hence getting the most general kind. We then kind check
101 X, which works fine because we then know the polymorphic kind of Id, and simply
104 Note [Check role annotations in a second pass]
105 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
106 Role inference potentially depends on the types of all of the datacons declared
107 in a mutually recursive group. The validity of a role annotation, in turn,
108 depends on the result of role inference. Because the types of datacons might
109 be ill-formed (see #7175 and Note [Checking GADT return types]) we must check
110 *all* the tycons in a group for validity before checking *any* of the roles.
111 Thus, we take two passes over the resulting tycons, first checking for general
112 validity and then checking for valid role annotations.
115 tcTyAndClassDecls
:: [TyClGroup GhcRn
] -- Mutually-recursive groups in
117 -> TcM
( TcGblEnv
-- Input env extended by types and
119 -- and their implicit Ids,DataCons
120 , [InstInfo GhcRn
] -- Source-code instance decls info
121 , [DerivInfo
] -- data family deriving info
123 -- Fails if there are any errors
124 tcTyAndClassDecls tyclds_s
125 -- The code recovers internally, but if anything gave rise to
126 -- an error we'd better stop now, to avoid a cascade
127 -- Type check each group in dependency order folding the global env
128 = checkNoErrs
$ fold_env
[] [] tyclds_s
130 fold_env
:: [InstInfo GhcRn
]
133 -> TcM
(TcGblEnv
, [InstInfo GhcRn
], [DerivInfo
])
134 fold_env inst_info deriv_info
[]
135 = do { gbl_env
<- getGblEnv
136 ; return (gbl_env
, inst_info
, deriv_info
) }
137 fold_env inst_info deriv_info
(tyclds
:tyclds_s
)
138 = do { (tcg_env
, inst_info
', deriv_info
') <- tcTyClGroup tyclds
139 ; setGblEnv tcg_env
$
140 -- remaining groups are typechecked in the extended global env.
141 fold_env
(inst_info
' ++ inst_info
)
142 (deriv_info
' ++ deriv_info
)
145 tcTyClGroup
:: TyClGroup GhcRn
146 -> TcM
(TcGblEnv
, [InstInfo GhcRn
], [DerivInfo
])
147 -- Typecheck one strongly-connected component of type, class, and instance decls
148 -- See Note [TyClGroups and dependency analysis] in HsDecls
149 tcTyClGroup
(TyClGroup
{ group_tyclds
= tyclds
150 , group_roles
= roles
151 , group_instds
= instds
})
152 = do { let role_annots
= mkRoleAnnotEnv roles
154 -- Step 1: Typecheck the type/class declarations
155 ; traceTc
"-------- tcTyClGroup ------------" empty
156 ; traceTc
"Decls for" (ppr
(map (tcdName
. unLoc
) tyclds
))
157 ; tyclss
<- tcTyClDecls tyclds role_annots
159 -- Step 1.5: Make sure we don't have any type synonym cycles
160 ; traceTc
"Starting synonym cycle check" (ppr tyclss
)
161 ; this_uid
<- fmap thisPackage getDynFlags
162 ; checkSynCycles this_uid tyclss tyclds
163 ; traceTc
"Done synonym cycle check" (ppr tyclss
)
165 ; traceTc
"Starting family consistency check" (ppr tyclss
)
166 ; forM_ tyclss checkRecFamInstConsistency
167 ; traceTc
"Done family consistency" (ppr tyclss
)
169 -- Step 2: Perform the validity check on those types/classes
170 -- We can do this now because we are done with the recursive knot
171 -- Do it before Step 3 (adding implicit things) because the latter
172 -- expects well-formed TyCons
173 ; traceTc
"Starting validity check" (ppr tyclss
)
174 ; tyclss
<- mapM checkValidTyCl tyclss
175 ; traceTc
"Done validity check" (ppr tyclss
)
176 ; mapM_ (recoverM
(return ()) . checkValidRoleAnnots role_annots
) tyclss
177 -- See Note [Check role annotations in a second pass]
179 -- Step 3: Add the implicit things;
180 -- we want them in the environment because
181 -- they may be mentioned in interface files
182 ; tcExtendTyConEnv tyclss
$
183 do { gbl_env
<- tcAddImplicits tyclss
184 ; setGblEnv gbl_env
$
186 -- Step 4: check instance declarations
187 ; (gbl_env
, inst_info
, datafam_deriv_info
) <- tcInstDecls1 instds
189 ; return (gbl_env
, inst_info
, datafam_deriv_info
) } } }
191 tcTyClDecls
:: [LTyClDecl GhcRn
] -> RoleAnnotEnv
-> TcM
[TyCon
]
192 tcTyClDecls tyclds role_annots
193 = do { -- Step 1: kind-check this group and returns the final
194 -- (possibly-polymorphic) kind of each TyCon and Class
195 -- See Note [Kind checking for type and class decls]
196 tc_tycons
<- kcTyClGroup tyclds
197 ; traceTc
"tcTyAndCl generalized kinds" (vcat
(map ppr_tc_tycon tc_tycons
))
199 -- Step 2: type-check all groups together, returning
200 -- the final TyCons and Classes
202 -- NB: We have to be careful here to NOT eagerly unfold
203 -- type synonyms, as we have not tested for type synonym
204 -- loops yet and could fall into a black hole.
205 ; fixM
$ \ ~rec_tyclss
-> do
206 { tcg_env
<- getGblEnv
207 ; let roles
= inferRoles
(tcg_src tcg_env
) role_annots rec_tyclss
209 -- Populate environment with knot-tied ATyCon for TyCons
210 -- NB: if the decls mention any ill-staged data cons
211 -- (see Note [Recursion and promoting data constructors])
212 -- we will have failed already in kcTyClGroup, so no worries here
213 ; tcExtendRecEnv
(zipRecTyClss tc_tycons rec_tyclss
) $
215 -- Also extend the local type envt with bindings giving
216 -- the (polymorphic) kind of each knot-tied TyCon or Class
217 -- See Note [Type checking recursive type and class declarations]
218 tcExtendKindEnv
(foldl extendEnvWithTcTyCon emptyNameEnv tc_tycons
) $
220 -- Kind and type check declarations for this group
221 mapM (tcTyClDecl roles
) tyclds
224 ppr_tc_tycon tc
= parens
(sep
[ ppr
(tyConName tc
) <> comma
225 , ppr
(tyConBinders tc
) <> comma
226 , ppr
(tyConResKind tc
) ])
228 zipRecTyClss
:: [TcTyCon
]
229 -> [TyCon
] -- Knot-tied
231 -- Build a name-TyThing mapping for the TyCons bound by decls
232 -- being careful not to look at the knot-tied [TyThing]
233 -- The TyThings in the result list must have a visible ATyCon,
234 -- because typechecking types (in, say, tcTyClDecl) looks at
235 -- this outer constructor
236 zipRecTyClss tc_tycons rec_tycons
237 = [ (name
, ATyCon
(get name
)) | tc_tycon
<- tc_tycons
, let name
= getName tc_tycon
]
239 rec_tc_env
:: NameEnv TyCon
240 rec_tc_env
= foldr add_tc emptyNameEnv rec_tycons
242 add_tc
:: TyCon
-> NameEnv TyCon
-> NameEnv TyCon
243 add_tc tc env
= foldr add_one_tc env
(tc
: tyConATs tc
)
245 add_one_tc
:: TyCon
-> NameEnv TyCon
-> NameEnv TyCon
246 add_one_tc tc env
= extendNameEnv env
(tyConName tc
) tc
248 get name
= case lookupNameEnv rec_tc_env name
of
250 other
-> pprPanic
"zipRecTyClss" (ppr name
<+> ppr other
)
253 ************************************************************************
257 ************************************************************************
259 Note [Kind checking for type and class decls]
260 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
261 Kind checking is done thus:
263 1. Make up a kind variable for each parameter of the declarations,
264 and extend the kind environment (which is in the TcLclEnv)
266 2. Kind check the declarations
268 We need to kind check all types in the mutually recursive group
269 before we know the kind of the type variables. For example:
272 op :: D b => a -> b -> b
275 bop :: (Monad c) => ...
277 Here, the kind of the locally-polymorphic type variable "b"
278 depends on *all the uses of class D*. For example, the use of
279 Monad c in bop's type signature means that D must have kind Type->Type.
281 Note: we don't treat type synonyms specially (we used to, in the past);
282 in particular, even if we have a type synonym cycle, we still kind check
283 it normally, and test for cycles later (checkSynCycles). The reason
284 we can get away with this is because we have more systematic TYPE r
285 inference, which means that we can do unification between kinds that
286 aren't lifted (this historically was not true.)
288 The downside of not directly reading off the kinds off the RHS of
289 type synonyms in topological order is that we don't transparently
290 support making synonyms of types with higher-rank kinds. But
291 you can always specify a CUSK directly to make this work out.
292 See tc269 for an example.
296 This treatment of type synonyms only applies to Haskell 98-style synonyms.
297 General type functions can be recursive, and hence, appear in `alg_decls'.
299 The kind of an open type family is solely determinded by its kind signature;
300 hence, only kind signatures participate in the construction of the initial
301 kind environment (as constructed by `getInitialKind'). In fact, we ignore
302 instances of families altogether in the following. However, we need to include
303 the kinds of *associated* families into the construction of the initial kind
304 environment. (This is handled by `allDecls').
307 See also Note [Kind checking recursive type and class declarations]
312 -- Note [Missed opportunity to retain higher-rank kinds]
313 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
314 -- In 'kcTyClGroup', there is a missed opportunity to make kind
315 -- inference work in a few more cases. The idea is analogous
316 -- to Note [Single function non-recursive binding special-case]:
318 -- * If we have an SCC with a single decl, which is non-recursive,
319 -- instead of creating a unification variable representing the
320 -- kind of the decl and unifying it with the rhs, we can just
321 -- read the type directly of the rhs.
323 -- * Furthermore, we can update our SCC analysis to ignore
324 -- dependencies on declarations which have CUSKs: we don't
325 -- have to kind-check these all at once, since we can use
326 -- the CUSK to initialize the kind environment.
328 -- Unfortunately this requires reworking a bit of the code in
329 -- 'kcLTyClDecl' so I've decided to punt unless someone shouts about it.
331 kcTyClGroup
:: [LTyClDecl GhcRn
] -> TcM
[TcTyCon
]
333 -- Kind check this group, kind generalize, and return the resulting local env
334 -- This binds the TyCons and Classes of the group, but not the DataCons
335 -- See Note [Kind checking for type and class decls]
336 -- Third return value is Nothing if the tycon be unsaturated; otherwise,
339 = do { mod <- getModule
340 ; traceTc
"kcTyClGroup" (text
"module" <+> ppr
mod $$ vcat
(map ppr decls
))
343 -- 1. Bind kind variables for decls
344 -- 2. Kind-check decls
345 -- 3. Generalise the inferred kinds
346 -- See Note [Kind checking for type and class decls]
348 ; lcl_env
<- solveEqualities
$
349 do { -- Step 1: Bind kind variables for all decls
350 initial_kinds
<- getInitialKinds decls
351 ; traceTc
"kcTyClGroup: initial kinds" $
354 -- Step 2: Set extended envt, kind-check the decls
355 ; tcExtendKindEnv initial_kinds
$
356 do { mapM_ kcLTyClDecl decls
359 -- Step 3: generalisation
360 -- Kind checking done for this group
361 -- Now we have to kind generalize the flexis
362 ; res
<- concatMapM
(generaliseTCD
(tcl_env lcl_env
)) decls
364 ; traceTc
"kcTyClGroup result" (vcat
(map pp_res res
))
368 generalise
:: TcTypeEnv
-> Name
-> TcM TcTyCon
369 -- For polymorphic things this is a no-op
370 generalise kind_env name
371 = do { let tc
= case lookupNameEnv kind_env name
of
372 Just
(ATcTyCon tc
) -> tc
373 _
-> pprPanic
"kcTyClGroup" (ppr name
$$ ppr kind_env
)
374 kc_binders
= tyConBinders tc
375 kc_res_kind
= tyConResKind tc
376 kc_tyvars
= tyConTyVars tc
377 ; kvs
<- kindGeneralize
(mkTyConKind kc_binders kc_res_kind
)
378 ; let all_binders
= mkNamedTyConBinders Inferred kvs
++ kc_binders
380 ; (env
, all_binders
') <- zonkTyVarBindersX emptyZonkEnv all_binders
381 ; kc_res_kind
' <- zonkTcTypeToType env kc_res_kind
383 -- Make sure kc_kind' has the final, zonked kind variables
384 ; traceTc
"Generalise kind" $
385 vcat
[ ppr name
, ppr kc_binders
, ppr
(mkTyConKind kc_binders kc_res_kind
)
386 , ppr kvs
, ppr all_binders
, ppr kc_res_kind
387 , ppr all_binders
', ppr kc_res_kind
'
388 , ppr kc_tyvars
, ppr
(tcTyConScopedTyVars tc
)]
390 ; return (mkTcTyCon name all_binders
' kc_res_kind
'
391 (tcTyConScopedTyVars tc
)
394 generaliseTCD
:: TcTypeEnv
395 -> LTyClDecl GhcRn
-> TcM
[TcTyCon
]
396 generaliseTCD kind_env
(L _ decl
)
397 | ClassDecl
{ tcdLName
= (L _ name
), tcdATs
= ats
} <- decl
398 = do { first
<- generalise kind_env name
399 ; rest
<- mapM ((generaliseFamDecl kind_env
) . unLoc
) ats
400 ; return (first
: rest
) }
402 | FamDecl
{ tcdFam
= fam
} <- decl
403 = do { res
<- generaliseFamDecl kind_env fam
407 = do { res
<- generalise kind_env
(tcdName decl
)
410 generaliseFamDecl
:: TcTypeEnv
411 -> FamilyDecl GhcRn
-> TcM TcTyCon
412 generaliseFamDecl kind_env
(FamilyDecl
{ fdLName
= L _ name
})
413 = generalise kind_env name
415 pp_res tc
= ppr
(tyConName tc
) <+> dcolon
<+> ppr
(tyConKind tc
)
418 mkTcTyConEnv
:: TcTyCon
-> TcTypeEnv
419 mkTcTyConEnv tc
= unitNameEnv
(getName tc
) (ATcTyCon tc
)
421 extendEnvWithTcTyCon
:: TcTypeEnv
-> TcTyCon
-> TcTypeEnv
422 -- Makes a binding to put in the local envt, binding
423 -- a name to a TcTyCon
424 extendEnvWithTcTyCon env tc
425 = extendNameEnv env
(getName tc
) (ATcTyCon tc
)
428 mkPromotionErrorEnv
:: [LTyClDecl GhcRn
] -> TcTypeEnv
429 -- Maps each tycon/datacon to a suitable promotion error
430 -- tc :-> APromotionErr TyConPE
431 -- dc :-> APromotionErr RecDataConPE
432 -- See Note [Recursion and promoting data constructors]
434 mkPromotionErrorEnv decls
435 = foldr (plusNameEnv
. mk_prom_err_env
. unLoc
)
438 mk_prom_err_env
:: TyClDecl GhcRn
-> TcTypeEnv
439 mk_prom_err_env
(ClassDecl
{ tcdLName
= L _ nm
, tcdATs
= ats
})
440 = unitNameEnv nm
(APromotionErr ClassPE
)
442 mkNameEnv
[ (name
, APromotionErr TyConPE
)
443 | L _
(FamilyDecl
{ fdLName
= L _ name
}) <- ats
]
445 mk_prom_err_env
(DataDecl
{ tcdLName
= L _ name
446 , tcdDataDefn
= HsDataDefn
{ dd_cons
= cons
} })
447 = unitNameEnv name
(APromotionErr TyConPE
)
449 mkNameEnv
[ (con
, APromotionErr RecDataConPE
)
450 | L _ con
' <- cons
, L _ con
<- getConNames con
' ]
453 = unitNameEnv
(tcdName decl
) (APromotionErr TyConPE
)
454 -- Works for family declarations too
457 getInitialKinds
:: [LTyClDecl GhcRn
] -> TcM
(NameEnv TcTyThing
)
458 -- Maps each tycon to its initial kind,
459 -- and each datacon to a suitable promotion error
460 -- tc :-> ATcTyCon (tc:initial_kind)
461 -- dc :-> APromotionErr RecDataConPE
462 -- See Note [Recursion and promoting data constructors]
464 getInitialKinds decls
465 = tcExtendKindEnv promotion_err_env
$
466 do { tc_kinds
<- mapM (addLocM getInitialKind
) decls
467 ; return (foldl plusNameEnv promotion_err_env tc_kinds
) }
469 promotion_err_env
= mkPromotionErrorEnv decls
471 getInitialKind
:: TyClDecl GhcRn
472 -> TcM
(NameEnv TcTyThing
)
473 -- Allocate a fresh kind variable for each TyCon and Class
474 -- For each tycon, return a NameEnv with
475 -- name :-> ATcTyCon (TcCyCon with kind k))
476 -- where k is the kind of tc, derived from the LHS
477 -- of the definition (and probably including
478 -- kind unification variables)
479 -- Example: data T a b = ...
480 -- return (T, kv1 -> kv2 -> kv3)
482 -- This pass deals with (ie incorporates into the kind it produces)
483 -- * The kind signatures on type-variable binders
484 -- * The result kinds signature on a TyClDecl
486 -- No family instances are passed to getInitialKinds
488 getInitialKind decl
@(ClassDecl
{ tcdLName
= L _ name
, tcdTyVars
= ktvs
, tcdATs
= ats
})
489 = do { let cusk
= hsDeclHasCusk decl
490 ; (tycon
, inner_prs
) <-
491 kcHsTyVarBndrs name ClassFlavour cusk
True ktvs
$
492 do { inner_prs
<- getFamDeclInitialKinds
(Just cusk
) ats
493 ; return (constraintKind
, inner_prs
) }
494 ; return (extendEnvWithTcTyCon inner_prs tycon
) }
496 getInitialKind decl
@(DataDecl
{ tcdLName
= L _ name
498 , tcdDataDefn
= HsDataDefn
{ dd_kindSig
= m_sig
499 , dd_ND
= new_or_data
} })
501 kcHsTyVarBndrs name flav
(hsDeclHasCusk decl
) True ktvs
$
502 do { res_k
<- case m_sig
of
503 Just ksig
-> tcLHsKindSig ksig
504 Nothing
-> return liftedTypeKind
505 ; return (res_k
, ()) }
506 ; return (mkTcTyConEnv tycon
) }
508 flav
= case new_or_data
of
509 NewType
-> NewtypeFlavour
510 DataType
-> DataTypeFlavour
512 getInitialKind
(FamDecl
{ tcdFam
= decl
})
513 = getFamDeclInitialKind Nothing decl
515 getInitialKind decl
@(SynDecl
{ tcdLName
= L _ name
518 = do { (tycon
, _
) <- kcHsTyVarBndrs name TypeSynonymFlavour
521 do { res_k
<- case kind_annotation rhs
of
522 Nothing
-> newMetaKindVar
523 Just ksig
-> tcLHsKindSig ksig
524 ; return (res_k
, ()) }
525 ; return (mkTcTyConEnv tycon
) }
527 -- Keep this synchronized with 'hsDeclHasCusk'.
528 kind_annotation
(L _ ty
) = case ty
of
529 HsParTy lty
-> kind_annotation lty
530 HsKindSig _ k
-> Just k
533 ---------------------------------
534 getFamDeclInitialKinds
:: Maybe Bool -- if assoc., CUSKness of assoc. class
535 -> [LFamilyDecl GhcRn
]
537 getFamDeclInitialKinds mb_cusk decls
538 = do { tc_kinds
<- mapM (addLocM
(getFamDeclInitialKind mb_cusk
)) decls
539 ; return (foldr plusNameEnv emptyNameEnv tc_kinds
) }
541 getFamDeclInitialKind
:: Maybe Bool -- if assoc., CUSKness of assoc. class
544 getFamDeclInitialKind mb_cusk decl
@(FamilyDecl
{ fdLName
= L _ name
546 , fdResultSig
= L _ resultSig
549 kcHsTyVarBndrs name flav cusk
True ktvs
$
550 do { res_k
<- case resultSig
of
551 KindSig ki
-> tcLHsKindSig ki
552 TyVarSig
(L _
(KindedTyVar _ ki
)) -> tcLHsKindSig ki
553 _
-- open type families have * return kind by default
554 | tcFlavourIsOpen flav
-> return liftedTypeKind
555 -- closed type families have their return kind inferred
557 |
otherwise -> newMetaKindVar
558 ; return (res_k
, ()) }
559 ; return (mkTcTyConEnv tycon
) }
561 cusk
= famDeclHasCusk mb_cusk decl
563 DataFamily
-> DataFamilyFlavour
564 OpenTypeFamily
-> OpenTypeFamilyFlavour
565 ClosedTypeFamily _
-> ClosedTypeFamilyFlavour
567 ------------------------------------------------------------------------
568 kcLTyClDecl
:: LTyClDecl GhcRn
-> TcM
()
569 -- See Note [Kind checking for type and class decls]
570 kcLTyClDecl
(L loc decl
)
573 do { traceTc
"kcTyClDecl {" (ppr
(tyClDeclLName decl
))
575 ; traceTc
"kcTyClDecl done }" (ppr
(tyClDeclLName decl
)) }
577 kcTyClDecl
:: TyClDecl GhcRn
-> TcM
()
578 -- This function is used solely for its side effect on kind variables
579 -- NB kind signatures on the type variables and
580 -- result kind signature have already been dealt with
581 -- by getInitialKind, so we can ignore them here.
583 kcTyClDecl
(DataDecl
{ tcdLName
= L _ name
, tcdDataDefn
= defn
})
584 | HsDataDefn
{ dd_cons
= cons
, dd_kindSig
= Just _
} <- defn
585 = mapM_ (wrapLocM kcConDecl
) cons
586 -- hs_tvs and dd_kindSig already dealt with in getInitialKind
587 -- If dd_kindSig is Just, this must be a GADT-style decl,
588 -- (see invariants of DataDefn declaration)
589 -- so (a) we don't need to bring the hs_tvs into scope, because the
590 -- ConDecls bind all their own variables
591 -- (b) dd_ctxt is not allowed for GADT-style decls, so we can ignore it
593 | HsDataDefn
{ dd_ctxt
= ctxt
, dd_cons
= cons
} <- defn
594 = kcTyClTyVars name
$
595 do { _
<- tcHsContext ctxt
596 ; mapM_ (wrapLocM kcConDecl
) cons
}
598 kcTyClDecl
(SynDecl
{ tcdLName
= L _ name
, tcdRhs
= lrhs
})
599 = kcTyClTyVars name
$
600 do { syn_tc
<- kcLookupTcTyCon name
601 -- NB: check against the result kind that we allocated
602 -- in getInitialKinds.
603 ; discardResult
$ tcCheckLHsType lrhs
(tyConResKind syn_tc
) }
605 kcTyClDecl
(ClassDecl
{ tcdLName
= L _ name
606 , tcdCtxt
= ctxt
, tcdSigs
= sigs
})
607 = kcTyClTyVars name
$
608 do { _
<- tcHsContext ctxt
609 ; mapM_ (wrapLocM kc_sig
) sigs
}
611 kc_sig
(ClassOpSig _ nms op_ty
) = kcHsSigType nms op_ty
614 kcTyClDecl
(FamDecl
(FamilyDecl
{ fdLName
= L _ fam_tc_name
615 , fdInfo
= fd_info
}))
616 -- closed type families look at their equations, but other families don't
619 ClosedTypeFamily
(Just eqns
) ->
620 do { fam_tc
<- kcLookupTcTyCon fam_tc_name
621 ; mapM_ (kcTyFamInstEqn fam_tc
) eqns
}
625 kcConDecl
:: ConDecl GhcRn
-> TcM
()
626 kcConDecl
(ConDeclH98
{ con_name
= name
, con_qvars
= ex_tvs
627 , con_cxt
= ex_ctxt
, con_details
= details
})
628 = addErrCtxt
(dataConCtxtName
[name
]) $
629 -- the 'False' says that the existentials don't have a CUSK, as the
630 -- concept doesn't really apply here. We just need to bring the variables
631 -- into scope. (Similarly, the choice of PromotedDataConFlavour isn't
632 -- particularly important.)
633 do { _
<- kcHsTyVarBndrs
(unLoc name
) PromotedDataConFlavour
635 ((fromMaybe emptyLHsQTvs ex_tvs
)) $
636 do { _
<- tcHsContext
(fromMaybe (noLoc
[]) ex_ctxt
)
637 ; mapM_ (tcHsOpenType
. getBangType
) (hsConDeclArgTys details
)
638 ; return (panic
"kcConDecl", ()) }
639 -- We don't need to check the telescope here, because that's
643 kcConDecl
(ConDeclGADT
{ con_names
= names
645 = addErrCtxt
(dataConCtxtName names
) $
646 do { _
<- tcGadtSigType
(ppr names
) (unLoc
$ head names
) ty
647 -- Even though the data constructor's type is closed, we
648 -- must still call tcGadtSigType, because that influences
649 -- the inferred kind of the /type/ constructor. Example:
651 -- MkT :: f a -> T f a
652 -- If we don't look at MkT we won't get the correct kind
653 -- for the type constructor T
657 Note [Recursion and promoting data constructors]
658 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
659 We don't want to allow promotion in a strongly connected component
663 data T f = K (f (K Any))
665 When kind checking the `data T' declaration the local env contains the
667 T -> ATcTyCon <some initial kind>
670 APromotionErr is only used for DataCons, and only used during type checking
674 ************************************************************************
676 \subsection{Type checking}
678 ************************************************************************
680 Note [Type checking recursive type and class declarations]
681 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
682 At this point we have completed *kind-checking* of a mutually
683 recursive group of type/class decls (done in kcTyClGroup). However,
684 we discarded the kind-checked types (eg RHSs of data type decls);
685 note that kcTyClDecl returns (). There are two reasons:
687 * It's convenient, because we don't have to rebuild a
688 kinded HsDecl (a fairly elaborate type)
690 * It's necessary, because after kind-generalisation, the
691 TyCons/Classes may now be kind-polymorphic, and hence need
692 to be given kind arguments.
695 data T f a = MkT (f a) (T f a)
696 During kind-checking, we give T the kind T :: k1 -> k2 -> *
697 and figure out constraints on k1, k2 etc. Then we generalise
698 to get T :: forall k. (k->*) -> k -> *
699 So now the (T f a) in the RHS must be elaborated to (T k f a).
701 However, during tcTyClDecl of T (above) we will be in a recursive
702 "knot". So we aren't allowed to look at the TyCon T itself; we are only
703 allowed to put it (lazily) in the returned structures. But when
704 kind-checking the RHS of T's decl, we *do* need to know T's kind (so
705 that we can correctly elaboarate (T k f a). How can we get T's kind
706 without looking at T? Delicate answer: during tcTyClDecl, we extend
708 *Global* env with T -> ATyCon (the (not yet built) final TyCon for T)
709 *Local* env with T -> ATcTyCon (TcTyCon with the polymorphic kind of T)
713 * During TcHsType.kcTyVar we look in the *local* env, to get the
716 * But in TcHsType.ds_type (and ds_var_app in particular) we look in
717 the *global* env to get the TyCon. But we must be careful not to
718 force the TyCon or we'll get a loop.
720 This fancy footwork (with two bindings for T) is only necessary for the
721 TyCons or Classes of this recursive group. Earlier, finished groups,
722 live in the global env only.
724 See also Note [Kind checking recursive type and class declarations]
726 Note [Kind checking recursive type and class declarations]
727 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
728 Before we can type-check the decls, we must kind check them. This
729 is done by establishing an "initial kind", which is a rather uninformed
730 guess at a tycon's kind (by counting arguments, mainly) and then
731 using this initial kind for recursive occurrences.
733 The initial kind is stored in exactly the same way during kind-checking
734 as it is during type-checking (Note [Type checking recursive type and class
735 declarations]): in the *local* environment, with ATcTyCon. But we still
736 must store *something* in the *global* environment. Even though we
737 discard the result of kind-checking, we sometimes need to produce error
738 messages. These error messages will want to refer to the tycons being
739 checked, except that they don't exist yet, and it would be Terribly
740 Annoying to get the error messages to refer back to HsSyn. So we
741 create a TcTyCon and put it in the global env. This tycon can
742 print out its name and knows its kind,
743 but any other action taken on it will panic. Note
744 that TcTyCons are *not* knot-tied, unlike the rather valid but
745 knot-tied ones that occur during type-checking.
747 Note [Declarations for wired-in things]
748 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
749 For wired-in things we simply ignore the declaration
750 and take the wired-in information. That avoids complications.
751 e.g. the need to make the data constructor worker name for
752 a constraint tuple match the wired-in one
755 tcTyClDecl
:: RolesInfo
-> LTyClDecl GhcRn
-> TcM TyCon
756 tcTyClDecl roles_info
(L loc decl
)
757 | Just thing
<- wiredInNameTyThing_maybe
(tcdName decl
)
758 = case thing
of -- See Note [Declarations for wired-in things]
759 ATyCon tc
-> return tc
760 _
-> pprPanic
"tcTyClDecl" (ppr thing
)
763 = setSrcSpan loc
$ tcAddDeclCtxt decl
$
764 do { traceTc
"tcTyAndCl-x" (ppr decl
)
765 ; tcTyClDecl1 Nothing roles_info decl
}
767 -- "type family" declarations
768 tcTyClDecl1
:: Maybe Class
-> RolesInfo
-> TyClDecl GhcRn
-> TcM TyCon
769 tcTyClDecl1 parent _roles_info
(FamDecl
{ tcdFam
= fd
})
770 = tcFamDecl1 parent fd
772 -- "type" synonym declaration
773 tcTyClDecl1 _parent roles_info
774 (SynDecl
{ tcdLName
= L _ tc_name
, tcdRhs
= rhs
})
775 = ASSERT
( isNothing _parent
)
776 tcTyClTyVars tc_name
$ \ binders res_kind
->
777 tcTySynRhs roles_info tc_name binders res_kind rhs
779 -- "data/newtype" declaration
780 tcTyClDecl1 _parent roles_info
781 (DataDecl
{ tcdLName
= L _ tc_name
, tcdDataDefn
= defn
})
782 = ASSERT
( isNothing _parent
)
783 tcTyClTyVars tc_name
$ \ tycon_binders res_kind
->
784 tcDataDefn roles_info tc_name tycon_binders res_kind defn
786 tcTyClDecl1 _parent roles_info
787 (ClassDecl
{ tcdLName
= L _ class_name
788 , tcdCtxt
= ctxt
, tcdMeths
= meths
789 , tcdFDs
= fundeps
, tcdSigs
= sigs
790 , tcdATs
= ats
, tcdATDefs
= at_defs
})
791 = ASSERT
( isNothing _parent
)
792 do { clas
<- fixM
$ \ clas
->
793 -- We need the knot because 'clas' is passed into tcClassATs
794 tcTyClTyVars class_name
$ \ binders res_kind
->
795 do { MASSERT
( isConstraintKind res_kind
)
796 ; traceTc
"tcClassDecl 1" (ppr class_name
$$ ppr binders
)
797 ; let tycon_name
= class_name
-- We use the same name
798 roles
= roles_info tycon_name
-- for TyCon and Class
800 ; ctxt
' <- solveEqualities
$ tcHsContext ctxt
801 ; ctxt
' <- zonkTcTypeToTypes emptyZonkEnv ctxt
'
802 -- Squeeze out any kind unification variables
803 ; fds
' <- mapM (addLocM tc_fundep
) fundeps
804 ; sig_stuff
<- tcClassSigs class_name sigs meths
805 ; at_stuff
<- tcClassATs class_name clas ats at_defs
806 ; mindef
<- tcClassMinimalDef class_name sigs sig_stuff
807 -- TODO: Allow us to distinguish between abstract class,
808 -- and concrete class with no methods (maybe by
809 -- specifying a trailing where or not
810 ; is_boot
<- tcIsHsBootOrSig
811 ; let body | is_boot
, null ctxt
', null at_stuff
, null sig_stuff
814 = Just
(ctxt
', at_stuff
, sig_stuff
, mindef
)
815 ; clas
<- buildClass class_name binders roles fds
' body
816 ; traceTc
"tcClassDecl" (ppr fundeps
$$ ppr binders
$$
820 ; return (classTyCon clas
) }
822 tc_fundep
(tvs1
, tvs2
) = do { tvs1
' <- mapM (tcLookupTyVar
. unLoc
) tvs1
;
823 ; tvs2
' <- mapM (tcLookupTyVar
. unLoc
) tvs2
;
824 ; return (tvs1
', tvs2
') }
826 tcFamDecl1
:: Maybe Class
-> FamilyDecl GhcRn
-> TcM TyCon
827 tcFamDecl1 parent
(FamilyDecl
{ fdInfo
= fam_info
, fdLName
= tc_lname
@(L _ tc_name
)
828 , fdResultSig
= L _ sig
829 , fdInjectivityAnn
= inj
})
830 | DataFamily
<- fam_info
831 = tcTyClTyVars tc_name
$ \ binders res_kind
-> do
832 { traceTc
"data family:" (ppr tc_name
)
833 ; checkFamFlag tc_name
834 ; (extra_binders
, real_res_kind
) <- tcDataKindSig
False res_kind
835 ; tc_rep_name
<- newTyConRepName tc_name
836 ; let tycon
= mkFamilyTyCon tc_name
(binders `chkAppend` extra_binders
)
838 (resultVariableName sig
)
839 (DataFamilyTyCon tc_rep_name
)
843 | OpenTypeFamily
<- fam_info
844 = tcTyClTyVars tc_name
$ \ binders res_kind
-> do
845 { traceTc
"open type family:" (ppr tc_name
)
846 ; checkFamFlag tc_name
847 ; inj
' <- tcInjectivity binders inj
848 ; let tycon
= mkFamilyTyCon tc_name binders res_kind
849 (resultVariableName sig
) OpenSynFamilyTyCon
853 | ClosedTypeFamily mb_eqns
<- fam_info
854 = -- Closed type families are a little tricky, because they contain the definition
855 -- of both the type family and the equations for a CoAxiom.
856 do { traceTc
"Closed type family:" (ppr tc_name
)
857 -- the variables in the header scope only over the injectivity
858 -- declaration but this is not involved here
859 ; (inj
', binders
, res_kind
)
860 <- tcTyClTyVars tc_name
861 $ \ binders res_kind
->
862 do { inj
' <- tcInjectivity binders inj
863 ; return (inj
', binders
, res_kind
) }
865 ; checkFamFlag tc_name
-- make sure we have -XTypeFamilies
867 -- If Nothing, this is an abstract family in a hs-boot file;
868 -- but eqns might be empty in the Just case as well
871 return $ mkFamilyTyCon tc_name binders res_kind
872 (resultVariableName sig
)
873 AbstractClosedSynFamilyTyCon parent
877 -- Process the equations, creating CoAxBranches
878 ; let tc_fam_tc
= mkTcTyCon tc_name binders res_kind
879 [] ClosedTypeFamilyFlavour
881 ; branches
<- mapM (tcTyFamInstEqn tc_fam_tc Nothing
) eqns
882 -- Do not attempt to drop equations dominated by earlier
883 -- ones here; in the case of mutual recursion with a data
884 -- type, we get a knot-tying failure. Instead we check
885 -- for this afterwards, in TcValidity.checkValidCoAxiom
888 -- Create a CoAxiom, with the correct src location. It is Vitally
889 -- Important that we do not pass the branches into
890 -- newFamInstAxiomName. They have types that have been zonked inside
891 -- the knot and we will die if we look at them. This is OK here
892 -- because there will only be one axiom, so we don't need to
893 -- differentiate names.
894 -- See [Zonking inside the knot] in TcHsType
895 ; co_ax_name
<- newFamInstAxiomName tc_lname
[]
898 |
null eqns
= Nothing
-- mkBranchedCoAxiom fails on empty list
899 |
otherwise = Just
(mkBranchedCoAxiom co_ax_name fam_tc branches
)
901 fam_tc
= mkFamilyTyCon tc_name binders res_kind
(resultVariableName sig
)
902 (ClosedSynFamilyTyCon mb_co_ax
) parent inj
'
904 -- We check for instance validity later, when doing validity
905 -- checking for the tycon. Exception: checking equations
906 -- overlap done by dropDominatedAxioms
909 |
otherwise = panic
"tcFamInst1" -- Silence pattern-exhaustiveness checker
912 -- | Maybe return a list of Bools that say whether a type family was declared
913 -- injective in the corresponding type arguments. Length of the list is equal to
914 -- the number of arguments (including implicit kind/coercion arguments).
916 -- N means that a function is injective in its Nth argument. False means it is
918 tcInjectivity
:: [TyConBinder
] -> Maybe (LInjectivityAnn GhcRn
)
920 tcInjectivity _ Nothing
921 = return NotInjective
923 -- User provided an injectivity annotation, so for each tyvar argument we
924 -- check whether a type family was declared injective in that argument. We
925 -- return a list of Bools, where True means that corresponding type variable
926 -- was mentioned in lInjNames (type family is injective in that argument) and
927 -- False means that it was not mentioned in lInjNames (type family is not
928 -- injective in that type variable). We also extend injectivity information to
929 -- kind variables, so if a user declares:
931 -- type family F (a :: k1) (b :: k2) = (r :: k3) | r -> a
933 -- then we mark both `a` and `k1` as injective.
934 -- NB: the return kind is considered to be *input* argument to a type family.
935 -- Since injectivity allows to infer input arguments from the result in theory
936 -- we should always mark the result kind variable (`k3` in this example) as
937 -- injective. The reason is that result type has always an assigned kind and
938 -- therefore we can always infer the result kind if we know the result type.
939 -- But this does not seem to be useful in any way so we don't do it. (Another
940 -- reason is that the implementation would not be straightforward.)
941 tcInjectivity tcbs
(Just
(L loc
(InjectivityAnn _ lInjNames
)))
943 do { let tvs
= binderVars tcbs
944 ; dflags
<- getDynFlags
945 ; checkTc
(xopt LangExt
.TypeFamilyDependencies dflags
)
946 (text
"Illegal injectivity annotation" $$
947 text
"Use TypeFamilyDependencies to allow this")
948 ; inj_tvs
<- mapM (tcLookupTyVar
. unLoc
) lInjNames
949 ; inj_tvs
<- mapM zonkTcTyVarToTyVar inj_tvs
-- zonk the kinds
950 ; let inj_ktvs
= filterVarSet isTyVar
$ -- no injective coercion vars
951 closeOverKinds
(mkVarSet inj_tvs
)
952 ; let inj_bools
= map (`elemVarSet` inj_ktvs
) tvs
953 ; traceTc
"tcInjectivity" (vcat
[ ppr tvs
, ppr lInjNames
, ppr inj_tvs
954 , ppr inj_ktvs
, ppr inj_bools
])
955 ; return $ Injective inj_bools
}
957 tcTySynRhs
:: RolesInfo
959 -> [TyConBinder
] -> Kind
960 -> LHsType GhcRn
-> TcM TyCon
961 tcTySynRhs roles_info tc_name binders res_kind hs_ty
962 = do { env
<- getLclEnv
963 ; traceTc
"tc-syn" (ppr tc_name
$$ ppr
(tcl_env env
))
964 ; rhs_ty
<- solveEqualities
$ tcCheckLHsType hs_ty res_kind
965 ; rhs_ty
<- zonkTcTypeToType emptyZonkEnv rhs_ty
966 ; let roles
= roles_info tc_name
967 tycon
= buildSynTyCon tc_name binders res_kind roles rhs_ty
970 tcDataDefn
:: RolesInfo
-> Name
971 -> [TyConBinder
] -> Kind
972 -> HsDataDefn GhcRn
-> TcM TyCon
973 -- NB: not used for newtype/data instances (whether associated or not)
974 tcDataDefn roles_info
975 tc_name tycon_binders res_kind
976 (HsDataDefn
{ dd_ND
= new_or_data
, dd_cType
= cType
977 , dd_ctxt
= ctxt
, dd_kindSig
= mb_ksig
979 = do { (extra_bndrs
, real_res_kind
) <- tcDataKindSig
True res_kind
980 ; let final_bndrs
= tycon_binders `chkAppend` extra_bndrs
981 roles
= roles_info tc_name
983 ; stupid_tc_theta
<- solveEqualities
$ tcHsContext ctxt
984 ; stupid_theta
<- zonkTcTypeToTypes emptyZonkEnv
986 ; kind_signatures
<- xoptM LangExt
.KindSignatures
987 ; tcg_env
<- getGblEnv
988 ; let hsc_src
= tcg_src tcg_env
990 -- Check that we don't use kind signatures without Glasgow extensions
991 ; when (isJust mb_ksig
) $
992 checkTc
(kind_signatures
) (badSigTyDecl tc_name
)
994 ; gadt_syntax
<- dataDeclChecks tc_name new_or_data stupid_theta cons
996 ; tycon
<- fixM
$ \ tycon
-> do
997 { let res_ty
= mkTyConApp tycon
(mkTyVarTys
(binderVars final_bndrs
))
998 ; data_cons
<- tcConDecls tycon
(final_bndrs
, res_ty
) cons
999 ; tc_rhs
<- mk_tc_rhs hsc_src tycon data_cons
1000 ; tc_rep_nm
<- newTyConRepName tc_name
1001 ; return (mkAlgTyCon tc_name
1007 (VanillaAlgTyCon tc_rep_nm
)
1009 ; traceTc
"tcDataDefn" (ppr tc_name
$$ ppr tycon_binders
$$ ppr extra_bndrs
)
1012 -- In hs-boot, a 'data' declaration with no constructors
1013 -- indicates an nominally distinct abstract data type.
1014 mk_tc_rhs HsBootFile _
[]
1015 = return AbstractTyCon
1017 mk_tc_rhs HsigFile _
[] -- ditto
1018 = return AbstractTyCon
1020 mk_tc_rhs _ tycon data_cons
1021 = case new_or_data
of
1022 DataType
-> return (mkDataTyConRhs data_cons
)
1023 NewType
-> ASSERT
( not (null data_cons
) )
1024 mkNewTyConRhs tc_name tycon
(head data_cons
)
1027 ************************************************************************
1029 Typechecking associated types (in class decls)
1030 (including the associated-type defaults)
1032 ************************************************************************
1034 Note [Associated type defaults]
1035 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1037 The following is an example of associated type defaults:
1042 type F a b = [a] -- Default
1044 Note that we can get default definitions only for type families, not data
1048 tcClassATs
:: Name
-- The class name (not knot-tied)
1049 -> Class
-- The class parent of this associated type
1050 -> [LFamilyDecl GhcRn
] -- Associated types.
1051 -> [LTyFamDefltEqn GhcRn
] -- Associated type defaults.
1052 -> TcM
[ClassATItem
]
1053 tcClassATs class_name cls ats at_defs
1054 = do { -- Complain about associated type defaults for non associated-types
1055 sequence_ [ failWithTc
(badATErr class_name n
)
1056 | n
<- map at_def_tycon at_defs
1057 , not (n `elemNameSet` at_names
) ]
1060 at_def_tycon
:: LTyFamDefltEqn GhcRn
-> Name
1061 at_def_tycon
(L _ eqn
) = unLoc
(feqn_tycon eqn
)
1063 at_fam_name
:: LFamilyDecl GhcRn
-> Name
1064 at_fam_name
(L _ decl
) = unLoc
(fdLName decl
)
1066 at_names
= mkNameSet
(map at_fam_name ats
)
1068 at_defs_map
:: NameEnv
[LTyFamDefltEqn GhcRn
]
1069 -- Maps an AT in 'ats' to a list of all its default defs in 'at_defs'
1070 at_defs_map
= foldr (\at_def nenv
-> extendNameEnv_C
(++) nenv
1071 (at_def_tycon at_def
) [at_def
])
1072 emptyNameEnv at_defs
1074 tc_at at
= do { fam_tc
<- addLocM
(tcFamDecl1
(Just cls
)) at
1075 ; let at_defs
= lookupNameEnv at_defs_map
(at_fam_name at
)
1077 ; atd
<- tcDefaultAssocDecl fam_tc at_defs
1078 ; return (ATI fam_tc atd
) }
1080 -------------------------
1081 tcDefaultAssocDecl
:: TyCon
-- ^ Family TyCon (not knot-tied)
1082 -> [LTyFamDefltEqn GhcRn
] -- ^ Defaults
1083 -> TcM
(Maybe (Type
, SrcSpan
)) -- ^ Type checked RHS
1084 tcDefaultAssocDecl _
[]
1085 = return Nothing
-- No default declaration
1087 tcDefaultAssocDecl _
(d1
:_
:_
)
1088 = failWithTc
(text
"More than one default declaration for"
1089 <+> ppr
(feqn_tycon
(unLoc d1
)))
1091 tcDefaultAssocDecl fam_tc
[L loc
(FamEqn
{ feqn_tycon
= lname
@(L _ tc_name
)
1092 , feqn_pats
= hs_tvs
1093 , feqn_fixity
= fixity
1094 , feqn_rhs
= rhs
})]
1095 | HsQTvs
{ hsq_implicit
= imp_vars
, hsq_explicit
= exp_vars
} <- hs_tvs
1096 = -- See Note [Type-checking default assoc decls]
1098 tcAddFamInstCtxt
(text
"default type instance") tc_name
$
1099 do { traceTc
"tcDefaultAssocDecl" (ppr tc_name
)
1100 ; let fam_tc_name
= tyConName fam_tc
1101 fam_arity
= length (tyConVisibleTyVars fam_tc
)
1103 -- Kind of family check
1104 ; ASSERT
( fam_tc_name
== tc_name
)
1105 checkTc
(isTypeFamilyTyCon fam_tc
) (wrongKindOfFamily fam_tc
)
1108 ; checkTc
(exp_vars `lengthIs` fam_arity
)
1109 (wrongNumberOfParmsErr fam_arity
)
1112 ; let all_vars
= imp_vars
++ map hsLTyVarName exp_vars
1113 pats
= map hsLTyVarBndrToType exp_vars
1114 pp_lhs
= pprFamInstLHS lname pats fixity
[] Nothing
1116 -- NB: Use tcFamTyPats, not tcTyClTyVars. The latter expects to get
1117 -- the LHsQTyVars used for declaring a tycon, but the names here
1120 -- You might think we should pass in some ClsInstInfo, as we're looking
1121 -- at an associated type. But this would be wrong, because an associated
1122 -- type default LHS can mention *different* type variables than the
1123 -- enclosing class. So it's treated more as a freestanding beast.
1125 <- tcFamTyPats fam_tc Nothing all_vars pats
1126 (kcTyFamEqnRhs Nothing pp_lhs rhs
) $
1127 \tvs pats rhs_kind
->
1128 do { rhs_ty
<- solveEqualities
$
1129 tcCheckLHsType rhs rhs_kind
1131 -- Zonk the patterns etc into the Type world
1132 ; (ze
, _
) <- zonkTyBndrsX emptyZonkEnv tvs
1133 ; pats
' <- zonkTcTypeToTypes ze pats
1134 ; rhs_ty
' <- zonkTcTypeToType ze rhs_ty
1135 ; return (pats
', rhs_ty
') }
1137 -- See Note [Type-checking default assoc decls]
1138 ; case tcMatchTys pats
' (mkTyVarTys
(tyConTyVars fam_tc
)) of
1139 Just subst
-> return (Just
(substTyUnchecked subst rhs_ty
, loc
) )
1140 Nothing
-> failWithTc
(defaultAssocKindErr fam_tc
)
1141 -- We check for well-formedness and validity later,
1142 -- in checkValidClass
1145 {- Note [Type-checking default assoc decls]
1146 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1147 Consider this default declaration for an associated type
1150 type F (a :: k) b :: *
1151 type F x y = Proxy x -> y
1153 Note that the class variable 'a' doesn't scope over the default assoc
1154 decl (rather oddly I think), and (less oddly) neither does the second
1155 argument 'b' of the associated type 'F', or the kind variable 'k'.
1156 Instead, the default decl is treated more like a top-level type
1159 However we store the default rhs (Proxy x -> y) in F's TyCon, using
1160 F's own type variables, so we need to convert it to (Proxy a -> b).
1161 We do this by calling tcMatchTys to match them up. This also ensures
1162 that x's kind matches a's and similarly for y and b. The error
1163 message isn't great, mind you. (Trac #11361 was caused by not doing a
1164 proper tcMatchTys here.) -}
1166 -------------------------
1167 kcTyFamInstEqn
:: TcTyCon
-> LTyFamInstEqn GhcRn
-> TcM
()
1168 kcTyFamInstEqn tc_fam_tc
1169 (L loc
(HsIB
{ hsib_vars
= tv_names
1170 , hsib_body
= FamEqn
{ feqn_tycon
= lname
@(L _ eqn_tc_name
)
1172 , feqn_fixity
= fixity
1173 , feqn_rhs
= hs_ty
}}))
1175 do { checkTc
(fam_name
== eqn_tc_name
)
1176 (wrongTyFamName fam_name eqn_tc_name
)
1178 tc_fam_ty_pats tc_fam_tc Nothing
-- not an associated type
1179 tv_names pats
(kcTyFamEqnRhs Nothing pp_lhs hs_ty
) }
1181 fam_name
= tyConName tc_fam_tc
1182 pp_lhs
= pprFamInstLHS lname pats fixity
[] Nothing
1184 -- Infer the kind of the type on the RHS of a type family eqn. Then use
1185 -- this kind to check the kind of the LHS of the equation. This is useful
1186 -- as the callback to tc_fam_ty_pats and the kind-checker to
1188 kcTyFamEqnRhs
:: Maybe ClsInstInfo
1189 -> SDoc
-- ^ Eqn LHS (for errors only)
1190 -> LHsType GhcRn
-- ^ Eqn RHS
1191 -> TcKind
-- ^ Inferred kind of left-hand side
1192 -> TcM
([TcType
], TcKind
) -- ^ New pats, inst'ed kind of left-hand side
1193 kcTyFamEqnRhs mb_clsinfo pp_lhs_ty rhs_hs_ty lhs_ki
1194 = do { -- It's still possible the lhs_ki has some foralls. Instantiate these away.
1195 (_lhs_ty
', new_pats
, insted_lhs_ki
)
1196 <- instantiateTyUntilN mb_kind_env
0 bogus_ty lhs_ki
1197 ; _
<- tcCheckLHsType rhs_hs_ty insted_lhs_ki
1199 ; return (new_pats
, insted_lhs_ki
) }
1201 mb_kind_env
= thdOf3
<$> mb_clsinfo
1203 bogus_ty
= pprPanic
"kcTyFamEqnRhs" (pp_lhs_ty
$$ ppr rhs_hs_ty
)
1205 tcTyFamInstEqn
:: TcTyCon
-> Maybe ClsInstInfo
-> LTyFamInstEqn GhcRn
1207 -- Needs to be here, not in TcInstDcls, because closed families
1208 -- (typechecked here) have TyFamInstEqns
1209 tcTyFamInstEqn fam_tc mb_clsinfo
1210 (L loc
(HsIB
{ hsib_vars
= tv_names
1211 , hsib_body
= FamEqn
{ feqn_tycon
= lname
@(L _ eqn_tc_name
)
1213 , feqn_fixity
= fixity
1214 , feqn_rhs
= hs_ty
}}))
1215 = ASSERT
( getName fam_tc
== eqn_tc_name
)
1217 tcFamTyPats fam_tc mb_clsinfo tv_names pats
1218 (kcTyFamEqnRhs mb_clsinfo pp_lhs hs_ty
) $
1219 \tvs pats res_kind
->
1220 do { rhs_ty
<- solveEqualities
$ tcCheckLHsType hs_ty res_kind
1222 ; (ze
, tvs
') <- zonkTyBndrsX emptyZonkEnv tvs
1223 ; pats
' <- zonkTcTypeToTypes ze pats
1224 ; rhs_ty
' <- zonkTcTypeToType ze rhs_ty
1225 ; traceTc
"tcTyFamInstEqn" (ppr fam_tc
<+> pprTyVars tvs
')
1226 -- don't print out the pats here, as they might be zonked inside the knot
1227 ; return (mkCoAxBranch tvs
' [] pats
' rhs_ty
'
1228 (map (const Nominal
) tvs
')
1231 pp_lhs
= pprFamInstLHS lname pats fixity
[] Nothing
1233 kcDataDefn
:: Maybe (VarEnv Kind
) -- ^ Possibly, instantiations for vars
1234 -- (associated types only)
1235 -> DataFamInstDecl GhcRn
1236 -> TcKind
-- ^ the kind of the tycon applied to pats
1237 -> TcM
([TcType
], TcKind
)
1238 -- ^ the kind signature might force instantiation
1239 -- of the tycon; this returns any extra args and the inst'ed kind
1240 -- See Note [Instantiating a family tycon]
1241 -- Used for 'data instance' only
1242 -- Ordinary 'data' is handled by kcTyClDec
1243 kcDataDefn mb_kind_env
1244 (DataFamInstDecl
{ dfid_eqn
= HsIB
{ hsib_body
=
1245 FamEqn
{ feqn_tycon
= fam_name
1247 , feqn_fixity
= fixity
1248 , feqn_rhs
= HsDataDefn
{ dd_ctxt
= ctxt
1250 , dd_kindSig
= mb_kind
} }}})
1252 = do { _
<- tcHsContext ctxt
1253 ; checkNoErrs
$ mapM_ (wrapLocM kcConDecl
) cons
1254 -- See Note [Failing early in kcDataDefn]
1255 ; exp_res_kind
<- case mb_kind
of
1256 Nothing
-> return liftedTypeKind
1257 Just k
-> tcLHsKindSig k
1259 -- The expected type might have a forall at the type. Normally, we
1260 -- can't skolemise in kinds because we don't have type-level lambda.
1261 -- But here, we're at the top-level of an instance declaration, so
1262 -- we actually have a place to put the regeneralised variables.
1263 -- Thus: skolemise away. cf. Inst.deeplySkolemise and TcUnify.tcSkolemise
1264 -- Examples in indexed-types/should_compile/T12369
1265 ; let (tvs_to_skolemise
, inner_res_kind
) = tcSplitForAllTys exp_res_kind
1267 ; (skol_subst
, tvs
') <- tcInstSkolTyVars tvs_to_skolemise
1268 -- we don't need to do anything substantive with the tvs' because the
1269 -- quantifyTyVars in tcFamTyPats will catch them.
1271 ; let inner_res_kind
' = substTyAddInScope skol_subst inner_res_kind
1272 tv_prs
= zip (map tyVarName tvs_to_skolemise
) tvs
'
1273 skol_info
= SigSkol InstDeclCtxt exp_res_kind tv_prs
1275 ; (ev_binds
, (_
, new_args
, co
))
1276 <- solveEqualities
$
1277 checkConstraints skol_info tvs
' [] $
1278 checkExpectedKindX mb_kind_env pp_fam_app
1279 bogus_ty res_k inner_res_kind
'
1281 ; let Pair lhs_ki rhs_ki
= tcCoercionKind co
1284 do { (_
, ev_binds
) <- zonkTcEvBinds emptyZonkEnv ev_binds
1285 ; MASSERT
( isEmptyTcEvBinds ev_binds
)
1286 ; lhs_ki
<- zonkTcType lhs_ki
1287 ; rhs_ki
<- zonkTcType rhs_ki
1288 ; MASSERT
( lhs_ki `tcEqType` rhs_ki
) }
1290 ; return (new_args
, lhs_ki
) }
1292 bogus_ty
= pprPanic
"kcDataDefn" (ppr fam_name
<+> ppr pats
)
1293 pp_fam_app
= pprFamInstLHS fam_name pats fixity
(unLoc ctxt
) mb_kind
1296 Kind check type patterns and kind annotate the embedded type variables.
1297 type instance F [a] = rhs
1299 * Here we check that a type instance matches its kind signature, but we do
1300 not check whether there is a pattern for each type index; the latter
1301 check is only required for type synonym instances.
1303 Note [tc_fam_ty_pats vs tcFamTyPats]
1304 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1305 tc_fam_ty_pats does the type checking of the patterns, but it doesn't
1306 zonk or generate any desugaring. It is used when kind-checking closed
1309 tcFamTyPats type checks the patterns, zonks, and then calls thing_inside
1310 to generate a desugaring. It is used during type-checking (not kind-checking).
1312 Note [Type-checking type patterns]
1313 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1314 When typechecking the patterns of a family instance declaration, we can't
1315 rely on using the family TyCon itself, because this is sometimes called
1316 from within a type-checking knot. (Specifically for closed type families.)
1317 The TcTyCon gives just enough information to do the job.
1319 See also Note [tc_fam_ty_pats vs tcFamTyPats]
1321 Note [Instantiating a family tycon]
1322 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1323 It's possible that kind-checking the result of a family tycon applied to
1324 its patterns will instantiate the tycon further. For example, we might
1327 type family F :: k where
1331 After checking (F :: forall k. k) (with no visible patterns), we still need
1332 to instantiate the k. With data family instances, this problem can be even
1333 more intricate, due to Note [Arity of data families] in FamInstEnv. See
1334 indexed-types/should_compile/T12369 for an example.
1336 So, the kind-checker must return both the new args (that is, Type
1337 (Type -> Type) for the equations above) and the instantiated kind.
1339 Because we don't need this information in the kind-checking phase of
1340 checking closed type families, we don't require these extra pieces of
1341 information in tc_fam_ty_pats. See also Note [tc_fam_ty_pats vs tcFamTyPats].
1343 Note [Failing early in kcDataDefn]
1344 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1345 We need to use checkNoErrs when calling kcConDecl. This is because kcConDecl
1346 calls tcConDecl, which checks that the return type of a GADT-like constructor
1347 is actually an instance of the type head. Without the checkNoErrs, potentially
1348 two bad things could happen:
1350 1) Duplicate error messages, because tcConDecl will be called again during
1351 *type* checking (as opposed to kind checking)
1352 2) If we just keep blindly forging forward after both kind checking and type
1353 checking, we can get a panic in rejigConRes. See Trac #8368.
1357 tc_fam_ty_pats
:: TcTyCon
-- The family TcTyCon
1358 -- See Note [Type-checking type patterns]
1359 -> Maybe ClsInstInfo
1360 -> [Name
] -- Bound kind/type variable names
1361 -> HsTyPats GhcRn
-- Type patterns
1362 -> (TcKind
-> TcM r
) -- Kind checker for RHS
1363 -> TcM
( [TcTyVar
] -- Returns the type-checked patterns,
1364 , [TcType
] -- the type variables that scope over
1365 , r
) -- them, and the thing inside
1366 -- Check the type patterns of a type or data family instance
1367 -- type instance F <pat1> <pat2> = <type>
1368 -- The 'tyvars' are the free type variables of pats
1370 -- NB: The family instance declaration may be an associated one,
1371 -- nested inside an instance decl, thus
1372 -- instance C [a] where
1374 -- In that case, the type variable 'a' will *already be in scope*
1375 -- (and, if C is poly-kinded, so will its kind parameter).
1377 tc_fam_ty_pats tc_fam_tc mb_clsinfo tv_names arg_pats
1379 = do { -- First, check the arity.
1380 -- If we wait until validity checking, we'll get kind
1381 -- errors below when an arity error will be much easier to
1383 let should_check_arity
1384 | DataFamilyFlavour
<- flav
= False
1385 -- why not check data families? See [Arity of data families] in FamInstEnv
1388 ; when should_check_arity
$
1389 checkTc
(arg_pats `lengthIs` vis_arity
) $
1390 wrongNumberOfParmsErr vis_arity
1391 -- report only explicit arguments
1393 -- Kind-check and quantify
1394 -- See Note [Quantifying over family patterns]
1395 ; (arg_tvs
, (args
, stuff
)) <- tcImplicitTKBndrs tv_names
$
1396 do { let loc
= nameSrcSpan name
1397 lhs_fun
= L loc
(HsTyVar NotPromoted
(L loc name
))
1398 fun_ty
= mkTyConApp tc_fam_tc
[]
1399 fun_kind
= tyConKind tc_fam_tc
1400 mb_kind_env
= thdOf3
<$> mb_clsinfo
1402 ; (_
, args
, res_kind_out
)
1403 <- tcInferApps typeLevelMode mb_kind_env
1404 lhs_fun fun_ty fun_kind arg_pats
1406 ; stuff
<- kind_checker res_kind_out
1408 ; return ((args
, stuff
), emptyVarSet
) }
1410 ; return (arg_tvs
, args
, stuff
) }
1412 name
= tyConName tc_fam_tc
1413 vis_arity
= length (tyConVisibleTyVars tc_fam_tc
)
1414 flav
= tyConFlavour tc_fam_tc
1416 -- See Note [tc_fam_ty_pats vs tcFamTyPats]
1417 tcFamTyPats
:: TcTyCon
1418 -> Maybe ClsInstInfo
1419 -> [Name
] -- Implicitly bound kind/type variable names
1420 -> HsTyPats GhcRn
-- Type patterns
1421 -> (TcKind
-> TcM
([TcType
], TcKind
))
1422 -- kind-checker for RHS
1423 -- See Note [Instantiating a family tycon]
1424 -> ( [TcTyVar
] -- Kind and type variables
1425 -> [TcType
] -- Kind and type arguments
1427 -> TcM a
) -- NB: You can use solveEqualities here.
1429 tcFamTyPats tc_fam_tc mb_clsinfo
1430 tv_names arg_pats kind_checker thing_inside
1431 = do { (fam_used_tvs
, typats
, (more_typats
, res_kind
))
1432 <- solveEqualities
$ -- See Note [Constraints in patterns]
1433 tc_fam_ty_pats tc_fam_tc mb_clsinfo
1434 tv_names arg_pats kind_checker
1436 {- TODO (RAE): This should be cleverer. Consider this:
1441 MkG :: F a ~ Bool => G a
1443 type family Foo (x :: G a) :: F a
1444 type instance Foo MkG = False
1446 This should probably be accepted. Yet the solveEqualities
1447 will fail, unable to solve (F a ~ Bool)
1448 We want to quantify over that proof.
1449 But see Note [Constraints in patterns]
1450 below, which is missing this piece. -}
1453 -- Find free variables (after zonking) and turn
1454 -- them into skolems, so that we don't subsequently
1455 -- replace a meta kind var with (Any *)
1456 -- Very like kindGeneralize
1457 ; let all_pats
= typats `chkAppend` more_typats
1458 ; vars
<- zonkTcTypesAndSplitDepVars all_pats
1459 ; qtkvs
<- quantifyTyVars emptyVarSet vars
1461 ; MASSERT
( isEmptyVarSet
$ coVarsOfTypes typats
)
1462 -- This should be the case, because otherwise the solveEqualities
1463 -- above would fail. TODO (RAE): Update once the solveEqualities
1466 ; traceTc
"tcFamTyPats" (ppr
(getName tc_fam_tc
)
1467 $$ ppr all_pats
$$ ppr qtkvs
)
1468 -- Don't print out too much, as we might be in the knot
1470 -- See Note [Free-floating kind vars] in TcHsType
1471 ; let tc_flav
= tyConFlavour tc_fam_tc
1472 all_mentioned_tvs
= mkVarSet qtkvs
1473 -- qtkvs has all the tyvars bound by LHS
1475 unmentioned_tvs
= filterOut
(`elemVarSet` all_mentioned_tvs
)
1477 -- If there are tyvars left over, we can
1478 -- assume they're free-floating, since they
1479 -- aren't bound by a type pattern
1480 ; checkNoErrs
$ reportFloatingKvs
(getName tc_fam_tc
) tc_flav
1481 qtkvs unmentioned_tvs
1483 ; tcExtendTyVarEnv qtkvs
$
1484 -- Extend envt with TcTyVars not TyVars, because the
1485 -- kind checking etc done by thing_inside does not expect
1486 -- to encounter TyVars; it expects TcTyVars
1487 thing_inside qtkvs all_pats res_kind
}
1490 Note [Constraints in patterns]
1491 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1492 NB: This isn't the whole story. See comment in tcFamTyPats.
1494 At first glance, it seems there is a complicated story to tell in tcFamTyPats
1495 around constraint solving. After all, type family patterns can now do
1496 GADT pattern-matching, which is jolly complicated. But, there's a key fact
1497 which makes this all simple: everything is at top level! There cannot
1498 be untouchable type variables. There can't be weird interaction between
1499 case branches. There can't be global skolems.
1501 This means that the semantics of type-level GADT matching is a little
1502 different than term level. If we have
1509 type family F (a :: G k) :: k
1510 type instance F MkGBool = True
1514 axF : F Bool (MkGBool <Bool>) ~ True
1516 Simple! No casting on the RHS, because we can affect the kind parameter
1519 If we ever introduce local type families, this all gets a lot more
1520 complicated, and will end up looking awfully like term-level GADT
1526 Here is really what we want:
1528 The matcher really can't deal with covars in arbitrary spots in coercions.
1529 But it can deal with covars that are arguments to GADT data constructors.
1530 So we somehow want to allow covars only in precisely those spots, then use
1531 them as givens when checking the RHS. TODO (RAE): Implement plan.
1534 Note [Quantifying over family patterns]
1535 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1536 We need to quantify over two different lots of kind variables:
1538 First, the ones that come from the kinds of the tyvar args of
1539 tcTyVarBndrsKindGen, as usual
1542 -- Proxy :: forall k. k -> *
1543 data instance Dist (Proxy a) = DP
1544 -- Generates data DistProxy = DP
1545 -- ax8 k (a::k) :: Dist * (Proxy k a) ~ DistProxy k a
1546 -- The 'k' comes from the tcTyVarBndrsKindGen (a::k)
1548 Second, the ones that come from the kind argument of the type family
1549 which we pick up using the (tyCoVarsOfTypes typats) in the result of
1550 the thing_inside of tcHsTyvarBndrsGen.
1551 -- Any :: forall k. k
1552 data instance Dist Any = DA
1553 -- Generates data DistAny k = DA
1554 -- ax7 k :: Dist k (Any k) ~ DistAny k
1555 -- The 'k' comes from kindGeneralizeKinds (Any k)
1557 Note [Quantified kind variables of a family pattern]
1558 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1559 Consider type family KindFam (p :: k1) (q :: k1)
1560 data T :: Maybe k1 -> k2 -> *
1561 type instance KindFam (a :: Maybe k) b = T a b -> Int
1562 The HsBSig for the family patterns will be ([k], [a])
1564 Then in the family instance we want to
1565 * Bring into scope [ "k" -> k:*, "a" -> a:k ]
1566 * Kind-check the RHS
1567 * Quantify the type instance over k and k', as well as a,b, thus
1568 type instance [k, k', a:Maybe k, b:k']
1569 KindFam (Maybe k) k' a b = T k k' a b -> Int
1571 Notice that in the third step we quantify over all the visibly-mentioned
1572 type variables (a,b), but also over the implicitly mentioned kind variables
1573 (k, k'). In this case one is bound explicitly but often there will be
1574 none. The role of the kind signature (a :: Maybe k) is to add a constraint
1575 that 'a' must have that kind, and to bring 'k' into scope.
1579 ************************************************************************
1583 ************************************************************************
1586 dataDeclChecks
:: Name
-> NewOrData
-> ThetaType
-> [LConDecl GhcRn
] -> TcM
Bool
1587 dataDeclChecks tc_name new_or_data stupid_theta cons
1588 = do { -- Check that we don't use GADT syntax in H98 world
1589 gadtSyntax_ok
<- xoptM LangExt
.GADTSyntax
1590 ; let gadt_syntax
= consUseGadtSyntax cons
1591 ; checkTc
(gadtSyntax_ok ||
not gadt_syntax
) (badGadtDecl tc_name
)
1593 -- Check that the stupid theta is empty for a GADT-style declaration
1594 ; checkTc
(null stupid_theta ||
not gadt_syntax
) (badStupidTheta tc_name
)
1596 -- Check that a newtype has exactly one constructor
1597 -- Do this before checking for empty data decls, so that
1598 -- we don't suggest -XEmptyDataDecls for newtypes
1599 ; checkTc
(new_or_data
== DataType || isSingleton cons
)
1600 (newtypeConError tc_name
(length cons
))
1602 -- Check that there's at least one condecl,
1603 -- or else we're reading an hs-boot file, or -XEmptyDataDecls
1604 ; empty_data_decls
<- xoptM LangExt
.EmptyDataDecls
1605 ; is_boot
<- tcIsHsBootOrSig
-- Are we compiling an hs-boot file?
1606 ; checkTc
(not (null cons
) || empty_data_decls || is_boot
)
1607 (emptyConDeclsErr tc_name
)
1608 ; return gadt_syntax
}
1611 -----------------------------------
1612 consUseGadtSyntax
:: [LConDecl a
] -> Bool
1613 consUseGadtSyntax
(L _
(ConDeclGADT
{ }) : _
) = True
1614 consUseGadtSyntax _
= False
1615 -- All constructors have same shape
1617 -----------------------------------
1618 tcConDecls
:: TyCon
-> ([TyConBinder
], Type
)
1619 -> [LConDecl GhcRn
] -> TcM
[DataCon
]
1620 -- Why both the tycon tyvars and binders? Because the tyvars
1621 -- have all the names and the binders have the visibilities.
1622 tcConDecls rep_tycon
(tmpl_bndrs
, res_tmpl
)
1623 = concatMapM
$ addLocM
$
1624 tcConDecl rep_tycon tmpl_bndrs res_tmpl
1626 tcConDecl
:: TyCon
-- Representation tycon. Knot-tied!
1627 -> [TyConBinder
] -> Type
1628 -- Return type template (with its template tyvars)
1629 -- (tvs, T tys), where T is the family TyCon
1633 tcConDecl rep_tycon tmpl_bndrs res_tmpl
1634 (ConDeclH98
{ con_name
= name
1635 , con_qvars
= hs_qvars
, con_cxt
= hs_ctxt
1636 , con_details
= hs_details
})
1637 = addErrCtxt
(dataConCtxtName
[name
]) $
1638 do { -- Get hold of the existential type variables
1639 -- e.g. data T a = forall (b::k) f. MkT a (f b)
1640 -- Here tmpl_bndrs = {a}
1643 ; let (hs_kvs
, hs_tvs
) = case hs_qvars
of
1645 Just
(HsQTvs
{ hsq_implicit
= kvs
, hsq_explicit
= tvs
})
1648 ; traceTc
"tcConDecl 1" (vcat
[ ppr name
, ppr hs_kvs
, ppr hs_tvs
])
1650 ; (imp_tvs
, (exp_tvs
, ctxt
, arg_tys
, field_lbls
, stricts
))
1651 <- solveEqualities
$
1652 tcImplicitTKBndrs hs_kvs
$
1653 tcExplicitTKBndrs hs_tvs
$ \ exp_tvs
->
1654 do { traceTc
"tcConDecl" (ppr name
<+> text
"tvs:" <+> ppr hs_tvs
)
1655 ; ctxt
<- tcHsContext
(fromMaybe (noLoc
[]) hs_ctxt
)
1656 ; btys
<- tcConArgs hs_details
1657 ; field_lbls
<- lookupConstructorFields
(unLoc name
)
1658 ; let (arg_tys
, stricts
) = unzip btys
1659 bound_vars
= allBoundVariabless ctxt `unionVarSet`
1660 allBoundVariabless arg_tys
1661 ; return ((exp_tvs
, ctxt
, arg_tys
, field_lbls
, stricts
), bound_vars
)
1664 -- exp_tvs have explicit, user-written binding sites
1665 -- imp_tvs are user-written kind variables, without an explicit binding site
1666 -- the kvs below are those kind variables entirely unmentioned by the user
1667 -- and discovered only by generalization
1669 -- Kind generalisation
1670 ; let all_user_tvs
= imp_tvs
++ exp_tvs
1671 ; vars
<- zonkTcTypeAndSplitDepVars
(mkSpecForAllTys all_user_tvs
$
1675 -- That type is a lie, of course. (It shouldn't end in ()!)
1676 -- And we could construct a proper result type from the info
1677 -- at hand. But the result would mention only the tmpl_tvs,
1678 -- and so it just creates more work to do it right. Really,
1679 -- we're doing this to get the right behavior around removing
1680 -- any vars bound in exp_binders.
1682 ; kvs
<- quantifyTyVars
(mkVarSet
(binderVars tmpl_bndrs
)) vars
1685 ; (ze
, qkvs
) <- zonkTyBndrsX emptyZonkEnv kvs
1686 ; (ze
, user_qtvs
) <- zonkTyBndrsX ze all_user_tvs
1687 ; arg_tys
<- zonkTcTypeToTypes ze arg_tys
1688 ; ctxt
<- zonkTcTypeToTypes ze ctxt
1690 ; fam_envs
<- tcGetFamInstEnvs
1692 -- Can't print univ_tvs, arg_tys etc, because we are inside the knot here
1693 ; traceTc
"tcConDecl 2" (ppr name
$$ ppr field_lbls
)
1695 ex_tvs
= mkTyVarBinders Inferred qkvs
++
1696 mkTyVarBinders Specified user_qtvs
1697 buildOneDataCon
(L _ name
) = do
1698 { is_infix
<- tcConIsInfixH98 name hs_details
1699 ; rep_nm
<- newTyConRepName name
1701 ; buildDataCon fam_envs name is_infix rep_nm
1702 stricts Nothing field_lbls
1703 (tyConTyVarBinders tmpl_bndrs
)
1705 [{- no eq_preds -}] ctxt arg_tys
1707 -- NB: we put data_tc, the type constructor gotten from the
1708 -- constructor type signature into the data constructor;
1709 -- that way checkValidDataCon can complain if it's wrong.
1711 ; traceTc
"tcConDecl 2" (ppr name
)
1712 ; mapM buildOneDataCon
[name
]
1715 tcConDecl rep_tycon tmpl_bndrs res_tmpl
1716 (ConDeclGADT
{ con_names
= names
, con_type
= ty
})
1717 = addErrCtxt
(dataConCtxtName names
) $
1718 do { traceTc
"tcConDecl 1" (ppr names
)
1719 ; (user_tvs
, ctxt
, stricts
, field_lbls
, arg_tys
, res_ty
,hs_details
)
1720 <- tcGadtSigType
(ppr names
) (unLoc
$ head names
) ty
1722 ; vars
<- zonkTcTypeAndSplitDepVars
(mkSpecForAllTys user_tvs
$
1726 ; tkvs
<- quantifyTyVars emptyVarSet vars
1729 ; (ze
, qtkvs
) <- zonkTyBndrsX emptyZonkEnv
(tkvs
++ user_tvs
)
1730 ; arg_tys
<- zonkTcTypeToTypes ze arg_tys
1731 ; ctxt
<- zonkTcTypeToTypes ze ctxt
1732 ; res_ty
<- zonkTcTypeToType ze res_ty
1734 ; let (univ_tvs
, ex_tvs
, eq_preds
, arg_subst
)
1735 = rejigConRes tmpl_bndrs res_tmpl qtkvs res_ty
1736 -- NB: this is a /lazy/ binding, so we pass four thunks to
1737 -- buildDataCon without yet forcing the guards in rejigConRes
1738 -- See Note [Checking GADT return types]
1740 -- See Note [Wrong visibility for GADTs]
1741 univ_bndrs
= mkTyVarBinders Specified univ_tvs
1742 ex_bndrs
= mkTyVarBinders Specified ex_tvs
1743 ctxt
' = substTys arg_subst ctxt
1744 arg_tys
' = substTys arg_subst arg_tys
1745 res_ty
' = substTy arg_subst res_ty
1747 ; fam_envs
<- tcGetFamInstEnvs
1749 -- Can't print univ_tvs, arg_tys etc, because we are inside the knot here
1750 ; traceTc
"tcConDecl 2" (ppr names
$$ ppr field_lbls
)
1752 buildOneDataCon
(L _ name
) = do
1753 { is_infix
<- tcConIsInfixGADT name hs_details
1754 ; rep_nm
<- newTyConRepName name
1756 ; buildDataCon fam_envs name is_infix
1758 stricts Nothing field_lbls
1759 univ_bndrs ex_bndrs eq_preds
1760 ctxt
' arg_tys
' res_ty
' rep_tycon
1761 -- NB: we put data_tc, the type constructor gotten from the
1762 -- constructor type signature into the data constructor;
1763 -- that way checkValidDataCon can complain if it's wrong.
1765 ; traceTc
"tcConDecl 2" (ppr names
)
1766 ; mapM buildOneDataCon names
1770 tcGadtSigType
:: SDoc
-> Name
-> LHsSigType GhcRn
1771 -> TcM
( [TcTyVar
], [PredType
],[HsSrcBang
], [FieldLabel
], [Type
], Type
1772 , HsConDetails
(LHsType GhcRn
)
1773 (Located
[LConDeclField GhcRn
]) )
1774 tcGadtSigType doc name ty
@(HsIB
{ hsib_vars
= vars
})
1775 = do { let (hs_details
', res_ty
', cxt
, gtvs
) = gadtDeclDetails ty
1776 ; (hs_details
, res_ty
) <- updateGadtResult failWithTc doc hs_details
' res_ty
'
1777 ; (imp_tvs
, (exp_tvs
, ctxt
, arg_tys
, res_ty
, field_lbls
, stricts
))
1778 <- solveEqualities
$
1779 tcImplicitTKBndrs vars
$
1780 tcExplicitTKBndrs gtvs
$ \ exp_tvs
->
1781 do { ctxt
<- tcHsContext cxt
1782 ; btys
<- tcConArgs hs_details
1783 ; ty
' <- tcHsLiftedType res_ty
1784 ; field_lbls
<- lookupConstructorFields name
1785 ; let (arg_tys
, stricts
) = unzip btys
1786 bound_vars
= allBoundVariabless ctxt `unionVarSet`
1787 allBoundVariabless arg_tys
1789 ; return ((exp_tvs
, ctxt
, arg_tys
, ty
', field_lbls
, stricts
), bound_vars
)
1791 ; return (imp_tvs
++ exp_tvs
, ctxt
, stricts
, field_lbls
, arg_tys
, res_ty
, hs_details
)
1794 tcConIsInfixH98
:: Name
1795 -> HsConDetails
(LHsType GhcRn
) (Located
[LConDeclField GhcRn
])
1797 tcConIsInfixH98 _ details
1799 InfixCon
{} -> return True
1802 tcConIsInfixGADT
:: Name
1803 -> HsConDetails
(LHsType GhcRn
) (Located
[LConDeclField GhcRn
])
1805 tcConIsInfixGADT con details
1807 InfixCon
{} -> return True
1808 RecCon
{} -> return False
1809 PrefixCon arg_tys
-- See Note [Infix GADT constructors]
1810 | isSymOcc
(getOccName con
)
1811 , [_ty1
,_ty2
] <- arg_tys
1812 -> do { fix_env
<- getFixityEnv
1813 ; return (con `elemNameEnv` fix_env
) }
1814 |
otherwise -> return False
1816 tcConArgs
:: HsConDeclDetails GhcRn
1817 -> TcM
[(TcType
, HsSrcBang
)]
1818 tcConArgs
(PrefixCon btys
)
1819 = mapM tcConArg btys
1820 tcConArgs
(InfixCon bty1 bty2
)
1821 = do { bty1
' <- tcConArg bty1
1822 ; bty2
' <- tcConArg bty2
1823 ; return [bty1
', bty2
'] }
1824 tcConArgs
(RecCon fields
)
1825 = mapM tcConArg btys
1827 -- We need a one-to-one mapping from field_names to btys
1828 combined
= map (\(L _ f
) -> (cd_fld_names f
,cd_fld_type f
)) (unLoc fields
)
1829 explode
(ns
,ty
) = zip ns
(repeat ty
)
1830 exploded
= concatMap explode combined
1831 (_
,btys
) = unzip exploded
1834 tcConArg
:: LHsType GhcRn
-> TcM
(TcType
, HsSrcBang
)
1836 = do { traceTc
"tcConArg 1" (ppr bty
)
1837 ; arg_ty
<- tcHsOpenType
(getBangType bty
)
1838 -- Newtypes can't have unboxed types, but we check
1839 -- that in checkValidDataCon; this tcConArg stuff
1840 -- doesn't happen for GADT-style declarations
1841 ; traceTc
"tcConArg 2" (ppr bty
)
1842 ; return (arg_ty
, getBangStrictness bty
) }
1845 Note [Wrong visibility for GADTs]
1846 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1847 GADT tyvars shouldn't all be specified, but it's hard to do much better, as
1848 described in #11721, which is duplicated here for convenience:
1853 MkX :: b -> Proxy a -> X a
1855 According to the rules around specified vs. generalized variables around
1856 TypeApplications, the type of MkX should be
1858 MkX :: forall {k} (b :: *) (a :: k). b -> Proxy a -> X a
1860 A few things to note:
1862 * The k isn't available for TypeApplications (that's why it's in braces),
1863 because it is not user-written.
1865 * The b is quantified before the a, because b comes before a in the
1866 user-written type signature for MkX.
1868 Both of these bullets are currently violated. GHCi reports MkX's type as
1870 MkX :: forall k (a :: k) b. b -> Proxy a -> X a
1872 It turns out that this is hard to fix. The problem is that GHC expects data
1873 constructors to have their universal variables followed by their existential
1874 variables, always. And yet that's violated in the desired type for MkX.
1875 Furthermore, given the way that GHC deals with GADT return types ("rejigging",
1876 in technical parlance), it's inconvenient to get the specified/generalized
1877 distinction correct.
1879 Given time constraints, I'm afraid fixing this all won't make it for 8.0.
1881 Happily, there is are easy-to-articulate rules governing GHC's current (wrong)
1882 behavior. In a GADT-syntax data constructor:
1884 * All kind and type variables are considered specified and available for
1885 visible type application.
1887 * Universal variables always come first, in precisely the order they appear
1888 in the tycon. Note that universals that are constrained by a GADT return
1889 type are missing from the datacon.
1891 * Existential variables come next. Their order is determined by a
1892 user-written forall; or, if there is none, by taking the left-to-right
1893 order in the datacon's type and doing a stable topological sort. (This
1894 stable topological sort step is the same as for other user-written type
1897 Note [Infix GADT constructors]
1898 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1899 We do not currently have syntax to declare an infix constructor in GADT syntax,
1900 but it makes a (small) difference to the Show instance. So as a slightly
1901 ad-hoc solution, we regard a GADT data constructor as infix if
1902 a) it is an operator symbol
1903 b) it has two arguments
1904 c) there is a fixity declaration for it
1908 (:--:) :: t1 -> t2 -> T Int
1911 Note [Checking GADT return types]
1912 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1913 There is a delicacy around checking the return types of a datacon. The
1914 central problem is dealing with a declaration like
1919 Note that the return type of MkT is totally bogus. When creating the T
1920 tycon, we also need to create the MkT datacon, which must have a "rejigged"
1921 return type. That is, the MkT datacon's type must be transformed to have
1922 a uniform return type with explicit coercions for GADT-like type parameters.
1923 This rejigging is what rejigConRes does. The problem is, though, that checking
1924 that the return type is appropriate is much easier when done over *Type*,
1925 not *HsType*, and doing a call to tcMatchTy will loop because T isn't fully
1928 So, we want to make rejigConRes lazy and then check the validity of
1929 the return type in checkValidDataCon. To do this we /always/ return a
1930 4-tuple from rejigConRes (so that we can compute the return type from it, which
1931 checkValidDataCon needs), but the first three fields may be bogus if
1932 the return type isn't valid (the last equation for rejigConRes).
1934 This is better than an earlier solution which reduced the number of
1935 errors reported in one pass. See Trac #7175, and #10836.
1939 -- data instance T (b,c) where
1940 -- TI :: forall e. e -> T (e,e)
1942 -- The representation tycon looks like this:
1943 -- data :R7T b c where
1944 -- TI :: forall b1 c1. (b1 ~ c1) => b1 -> :R7T b1 c1
1945 -- In this case orig_res_ty = T (e,e)
1947 rejigConRes
:: [TyConBinder
] -> Type
-- Template for result type; e.g.
1948 -- data instance T [a] b c = ...
1949 -- gives template ([a,b,c], T [a] b c)
1950 -- Type must be of kind *!
1951 -> [TyVar
] -- where MkT :: forall x y z. ...
1952 -> Type
-- res_ty type must be of kind *
1953 -> ([TyVar
], -- Universal
1954 [TyVar
], -- Existential (distinct OccNames from univs)
1955 [EqSpec
], -- Equality predicates
1956 TCvSubst
) -- Substitution to apply to argument types
1957 -- We don't check that the TyCon given in the ResTy is
1958 -- the same as the parent tycon, because checkValidDataCon will do it
1960 rejigConRes tmpl_bndrs res_tmpl dc_tvs res_ty
1961 -- E.g. data T [a] b c where
1962 -- MkT :: forall x y z. T [(x,y)] z z
1963 -- The {a,b,c} are the tmpl_tvs, and the {x,y,z} are the dc_tvs
1964 -- (NB: unlike the H98 case, the dc_tvs are not all existential)
1966 -- Univ tyvars Eq-spec
1970 -- Existentials are the leftover type vars: [x,y]
1971 -- So we return ([a,b,z], [x,y], [a~(x,y),b~z], <arg-subst>)
1972 | Just subst
<- ASSERT
( isLiftedTypeKind
(typeKind res_ty
) )
1973 ASSERT
( isLiftedTypeKind
(typeKind res_tmpl
) )
1974 tcMatchTy res_tmpl res_ty
1975 = let (univ_tvs
, raw_eqs
, kind_subst
) = mkGADTVars tmpl_tvs dc_tvs subst
1976 raw_ex_tvs
= dc_tvs `minusList` univ_tvs
1977 (arg_subst
, substed_ex_tvs
)
1978 = mapAccumL substTyVarBndr kind_subst raw_ex_tvs
1980 substed_eqs
= map (substEqSpec arg_subst
) raw_eqs
1982 (univ_tvs
, substed_ex_tvs
, substed_eqs
, arg_subst
)
1985 -- If the return type of the data constructor doesn't match the parent
1986 -- type constructor, or the arity is wrong, the tcMatchTy will fail
1987 -- e.g data T a b where
1988 -- T1 :: Maybe a -- Wrong tycon
1989 -- T2 :: T [a] -- Wrong arity
1990 -- We are detect that later, in checkValidDataCon, but meanwhile
1991 -- we must do *something*, not just crash. So we do something simple
1992 -- albeit bogus, relying on checkValidDataCon to check the
1993 -- bad-result-type error before seeing that the other fields look odd
1994 -- See Note [Checking GADT return types]
1995 = (tmpl_tvs
, dc_tvs `minusList` tmpl_tvs
, [], emptyTCvSubst
)
1997 tmpl_tvs
= binderVars tmpl_bndrs
1999 {- Note [mkGADTVars]
2000 ~~~~~~~~~~~~~~~~~~~~
2003 data T (k1 :: *) (k2 :: *) (a :: k2) (b :: k2) where
2004 MkT :: forall (x1 : *) (y :: x1) (z :: *).
2005 T x1 * (Proxy (y :: x1), z) z
2007 We need the rejigged type to be
2009 MkT :: forall (x1 :: *) (k2 :: *) (a :: k2) (b :: k2).
2010 forall (y :: x1) (z :: *).
2011 (k2 ~ *, a ~ (Proxy x1 y, z), b ~ z)
2014 You might naively expect that z should become a universal tyvar,
2015 not an existential. (After all, x1 becomes a universal tyvar.)
2016 But z has kind * while b has kind k2, so the return type
2018 is ill-kinded. Another way to say it is this: the universal
2019 tyvars must have exactly the same kinds as the tyConTyVars.
2021 So we need an existential tyvar and a heterogeneous equality
2022 constraint. (The b ~ z is a bit redundant with the k2 ~ * that
2023 comes before in that b ~ z implies k2 ~ *. I'm sure we could do
2024 some analysis that could eliminate k2 ~ *. But we don't do this
2027 The data con signature has already been fully kind-checked.
2030 T x1 * (Proxy (y :: x1), z) z
2032 qtkvs = [x1 :: *, y :: x1, z :: *]
2033 res_tmpl = T x1 * (Proxy x1 y, z) z
2035 We start off by matching (T k1 k2 a b) with (T x1 * (Proxy x1 y, z) z). We
2036 know this match will succeed because of the validity check (actually done
2037 later, but laziness saves us -- see Note [Checking GADT return types]).
2040 subst := { k1 |-> x1, k2 |-> *, a |-> (Proxy x1 y, z), b |-> z }
2042 Now, we need to figure out what the GADT equalities should be. In this case,
2043 we *don't* want (k1 ~ x1) to be a GADT equality: it should just be a
2044 renaming. The others should be GADT equalities. We also need to make
2045 sure that the universally-quantified variables of the datacon match up
2046 with the tyvars of the tycon, as required for Core context well-formedness.
2047 (This last bit is why we have to rejig at all!)
2049 `choose` walks down the tycon tyvars, figuring out what to do with each one.
2050 It carries two substitutions:
2051 - t_sub's domain is *template* or *tycon* tyvars, mapping them to variables
2052 mentioned in the datacon signature.
2053 - r_sub's domain is *result* tyvars, names written by the programmer in
2054 the datacon signature. The final rejigged type will use these names, but
2055 the subst is still needed because sometimes the printed name of these variables
2056 is different. (See choose_tv_name, below.)
2058 Before explaining the details of `choose`, let's just look at its operation
2061 choose [] [] {} {} [k1, k2, a, b]
2062 --> -- first branch of `case` statement
2069 --> -- second branch of `case` statement
2071 univs: [k2 :: *, x1 :: *]
2073 t_sub: {k1 |-> x1, k2 |-> k2}
2076 --> -- second branch of `case` statement
2078 univs: [a :: k2, k2 :: *, x1 :: *]
2079 eq_spec: [ a ~ (Proxy x1 y, z)
2081 t_sub: {k1 |-> x1, k2 |-> k2, a |-> a}
2084 --> -- second branch of `case` statement
2086 univs: [b :: k2, a :: k2, k2 :: *, x1 :: *]
2088 , a ~ (Proxy x1 y, z)
2090 t_sub: {k1 |-> x1, k2 |-> k2, a |-> a, b |-> z}
2093 --> -- end of recursion
2094 ( [x1 :: *, k2 :: *, a :: k2, b :: k2]
2095 , [k2 ~ *, a ~ (Proxy x1 y, z), b ~ z]
2098 `choose` looks up each tycon tyvar in the matching (it *must* be matched!).
2100 * If it finds a bare result tyvar (the first branch of the `case`
2101 statement), it checks to make sure that the result tyvar isn't yet
2102 in the list of univ_tvs. If it is in that list, then we have a
2103 repeated variable in the return type, and we in fact need a GADT
2106 * It then checks to make sure that the kind of the result tyvar
2107 matches the kind of the template tyvar. This check is what forces
2108 `z` to be existential, as it should be, explained above.
2110 * Assuming no repeated variables or kind-changing, we wish to use the
2111 variable name given in the datacon signature (that is, `x1` not
2112 `k1`), not the tycon signature (which may have been made up by
2113 GHC). So, we add a mapping from the tycon tyvar to the result tyvar
2116 * If we discover that a mapping in `subst` gives us a non-tyvar (the
2117 second branch of the `case` statement), then we have a GADT equality
2118 to create. We create a fresh equality, but we don't extend any
2119 substitutions. The template variable substitution is meant for use
2120 in universal tyvar kinds, and these shouldn't be affected by any
2123 This whole algorithm is quite delicate, indeed. I (Richard E.) see two ways
2126 1) The first branch of the `case` statement is really an optimization, used
2127 in order to get fewer GADT equalities. It might be possible to make a GADT
2128 equality for *every* univ. tyvar, even if the equality is trivial, and then
2129 either deal with the bigger type or somehow reduce it later.
2131 2) This algorithm strives to use the names for type variables as specified
2132 by the user in the datacon signature. If we always used the tycon tyvar
2133 names, for example, this would be simplified. This change would almost
2134 certainly degrade error messages a bit, though.
2137 -- ^ From information about a source datacon definition, extract out
2138 -- what the universal variables and the GADT equalities should be.
2139 -- See Note [mkGADTVars].
2140 mkGADTVars
:: [TyVar
] -- ^ The tycon vars
2141 -> [TyVar
] -- ^ The datacon vars
2142 -> TCvSubst
-- ^ The matching between the template result type
2143 -- and the actual result type
2146 , TCvSubst
) -- ^ The univ. variables, the GADT equalities,
2147 -- and a subst to apply to the GADT equalities
2148 -- and existentials.
2149 mkGADTVars tmpl_tvs dc_tvs subst
2150 = choose
[] [] empty_subst empty_subst tmpl_tvs
2152 in_scope
= mkInScopeSet
(mkVarSet tmpl_tvs `unionVarSet` mkVarSet dc_tvs
)
2153 `unionInScope` getTCvInScope subst
2154 empty_subst
= mkEmptyTCvSubst in_scope
2156 choose
:: [TyVar
] -- accumulator of univ tvs, reversed
2157 -> [EqSpec
] -- accumulator of GADT equalities, reversed
2158 -> TCvSubst
-- template substitution
2159 -> TCvSubst
-- res. substitution
2160 -> [TyVar
] -- template tvs (the univ tvs passed in)
2161 -> ( [TyVar
] -- the univ_tvs
2162 , [EqSpec
] -- GADT equalities
2163 , TCvSubst
) -- a substitution to fix kinds in ex_tvs
2165 choose univs eqs _t_sub r_sub
[]
2166 = (reverse univs
, reverse eqs
, r_sub
)
2167 choose univs eqs t_sub r_sub
(t_tv
:t_tvs
)
2168 | Just r_ty
<- lookupTyVar subst t_tv
2169 = case getTyVar_maybe r_ty
of
2171 |
not (r_tv `
elem` univs
)
2172 , tyVarKind r_tv `eqType`
(substTy t_sub
(tyVarKind t_tv
))
2173 -> -- simple, well-kinded variable substitution.
2174 choose
(r_tv
:univs
) eqs
2175 (extendTvSubst t_sub t_tv r_ty
')
2176 (extendTvSubst r_sub r_tv r_ty
')
2179 r_tv1
= setTyVarName r_tv
(choose_tv_name r_tv t_tv
)
2180 r_ty
' = mkTyVarTy r_tv1
2182 -- Not a simple substitution: make an equality predicate
2183 _
-> choose
(t_tv
':univs
) (mkEqSpec t_tv
' r_ty
: eqs
)
2184 (extendTvSubst t_sub t_tv
(mkTyVarTy t_tv
'))
2185 -- We've updated the kind of t_tv,
2186 -- so add it to t_sub (Trac #14162)
2189 t_tv
' = updateTyVarKind
(substTy t_sub
) t_tv
2192 = pprPanic
"mkGADTVars" (ppr tmpl_tvs
$$ ppr subst
)
2194 -- choose an appropriate name for a univ tyvar.
2195 -- This *must* preserve the Unique of the result tv, so that we
2196 -- can detect repeated variables. It prefers user-specified names
2197 -- over system names. A result variable with a system name can
2198 -- happen with GHC-generated implicit kind variables.
2199 choose_tv_name
:: TyVar
-> TyVar
-> Name
2200 choose_tv_name r_tv t_tv
2201 | isSystemName r_tv_name
2202 = setNameUnique t_tv_name
(getUnique r_tv_name
)
2208 r_tv_name
= getName r_tv
2209 t_tv_name
= getName t_tv
2212 Note [Substitution in template variables kinds]
2213 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2215 data G (a :: Maybe k) where
2218 With explicit kind variables
2220 data G k (a :: Maybe k) where
2221 MkG :: G k1 (Nothing k1)
2223 Note how k1 is distinct from k. So, when we match the template
2224 `G k a` against `G k1 (Nothing k1)`, we get a subst
2225 [ k |-> k1, a |-> Nothing k1 ]. Even though this subst has two
2226 mappings, we surely don't want to add (k, k1) to the list of
2227 GADT equalities -- that would be overly complex and would create
2228 more untouchable variables than we need. So, when figuring out
2229 which tyvars are GADT-like and which aren't (the fundamental
2230 job of `choose`), we want to treat `k` as *not* GADT-like.
2231 Instead, we wish to substitute in `a`'s kind, to get (a :: Maybe k1)
2232 instead of (a :: Maybe k). This is the reason for dealing
2233 with a substitution in here.
2235 However, we do not *always* want to substitute. Consider
2237 data H (a :: k) where
2240 With explicit kind variables:
2242 data H k (a :: k) where
2245 Here, we have a kind-indexed GADT. The subst in question is
2246 [ k |-> *, a |-> Int ]. Now, we *don't* want to substitute in `a`'s
2247 kind, because that would give a constructor with the type
2249 MkH :: forall (k :: *) (a :: *). (k ~ *) -> (a ~ Int) -> H k a
2251 The problem here is that a's kind is wrong -- it needs to be k, not *!
2252 So, if the matching for a variable is anything but another bare variable,
2253 we drop the mapping from the substitution before proceeding. This
2254 was not an issue before kind-indexed GADTs because this case could
2257 ************************************************************************
2261 ************************************************************************
2263 Validity checking is done once the mutually-recursive knot has been
2264 tied, so we can look at things freely.
2267 checkValidTyCl
:: TyCon
-> TcM TyCon
2269 = setSrcSpan
(getSrcSpan tc
) $
2271 recoverM recovery_code
2272 (do { traceTc
"Starting validity for tycon" (ppr tc
)
2273 ; checkValidTyCon tc
2274 ; traceTc
"Done validity for tycon" (ppr tc
)
2277 recovery_code
-- See Note [Recover from validity error]
2278 = do { traceTc
"Aborted validity for tycon" (ppr tc
)
2280 fake_tc | isFamilyTyCon tc || isTypeSynonymTyCon tc
2281 = makeRecoveryTyCon tc
2285 {- Note [Recover from validity error]
2286 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2287 We recover from a validity error in a type or class, which allows us
2288 to report multiple validity errors. In the failure case we return a
2289 TyCon of the right kind, but with no interesting behaviour
2290 (makeRecoveryTyCon). Why? Suppose we have
2292 where Fun is a type family of arity 1. The RHS is invalid, but we
2293 want to go on checking validity of subsequent type declarations.
2294 So we replace T with an abstract TyCon which will do no harm.
2295 See indexed-types/should_fail/BadSock and Trac #10896
2297 Painfully, though, we *don't* want to do this for classes.
2299 class (?x::Int) => C a where ...
2301 The class is invalid because of the superclass constraint. But
2302 we still want it to look like a /class/, else the instance bleats
2303 that the instance is mal-formed because it hasn't got a class in
2307 -------------------------
2308 -- For data types declared with record syntax, we require
2309 -- that each constructor that has a field 'f'
2310 -- (a) has the same result type
2311 -- (b) has the same type for 'f'
2312 -- module alpha conversion of the quantified type variables
2313 -- of the constructor.
2315 -- Note that we allow existentials to match because the
2316 -- fields can never meet. E.g
2318 -- T1 { f1 :: b, f2 :: a, f3 ::Int } :: T
2319 -- T2 { f1 :: c, f2 :: c, f3 ::Int } :: T
2320 -- Here we do not complain about f1,f2 because they are existential
2322 checkValidTyCon
:: TyCon
-> TcM
()
2324 | isPrimTyCon tc
-- Happens when Haddock'ing GHC.Prim
2328 = do { traceTc
"checkValidTyCon" (ppr tc
$$ ppr
(tyConClass_maybe tc
))
2329 ; checkValidTyConTyVars tc
2330 ; if | Just cl
<- tyConClass_maybe tc
2331 -> checkValidClass cl
2333 | Just syn_rhs
<- synTyConRhs_maybe tc
2334 -> do { checkValidType syn_ctxt syn_rhs
2335 ; checkTySynRhs syn_ctxt syn_rhs
}
2337 | Just fam_flav
<- famTyConFlav_maybe tc
2339 { ClosedSynFamilyTyCon
(Just ax
)
2340 -> tcAddClosedTypeFamilyDeclCtxt tc
$
2341 checkValidCoAxiom ax
2342 ; ClosedSynFamilyTyCon Nothing
-> return ()
2343 ; AbstractClosedSynFamilyTyCon
->
2344 do { hsBoot
<- tcIsHsBootOrSig
2346 text
"You may define an abstract closed type family" $$
2347 text
"only in a .hs-boot file" }
2348 ; DataFamilyTyCon
{} -> return ()
2349 ; OpenSynFamilyTyCon
-> return ()
2350 ; BuiltInSynFamTyCon _
-> return () }
2353 { -- Check the context on the data decl
2354 traceTc
"cvtc1" (ppr tc
)
2355 ; checkValidTheta
(DataTyCtxt name
) (tyConStupidTheta tc
)
2357 ; traceTc
"cvtc2" (ppr tc
)
2359 ; dflags
<- getDynFlags
2360 ; existential_ok
<- xoptM LangExt
.ExistentialQuantification
2361 ; gadt_ok
<- xoptM LangExt
.GADTs
2362 ; let ex_ok
= existential_ok || gadt_ok
2363 -- Data cons can have existential context
2364 ; mapM_ (checkValidDataCon dflags ex_ok tc
) data_cons
2366 -- Check that fields with the same name share a type
2367 ; mapM_ check_fields groups
}}
2369 syn_ctxt
= TySynCtxt name
2371 data_cons
= tyConDataCons tc
2373 groups
= equivClasses cmp_fld
(concatMap get_fields data_cons
)
2374 cmp_fld
(f1
,_
) (f2
,_
) = flLabel f1 `
compare` flLabel f2
2375 get_fields con
= dataConFieldLabels con `
zip`
repeat con
2376 -- dataConFieldLabels may return the empty list, which is fine
2378 -- See Note [GADT record selectors] in TcTyDecls
2379 -- We must check (a) that the named field has the same
2380 -- type in each constructor
2381 -- (b) that those constructors have the same result type
2383 -- However, the constructors may have differently named type variable
2384 -- and (worse) we don't know how the correspond to each other. E.g.
2385 -- C1 :: forall a b. { f :: a, g :: b } -> T a b
2386 -- C2 :: forall d c. { f :: c, g :: c } -> T c d
2388 -- So what we do is to ust Unify.tcMatchTys to compare the first candidate's
2389 -- result type against other candidates' types BOTH WAYS ROUND.
2390 -- If they magically agrees, take the substitution and
2391 -- apply them to the latter ones, and see if they match perfectly.
2392 check_fields
((label
, con1
) :| other_fields
)
2393 -- These fields all have the same name, but are from
2394 -- different constructors in the data type
2395 = recoverM
(return ()) $ mapM_ checkOne other_fields
2396 -- Check that all the fields in the group have the same type
2397 -- NB: this check assumes that all the constructors of a given
2398 -- data type use the same type variables
2400 (_
, _
, _
, res1
) = dataConSig con1
2401 fty1
= dataConFieldType con1 lbl
2404 checkOne
(_
, con2
) -- Do it bothways to ensure they are structurally identical
2405 = do { checkFieldCompat lbl con1 con2 res1 res2 fty1 fty2
2406 ; checkFieldCompat lbl con2 con1 res2 res1 fty2 fty1
}
2408 (_
, _
, _
, res2
) = dataConSig con2
2409 fty2
= dataConFieldType con2 lbl
2411 checkFieldCompat
:: FieldLabelString
-> DataCon
-> DataCon
2412 -> Type
-> Type
-> Type
-> Type
-> TcM
()
2413 checkFieldCompat fld con1 con2 res1 res2 fty1 fty2
2414 = do { checkTc
(isJust mb_subst1
) (resultTypeMisMatch fld con1 con2
)
2415 ; checkTc
(isJust mb_subst2
) (fieldTypeMisMatch fld con1 con2
) }
2417 mb_subst1
= tcMatchTy res1 res2
2418 mb_subst2
= tcMatchTyX
(expectJust
"checkFieldCompat" mb_subst1
) fty1 fty2
2420 -------------------------------
2421 -- | Check for ill-scoped telescopes in a tycon.
2424 -- > data SameKind :: k -> k -> * -- this is OK
2425 -- > data Bad a (c :: Proxy b) (d :: Proxy a) (x :: SameKind b d)
2427 -- The problem is that @b@ should be bound (implicitly) at the beginning,
2428 -- but its kind mentions @a@, which is not yet in scope. Kind generalization
2429 -- makes a mess of this, and ends up including @a@ twice in the final
2430 -- tyvars. So this function checks for duplicates and, if there are any,
2431 -- produces the appropriate error message.
2432 checkValidTyConTyVars
:: TyCon
-> TcM
()
2433 checkValidTyConTyVars tc
2434 = do { -- strip off the duplicates and look for ill-scoped things
2435 -- but keep the *last* occurrence of each variable, as it's
2436 -- most likely the one the user wrote
2437 let stripped_tvs | duplicate_vars
2438 = reverse $ nub $ reverse tvs
2441 vis_tvs
= tyConVisibleTyVars tc
2442 extra |
not (vis_tvs `equalLength` stripped_tvs
)
2443 = text
"NB: Implicitly declared kind variables are put first."
2446 ; traceTc
"checkValidTyConTyVars" (ppr tc
<+> ppr tvs
)
2447 ; checkValidTelescope
(pprTyVars vis_tvs
) stripped_tvs extra
2448 `and_if_that_doesn
't_error`
2449 -- This triggers on test case dependent/should_fail/InferDependency
2450 -- It reports errors around Note [Dependent LHsQTyVars] in TcHsType
2451 when duplicate_vars
(
2452 addErr
(vcat
[ text
"Invalid declaration for" <+>
2453 quotes
(ppr tc
) <> semi
<+> text
"you must explicitly"
2454 , text
"declare which variables are dependent on which others."
2455 , hang
(text
"Inferred variable kinds:")
2456 2 (vcat
(map pp_tv stripped_tvs
)) ])) }
2458 tvs
= tyConTyVars tc
2459 duplicate_vars
= tvs `lengthExceeds` sizeVarSet
(mkVarSet tvs
)
2461 pp_tv tv
= ppr tv
<+> dcolon
<+> ppr
(tyVarKind tv
)
2463 -- only run try_second if the first reports no errors
2464 and_if_that_doesn
't_error
:: TcM
() -> TcM
() -> TcM
()
2465 try_first `and_if_that_doesn
't_error` try_second
2466 = recoverM
(return ()) $
2467 do { checkNoErrs try_first
2470 -------------------------------
2471 checkValidDataCon
:: DynFlags
-> Bool -> TyCon
-> DataCon
-> TcM
()
2472 checkValidDataCon dflags existential_ok tc con
2473 = setSrcSpan
(srcLocSpan
(getSrcLoc con
)) $
2474 addErrCtxt
(dataConCtxt con
) $
2475 do { -- Check that the return type of the data constructor
2476 -- matches the type constructor; eg reject this:
2477 -- data T a where { MkT :: Bogus a }
2478 -- It's important to do this first:
2479 -- see Note [Checking GADT return types]
2480 -- and c.f. Note [Check role annotations in a second pass]
2481 let tc_tvs
= tyConTyVars tc
2482 res_ty_tmpl
= mkFamilyTyConApp tc
(mkTyVarTys tc_tvs
)
2483 orig_res_ty
= dataConOrigResTy con
2484 ; traceTc
"checkValidDataCon" (vcat
2485 [ ppr con
, ppr tc
, ppr tc_tvs
2486 , ppr res_ty_tmpl
<+> dcolon
<+> ppr
(typeKind res_ty_tmpl
)
2487 , ppr orig_res_ty
<+> dcolon
<+> ppr
(typeKind orig_res_ty
)])
2490 ; checkTc
(isJust (tcMatchTy res_ty_tmpl
2492 (badDataConTyCon con res_ty_tmpl orig_res_ty
)
2493 -- Note that checkTc aborts if it finds an error. This is
2494 -- critical to avoid panicking when we call dataConUserType
2495 -- on an un-rejiggable datacon!
2497 ; traceTc
"checkValidDataCon 2" (ppr
(dataConUserType con
))
2499 -- Check that the result type is a *monotype*
2500 -- e.g. reject this: MkT :: T (forall a. a->a)
2501 -- Reason: it's really the argument of an equality constraint
2502 ; checkValidMonoType orig_res_ty
2504 -- Check all argument types for validity
2505 ; checkValidType ctxt
(dataConUserType con
)
2506 ; mapM_ (checkForLevPoly
empty)
2507 (dataConOrigArgTys con
)
2509 -- Extra checks for newtype data constructors
2510 ; when (isNewTyCon tc
) (checkNewDataCon con
)
2512 -- Check that existentials are allowed if they are used
2513 ; checkTc
(existential_ok || isVanillaDataCon con
)
2514 (badExistential con
)
2516 -- Check that UNPACK pragmas and bangs work out
2517 -- E.g. reject data T = MkT {-# UNPACK #-} Int -- No "!"
2518 -- data T = MkT {-# UNPACK #-} !a -- Can't unpack
2519 ; zipWith3M_ check_bang
(dataConSrcBangs con
) (dataConImplBangs con
) [1..]
2521 ; traceTc
"Done validity of data con" $
2523 , text
"Datacon user type:" <+> ppr
(dataConUserType con
)
2524 , text
"Datacon rep type:" <+> ppr
(dataConRepType con
)
2525 , text
"Rep typcon binders:" <+> ppr
(tyConBinders
(dataConTyCon con
))
2526 , case tyConFamInst_maybe
(dataConTyCon con
) of
2527 Nothing
-> text
"not family"
2528 Just
(f
, _
) -> ppr
(tyConBinders f
) ]
2531 ctxt
= ConArgCtxt
(dataConName con
)
2533 check_bang
:: HsSrcBang
-> HsImplBang
-> Int -> TcM
()
2534 check_bang
(HsSrcBang _ _ SrcLazy
) _ n
2535 |
not (xopt LangExt
.StrictData dflags
)
2537 (bad_bang n
(text
"Lazy annotation (~) without StrictData"))
2538 check_bang
(HsSrcBang _ want_unpack strict_mark
) rep_bang n
2539 | isSrcUnpacked want_unpack
, not is_strict
2540 = addWarnTc NoReason
(bad_bang n
(text
"UNPACK pragma lacks '!'"))
2541 | isSrcUnpacked want_unpack
2542 , case rep_bang
of { HsUnpack
{} -> False; _
-> True }
2543 , not (gopt Opt_OmitInterfacePragmas dflags
)
2544 -- If not optimising, se don't unpack, so don't complain!
2545 -- See MkId.dataConArgRep, the (HsBang True) case
2546 = addWarnTc NoReason
(bad_bang n
(text
"Ignoring unusable UNPACK pragma"))
2548 is_strict
= case strict_mark
of
2549 NoSrcStrict
-> xopt LangExt
.StrictData dflags
2550 bang
-> isSrcStrict bang
2556 = hang herald
2 (text
"on the" <+> speakNth n
2557 <+> text
"argument of" <+> quotes
(ppr con
))
2558 -------------------------------
2559 checkNewDataCon
:: DataCon
-> TcM
()
2560 -- Further checks for the data constructor of a newtype
2562 = do { checkTc
(isSingleton arg_tys
) (newtypeFieldErr con
(length arg_tys
))
2565 ; checkTc
(not (isUnliftedType arg_ty1
)) $
2566 text
"A newtype cannot have an unlifted argument type"
2568 ; check_con
(null eq_spec
) $
2569 text
"A newtype constructor must have a return type of form T a1 ... an"
2570 -- Return type is (T a b c)
2572 ; check_con
(null theta
) $
2573 text
"A newtype constructor cannot have a context in its type"
2575 ; check_con
(null ex_tvs
) $
2576 text
"A newtype constructor cannot have existential type variables"
2579 ; checkTc
(all ok_bang
(dataConSrcBangs con
))
2580 (newtypeStrictError con
)
2581 -- No strictness annotations
2584 (_univ_tvs
, ex_tvs
, eq_spec
, theta
, arg_tys
, _res_ty
)
2585 = dataConFullSig con
2587 = checkTc what
(msg
$$ ppr con
<+> dcolon
<+> ppr
(dataConUserType con
))
2589 (arg_ty1
: _
) = arg_tys
2591 ok_bang
(HsSrcBang _ _ SrcStrict
) = False
2592 ok_bang
(HsSrcBang _ _ SrcLazy
) = False
2595 -------------------------------
2596 checkValidClass
:: Class
-> TcM
()
2598 = do { constrained_class_methods
<- xoptM LangExt
.ConstrainedClassMethods
2599 ; multi_param_type_classes
<- xoptM LangExt
.MultiParamTypeClasses
2600 ; nullary_type_classes
<- xoptM LangExt
.NullaryTypeClasses
2601 ; fundep_classes
<- xoptM LangExt
.FunctionalDependencies
2602 ; undecidable_super_classes
<- xoptM LangExt
.UndecidableSuperClasses
2604 -- Check that the class is unary, unless multiparameter type classes
2605 -- are enabled; also recognize deprecated nullary type classes
2606 -- extension (subsumed by multiparameter type classes, Trac #8993)
2607 ; checkTc
(multi_param_type_classes || cls_arity
== 1 ||
2608 (nullary_type_classes
&& cls_arity
== 0))
2609 (classArityErr cls_arity cls
)
2610 ; checkTc
(fundep_classes ||
null fundeps
) (classFunDepsErr cls
)
2612 -- Check the super-classes
2613 ; checkValidTheta
(ClassSCCtxt
(className cls
)) theta
2615 -- Now check for cyclic superclasses
2616 -- If there are superclass cycles, checkClassCycleErrs bails.
2617 ; unless undecidable_super_classes
$
2618 case checkClassCycles cls
of
2619 Just err
-> setSrcSpan
(getSrcSpan cls
) $
2621 Nothing
-> return ()
2623 -- Check the class operations.
2624 -- But only if there have been no earlier errors
2625 -- See Note [Abort when superclass cycle is detected]
2627 mapM_ (check_op constrained_class_methods
) op_stuff
2629 -- Check the associated type defaults are well-formed and instantiated
2630 ; mapM_ check_at at_stuff
}
2632 (tyvars
, fundeps
, theta
, _
, at_stuff
, op_stuff
) = classExtraBigSig cls
2633 cls_arity
= length (tyConVisibleTyVars
(classTyCon cls
))
2634 -- Ignore invisible variables
2635 cls_tv_set
= mkVarSet tyvars
2636 mini_env
= zipVarEnv tyvars
(mkTyVarTys tyvars
)
2637 mb_cls
= Just
(cls
, tyvars
, mini_env
)
2639 check_op constrained_class_methods
(sel_id
, dm
)
2640 = setSrcSpan
(getSrcSpan sel_id
) $
2641 addErrCtxt
(classOpCtxt sel_id op_ty
) $ do
2642 { traceTc
"class op type" (ppr op_ty
)
2643 ; checkValidType ctxt op_ty
2644 -- This implements the ambiguity check, among other things
2646 -- class Error e => Game b mv e | b -> mv e where
2647 -- newBoard :: MonadState b m => m ()
2648 -- Here, MonadState has a fundep m->b, so newBoard is fine
2650 -- a method cannot be levity polymorphic, as we have to store the
2651 -- method in a dictionary
2652 -- example of what this prevents:
2653 -- class BoundedX (a :: TYPE r) where minBound :: a
2654 -- See Note [Levity polymorphism checking] in DsMonad
2655 ; checkForLevPoly
empty tau1
2657 ; unless constrained_class_methods
$
2658 mapM_ check_constraint
(tail (cls_pred
:op_theta
))
2660 ; check_dm ctxt sel_id cls_pred tau2 dm
2663 ctxt
= FunSigCtxt op_name
True -- Report redundant class constraints
2664 op_name
= idName sel_id
2665 op_ty
= idType sel_id
2666 (_
,cls_pred
,tau1
) = tcSplitMethodTy op_ty
2667 -- See Note [Splitting nested sigma types in class type signatures]
2668 (_
,op_theta
,tau2
) = tcSplitNestedSigmaTys tau1
2670 check_constraint
:: TcPredType
-> TcM
()
2671 check_constraint
pred -- See Note [Class method constraints]
2672 = when (not (isEmptyVarSet pred_tvs
) &&
2673 pred_tvs `subVarSet` cls_tv_set
)
2674 (addErrTc
(badMethPred sel_id
pred))
2676 pred_tvs
= tyCoVarsOfType
pred
2678 check_at
(ATI fam_tc m_dflt_rhs
)
2679 = do { checkTc
(cls_arity
== 0 ||
any (`elemVarSet` cls_tv_set
) fam_tvs
)
2680 (noClassTyVarErr cls fam_tc
)
2681 -- Check that the associated type mentions at least
2682 -- one of the class type variables
2683 -- The check is disabled for nullary type classes,
2684 -- since there is no possible ambiguity (Trac #10020)
2686 -- Check that any default declarations for associated types are valid
2687 ; whenIsJust m_dflt_rhs
$ \ (rhs
, loc
) ->
2688 checkValidTyFamEqn mb_cls fam_tc
2689 fam_tvs
[] (mkTyVarTys fam_tvs
) rhs pp_lhs loc
}
2691 fam_tvs
= tyConTyVars fam_tc
2692 pp_lhs
= ppr
(mkTyConApp fam_tc
(mkTyVarTys fam_tvs
))
2694 check_dm
:: UserTypeCtxt
-> Id
-> PredType
-> Type
-> DefMethInfo
-> TcM
()
2695 -- Check validity of the /top-level/ generic-default type
2696 -- E.g for class C a where
2697 -- default op :: forall b. (a~b) => blah
2698 -- we do not want to do an ambiguity check on a type with
2699 -- a free TyVar 'a' (Trac #11608). See TcType
2700 -- Note [TyVars and TcTyVars during type checking] in TcType
2701 -- Hence the mkDefaultMethodType to close the type.
2702 check_dm ctxt sel_id vanilla_cls_pred vanilla_tau
2703 (Just
(dm_name
, dm_spec
@(GenericDM dm_ty
)))
2704 = setSrcSpan
(getSrcSpan dm_name
) $ do
2705 -- We have carefully set the SrcSpan on the generic
2706 -- default-method Name to be that of the generic
2707 -- default type signature
2709 -- First, we check that that the method's default type signature
2710 -- aligns with the non-default type signature.
2711 -- See Note [Default method type signatures must align]
2712 let cls_pred
= mkClassPred cls
$ mkTyVarTys
$ classTyVars cls
2713 -- Note that the second field of this tuple contains the context
2714 -- of the default type signature, making it apparent that we
2715 -- ignore method contexts completely when validity-checking
2716 -- default type signatures. See the end of
2717 -- Note [Default method type signatures must align]
2718 -- to learn why this is OK.
2721 -- Note [Splitting nested sigma types in class type signatures]
2722 -- for an explanation of why we don't use tcSplitSigmaTy here.
2723 (_
, _
, dm_tau
) = tcSplitNestedSigmaTys dm_ty
2725 -- Given this class definition:
2727 -- class C a b where
2728 -- op :: forall p q. (Ord a, D p q)
2729 -- => a -> b -> p -> (a, b)
2730 -- default op :: forall r s. E r
2731 -- => a -> b -> s -> (a, b)
2733 -- We want to match up two types of the form:
2735 -- Vanilla type sig: C aa bb => aa -> bb -> p -> (aa, bb)
2736 -- Default type sig: C a b => a -> b -> s -> (a, b)
2738 -- Notice that the two type signatures can be quantified over
2739 -- different class type variables! Therefore, it's important that
2740 -- we include the class predicate parts to match up a with aa and
2742 vanilla_phi_ty
= mkPhiTy
[vanilla_cls_pred
] vanilla_tau
2743 dm_phi_ty
= mkPhiTy
[cls_pred
] dm_tau
2745 traceTc
"check_dm" $ vcat
2746 [ text
"vanilla_phi_ty" <+> ppr vanilla_phi_ty
2747 , text
"dm_phi_ty" <+> ppr dm_phi_ty
]
2749 -- Actually checking that the types align is done with a call to
2750 -- tcMatchTys. We need to get a match in both directions to rule
2751 -- out degenerate cases like these:
2753 -- class Foo a where
2755 -- default foo1 :: a -> Int
2758 -- default foo2 :: a -> b
2759 unless (isJust $ tcMatchTys
[dm_phi_ty
, vanilla_phi_ty
]
2760 [vanilla_phi_ty
, dm_phi_ty
]) $ addErrTc
$
2761 hang
(text
"The default type signature for"
2762 <+> ppr sel_id
<> colon
)
2764 $$ (text
"does not match its corresponding"
2765 <+> text
"non-default type signature")
2767 -- Now do an ambiguity check on the default type signature.
2768 checkValidType ctxt
(mkDefaultMethodType cls sel_id dm_spec
)
2769 check_dm _ _ _ _ _
= return ()
2771 checkFamFlag
:: Name
-> TcM
()
2772 -- Check that we don't use families without -XTypeFamilies
2773 -- The parser won't even parse them, but I suppose a GHC API
2774 -- client might have a go!
2775 checkFamFlag tc_name
2776 = do { idx_tys
<- xoptM LangExt
.TypeFamilies
2777 ; checkTc idx_tys err_msg
}
2779 err_msg
= hang
(text
"Illegal family declaration for" <+> quotes
(ppr tc_name
))
2780 2 (text
"Use TypeFamilies to allow indexed type families")
2782 {- Note [Class method constraints]
2783 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2784 Haskell 2010 is supposed to reject
2786 op :: Eq a => a -> a
2787 where the method type costrains only the class variable(s). (The extension
2788 -XConstrainedClassMethods switches off this check.) But regardless
2789 we should not reject
2791 op :: (?x::Int) => a -> a
2792 as pointed out in Trac #11793. So the test here rejects the program if
2793 * -XConstrainedClassMethods is off
2794 * the tyvars of the constraint are non-empty
2795 * all the tyvars are class tyvars, none are locally quantified
2797 Note [Abort when superclass cycle is detected]
2798 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2799 We must avoid doing the ambiguity check for the methods (in
2800 checkValidClass.check_op) when there are already errors accumulated.
2801 This is because one of the errors may be a superclass cycle, and
2802 superclass cycles cause canonicalization to loop. Here is a
2803 representative example:
2805 class D a => C a where
2809 This fixes Trac #9415, #9739
2811 Note [Default method type signatures must align]
2812 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2813 GHC enforces the invariant that a class method's default type signature
2814 must "align" with that of the method's non-default type signature, as per
2815 GHC Trac #12918. For instance, if you have:
2818 bar :: forall b. Context => a -> b
2820 Then a default type signature for bar must be alpha equivalent to
2821 (forall b. a -> b). That is, the types must be the same modulo differences in
2822 contexts. So the following would be acceptable default type signatures:
2824 default bar :: forall b. Context1 => a -> b
2825 default bar :: forall x. Context2 => a -> x
2827 But the following are NOT acceptable default type signatures:
2829 default bar :: forall b. b -> a
2830 default bar :: forall x. x
2831 default bar :: a -> Int
2833 Note that a is bound by the class declaration for Foo itself, so it is
2834 not allowed to differ in the default type signature.
2836 The default type signature (default bar :: a -> Int) deserves special mention,
2837 since (a -> Int) is a straightforward instantiation of (forall b. a -> b). To
2838 write this, you need to declare the default type signature like so:
2840 default bar :: forall b. (b ~ Int). a -> b
2842 As noted in #12918, there are several reasons to do this:
2844 1. It would make no sense to have a type that was flat-out incompatible with
2845 the non-default type signature. For instance, if you had:
2849 default bar :: a -> Bool
2851 Then that would always fail in an instance declaration. So this check
2852 nips such cases in the bud before they have the chance to produce
2853 confusing error messages.
2855 2. Internally, GHC uses TypeApplications to instantiate the default method in
2856 an instance. See Note [Default methods in instances] in TcInstDcls.
2857 Thus, GHC needs to know exactly what the universally quantified type
2858 variables are, and when instantiated that way, the default method's type
2859 must match the expected type.
2861 3. Aesthetically, by only allowing the default type signature to differ in its
2862 context, we are making it more explicit the ways in which the default type
2863 signature is less polymorphic than the non-default type signature.
2865 You might be wondering: why are the contexts allowed to be different, but not
2866 the rest of the type signature? That's because default implementations often
2867 rely on assumptions that the more general, non-default type signatures do not.
2868 For instance, in the Enum class declaration:
2872 default enum :: (Generic a, GEnum (Rep a)) => [a]
2878 The default implementation for enum only works for types that are instances of
2879 Generic, and for which their generic Rep type is an instance of GEnum. But
2880 clearly enum doesn't _have_ to use this implementation, so naturally, the
2881 context for enum is allowed to be different to accomodate this. As a result,
2882 when we validity-check default type signatures, we ignore contexts completely.
2884 Note that when checking whether two type signatures match, we must take care to
2885 split as many foralls as it takes to retrieve the tau types we which to check.
2886 See Note [Splitting nested sigma types in class type signatures].
2888 Note [Splitting nested sigma types in class type signatures]
2889 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2890 Consider this type synonym and class definition:
2892 type Traversal s t a b = forall f. Applicative f => (a -> f b) -> s -> f t
2894 class Each s t a b where
2895 each :: Traversal s t a b
2896 default each :: (Traversable g, s ~ g a, t ~ g b) => Traversal s t a b
2898 It might seem obvious that the tau types in both type signatures for `each`
2899 are the same, but actually getting GHC to conclude this is surprisingly tricky.
2900 That is because in general, the form of a class method's non-default type
2903 forall a. C a => forall d. D d => E a b
2905 And the general form of a default type signature is:
2907 forall f. F f => E a f -- The variable `a` comes from the class
2909 So it you want to get the tau types in each type signature, you might find it
2910 reasonable to call tcSplitSigmaTy twice on the non-default type signature, and
2911 call it once on the default type signature. For most classes and methods, this
2912 will work, but Each is a bit of an exceptional case. The way `each` is written,
2913 it doesn't quantify any additional type variables besides those of the Each
2914 class itself, so the non-default type signature for `each` is actually this:
2916 forall s t a b. Each s t a b => Traversal s t a b
2918 Notice that there _appears_ to only be one forall. But there's actually another
2919 forall lurking in the Traversal type synonym, so if you call tcSplitSigmaTy
2920 twice, you'll also go under the forall in Traversal! That is, you'll end up
2923 (a -> f b) -> s -> f t
2925 A problem arises because you only call tcSplitSigmaTy once on the default type
2926 signature for `each`, which gives you
2932 forall f. Applicative f => (a -> f b) -> s -> f t
2934 This is _not_ the same thing as (a -> f b) -> s -> f t! So now tcMatchTy will
2935 say that the tau types for `each` are not equal.
2937 A solution to this problem is to use tcSplitNestedSigmaTys instead of
2938 tcSplitSigmaTy. tcSplitNestedSigmaTys will always split any foralls that it
2939 sees until it can't go any further, so if you called it on the default type
2940 signature for `each`, it would return (a -> f b) -> s -> f t like we desired.
2942 ************************************************************************
2944 Checking role validity
2946 ************************************************************************
2949 checkValidRoleAnnots
:: RoleAnnotEnv
-> TyCon
-> TcM
()
2950 checkValidRoleAnnots role_annots tc
2951 | isTypeSynonymTyCon tc
= check_no_roles
2952 | isFamilyTyCon tc
= check_no_roles
2953 | isAlgTyCon tc
= check_roles
2954 |
otherwise = return ()
2956 -- Role annotations are given only on *explicit* variables,
2957 -- but a tycon stores roles for all variables.
2958 -- So, we drop the implicit roles (which are all Nominal, anyway).
2960 tyvars
= tyConTyVars tc
2961 roles
= tyConRoles tc
2962 (vis_roles
, vis_vars
) = unzip $ snd $
2963 partitionInvisibles tc
(mkTyVarTy
. snd) $
2965 role_annot_decl_maybe
= lookupRoleAnnot role_annots name
2968 = whenIsJust role_annot_decl_maybe
$
2969 \decl
@(L loc
(RoleAnnotDecl _ the_role_annots
)) ->
2970 addRoleAnnotCtxt name
$
2972 { role_annots_ok
<- xoptM LangExt
.RoleAnnotations
2973 ; checkTc role_annots_ok
$ needXRoleAnnotations tc
2974 ; checkTc
(vis_vars `equalLength` the_role_annots
)
2975 (wrongNumberOfRoles vis_vars decl
)
2976 ; _
<- zipWith3M checkRoleAnnot vis_vars the_role_annots vis_roles
2977 -- Representational or phantom roles for class parameters
2978 -- quickly lead to incoherence. So, we require
2979 -- IncoherentInstances to have them. See #8773.
2980 ; incoherent_roles_ok
<- xoptM LangExt
.IncoherentInstances
2981 ; checkTc
( incoherent_roles_ok
2982 ||
(not $ isClassTyCon tc
)
2983 ||
(all (== Nominal
) vis_roles
))
2986 ; lint
<- goptM Opt_DoCoreLinting
2987 ; when lint
$ checkValidRoles tc
}
2990 = whenIsJust role_annot_decl_maybe illegalRoleAnnotDecl
2992 checkRoleAnnot
:: TyVar
-> Located
(Maybe Role
) -> Role
-> TcM
()
2993 checkRoleAnnot _
(L _ Nothing
) _
= return ()
2994 checkRoleAnnot tv
(L _
(Just r1
)) r2
2996 addErrTc
$ badRoleAnnot
(tyVarName tv
) r1 r2
2998 -- This is a double-check on the role inference algorithm. It is only run when
2999 -- -dcore-lint is enabled. See Note [Role inference] in TcTyDecls
3000 checkValidRoles
:: TyCon
-> TcM
()
3001 -- If you edit this function, you may need to update the GHC formalism
3002 -- See Note [GHC Formalism] in CoreLint
3005 -- tyConDataCons returns an empty list for data families
3006 = mapM_ check_dc_roles
(tyConDataCons tc
)
3007 | Just rhs
<- synTyConRhs_maybe tc
3008 = check_ty_roles
(zipVarEnv
(tyConTyVars tc
) (tyConRoles tc
)) Representational rhs
3012 check_dc_roles datacon
3013 = do { traceTc
"check_dc_roles" (ppr datacon
<+> ppr
(tyConRoles tc
))
3014 ; mapM_ (check_ty_roles role_env Representational
) $
3015 eqSpecPreds eq_spec
++ theta
++ arg_tys
}
3016 -- See Note [Role-checking data constructor arguments] in TcTyDecls
3018 (univ_tvs
, ex_tvs
, eq_spec
, theta
, arg_tys
, _res_ty
)
3019 = dataConFullSig datacon
3020 univ_roles
= zipVarEnv univ_tvs
(tyConRoles tc
)
3021 -- zipVarEnv uses zipEqual, but we don't want that for ex_tvs
3022 ex_roles
= mkVarEnv
(map (, Nominal
) ex_tvs
)
3023 role_env
= univ_roles `plusVarEnv` ex_roles
3025 check_ty_roles env role ty
3026 | Just ty
' <- coreView ty
-- #14101
3027 = check_ty_roles env role ty
'
3029 check_ty_roles env role
(TyVarTy tv
)
3030 = case lookupVarEnv env tv
of
3031 Just role
' -> unless (role
' `ltRole` role || role
' == role
) $
3032 report_error
$ text
"type variable" <+> quotes
(ppr tv
) <+>
3033 text
"cannot have role" <+> ppr role
<+>
3034 text
"because it was assigned role" <+> ppr role
'
3035 Nothing
-> report_error
$ text
"type variable" <+> quotes
(ppr tv
) <+>
3036 text
"missing in environment"
3038 check_ty_roles env Representational
(TyConApp tc tys
)
3039 = let roles
' = tyConRoles tc
in
3040 zipWithM_ (maybe_check_ty_roles env
) roles
' tys
3042 check_ty_roles env Nominal
(TyConApp _ tys
)
3043 = mapM_ (check_ty_roles env Nominal
) tys
3045 check_ty_roles _ Phantom ty
@(TyConApp
{})
3046 = pprPanic
"check_ty_roles" (ppr ty
)
3048 check_ty_roles env role
(AppTy ty1 ty2
)
3049 = check_ty_roles env role ty1
3050 >> check_ty_roles env Nominal ty2
3052 check_ty_roles env role
(FunTy ty1 ty2
)
3053 = check_ty_roles env role ty1
3054 >> check_ty_roles env role ty2
3056 check_ty_roles env role
(ForAllTy
(TvBndr tv _
) ty
)
3057 = check_ty_roles env Nominal
(tyVarKind tv
)
3058 >> check_ty_roles
(extendVarEnv env tv Nominal
) role ty
3060 check_ty_roles _ _
(LitTy
{}) = return ()
3062 check_ty_roles env role
(CastTy t _
)
3063 = check_ty_roles env role t
3065 check_ty_roles _ role
(CoercionTy co
)
3066 = unless (role
== Phantom
) $
3067 report_error
$ text
"coercion" <+> ppr co
<+> text
"has bad role" <+> ppr role
3069 maybe_check_ty_roles env role ty
3070 = when (role
== Nominal || role
== Representational
) $
3071 check_ty_roles env role ty
3074 = addErrTc
$ vcat
[text
"Internal error in role inference:",
3076 text
"Please report this as a GHC bug: http://www.haskell.org/ghc/reportabug"]
3079 ************************************************************************
3083 ************************************************************************
3086 tcAddTyFamInstCtxt
:: TyFamInstDecl GhcRn
-> TcM a
-> TcM a
3087 tcAddTyFamInstCtxt decl
3088 = tcAddFamInstCtxt
(text
"type instance") (tyFamInstDeclName decl
)
3090 tcMkDataFamInstCtxt
:: DataFamInstDecl GhcRn
-> SDoc
3091 tcMkDataFamInstCtxt decl
@(DataFamInstDecl
{ dfid_eqn
=
3092 HsIB
{ hsib_body
= eqn
}})
3093 = tcMkFamInstCtxt
(pprDataFamInstFlavour decl
<+> text
"instance")
3094 (unLoc
(feqn_tycon eqn
))
3096 tcAddDataFamInstCtxt
:: DataFamInstDecl GhcRn
-> TcM a
-> TcM a
3097 tcAddDataFamInstCtxt decl
3098 = addErrCtxt
(tcMkDataFamInstCtxt decl
)
3100 tcMkFamInstCtxt
:: SDoc
-> Name
-> SDoc
3101 tcMkFamInstCtxt flavour tycon
3102 = hsep
[ text
"In the" <+> flavour
<+> text
"declaration for"
3103 , quotes
(ppr tycon
) ]
3105 tcAddFamInstCtxt
:: SDoc
-> Name
-> TcM a
-> TcM a
3106 tcAddFamInstCtxt flavour tycon thing_inside
3107 = addErrCtxt
(tcMkFamInstCtxt flavour tycon
) thing_inside
3109 tcAddClosedTypeFamilyDeclCtxt
:: TyCon
-> TcM a
-> TcM a
3110 tcAddClosedTypeFamilyDeclCtxt tc
3113 ctxt
= text
"In the equations for closed type family" <+>
3116 resultTypeMisMatch
:: FieldLabelString
-> DataCon
-> DataCon
-> SDoc
3117 resultTypeMisMatch field_name con1 con2
3118 = vcat
[sep
[text
"Constructors" <+> ppr con1
<+> text
"and" <+> ppr con2
,
3119 text
"have a common field" <+> quotes
(ppr field_name
) <> comma
],
3120 nest
2 $ text
"but have different result types"]
3122 fieldTypeMisMatch
:: FieldLabelString
-> DataCon
-> DataCon
-> SDoc
3123 fieldTypeMisMatch field_name con1 con2
3124 = sep
[text
"Constructors" <+> ppr con1
<+> text
"and" <+> ppr con2
,
3125 text
"give different types for field", quotes
(ppr field_name
)]
3127 dataConCtxtName
:: [Located Name
] -> SDoc
3128 dataConCtxtName
[con
]
3129 = text
"In the definition of data constructor" <+> quotes
(ppr con
)
3131 = text
"In the definition of data constructors" <+> interpp
'SP con
3133 dataConCtxt
:: Outputable a
=> a
-> SDoc
3134 dataConCtxt con
= text
"In the definition of data constructor" <+> quotes
(ppr con
)
3136 classOpCtxt
:: Var
-> Type
-> SDoc
3137 classOpCtxt sel_id tau
= sep
[text
"When checking the class method:",
3138 nest
2 (pprPrefixOcc sel_id
<+> dcolon
<+> ppr tau
)]
3140 classArityErr
:: Int -> Class
-> SDoc
3142 | n
== 0 = mkErr
"No" "no-parameter"
3143 |
otherwise = mkErr
"Too many" "multi-parameter"
3145 mkErr howMany allowWhat
=
3146 vcat
[text
(howMany
++ " parameters for class") <+> quotes
(ppr cls
),
3147 parens
(text
("Use MultiParamTypeClasses to allow "
3148 ++ allowWhat
++ " classes"))]
3150 classFunDepsErr
:: Class
-> SDoc
3152 = vcat
[text
"Fundeps in class" <+> quotes
(ppr cls
),
3153 parens
(text
"Use FunctionalDependencies to allow fundeps")]
3155 badMethPred
:: Id
-> TcPredType
-> SDoc
3156 badMethPred sel_id
pred
3157 = vcat
[ hang
(text
"Constraint" <+> quotes
(ppr
pred)
3158 <+> text
"in the type of" <+> quotes
(ppr sel_id
))
3159 2 (text
"constrains only the class type variables")
3160 , text
"Use ConstrainedClassMethods to allow it" ]
3162 noClassTyVarErr
:: Class
-> TyCon
-> SDoc
3163 noClassTyVarErr clas fam_tc
3164 = sep
[ text
"The associated type" <+> quotes
(ppr fam_tc
)
3165 , text
"mentions none of the type or kind variables of the class" <+>
3166 quotes
(ppr clas
<+> hsep
(map ppr
(classTyVars clas
)))]
3168 badDataConTyCon
:: DataCon
-> Type
-> Type
-> SDoc
3169 badDataConTyCon data_con res_ty_tmpl actual_res_ty
3170 | tcIsForAllTy actual_res_ty
3171 = nested_foralls_contexts_suggestion
3172 |
isJust (tcSplitPredFunTy_maybe actual_res_ty
)
3173 = nested_foralls_contexts_suggestion
3175 = hang
(text
"Data constructor" <+> quotes
(ppr data_con
) <+>
3176 text
"returns type" <+> quotes
(ppr actual_res_ty
))
3177 2 (text
"instead of an instance of its parent type" <+> quotes
(ppr res_ty_tmpl
))
3179 -- This suggestion is useful for suggesting how to correct code like what
3180 -- was reported in Trac #12087:
3183 -- MkF :: Ord a => Eq a => a -> F a
3185 -- Although nested foralls or contexts are allowed in function type
3186 -- signatures, it is much more difficult to engineer GADT constructor type
3187 -- signatures to allow something similar, so we error in the latter case.
3188 -- Nevertheless, we can at least suggest how a user might reshuffle their
3189 -- exotic GADT constructor type signature so that GHC will accept.
3190 nested_foralls_contexts_suggestion
=
3191 text
"GADT constructor type signature cannot contain nested"
3192 <+> quotes forAllLit
<> text
"s or contexts"
3193 $+$ hang
(text
"Suggestion: instead use this type signature:")
3194 2 (ppr
(dataConName data_con
) <+> dcolon
<+> ppr suggested_ty
)
3196 -- To construct a type that GHC would accept (suggested_ty), we:
3198 -- 1) Find the existentially quantified type variables and the class
3199 -- predicates from the datacon. (NB: We don't need the universally
3200 -- quantified type variables, since rejigConRes won't substitute them in
3201 -- the result type if it fails, as in this scenario.)
3202 -- 2) Split apart the return type (which is headed by a forall or a
3203 -- context) using tcSplitNestedSigmaTys, collecting the type variables
3204 -- and class predicates we find, as well as the rho type lurking
3205 -- underneath the nested foralls and contexts.
3206 -- 3) Smash together the type variables and class predicates from 1) and
3207 -- 2), and prepend them to the rho type from 2).
3208 actual_ex_tvs
= dataConExTyVarBinders data_con
3209 actual_theta
= dataConTheta data_con
3210 (actual_res_tvs
, actual_res_theta
, actual_res_rho
)
3211 = tcSplitNestedSigmaTys actual_res_ty
3212 actual_res_tvbs
= mkTyVarBinders Specified actual_res_tvs
3213 suggested_ty
= mkForAllTys
(actual_ex_tvs
++ actual_res_tvbs
) $
3214 mkFunTys
(actual_theta
++ actual_res_theta
)
3217 badGadtDecl
:: Name
-> SDoc
3219 = vcat
[ text
"Illegal generalised algebraic data declaration for" <+> quotes
(ppr tc_name
)
3220 , nest
2 (parens
$ text
"Use GADTs to allow GADTs") ]
3222 badExistential
:: DataCon
-> SDoc
3224 = hang
(text
"Data constructor" <+> quotes
(ppr con
) <+>
3225 text
"has existential type variables, a context, or a specialised result type")
3226 2 (vcat
[ ppr con
<+> dcolon
<+> ppr
(dataConUserType con
)
3227 , parens
$ text
"Use ExistentialQuantification or GADTs to allow this" ])
3229 badStupidTheta
:: Name
-> SDoc
3230 badStupidTheta tc_name
3231 = text
"A data type declared in GADT style cannot have a context:" <+> quotes
(ppr tc_name
)
3233 newtypeConError
:: Name
-> Int -> SDoc
3234 newtypeConError tycon n
3235 = sep
[text
"A newtype must have exactly one constructor,",
3236 nest
2 $ text
"but" <+> quotes
(ppr tycon
) <+> text
"has" <+> speakN n
]
3238 newtypeStrictError
:: DataCon
-> SDoc
3239 newtypeStrictError con
3240 = sep
[text
"A newtype constructor cannot have a strictness annotation,",
3241 nest
2 $ text
"but" <+> quotes
(ppr con
) <+> text
"does"]
3243 newtypeFieldErr
:: DataCon
-> Int -> SDoc
3244 newtypeFieldErr con_name n_flds
3245 = sep
[text
"The constructor of a newtype must have exactly one field",
3246 nest
2 $ text
"but" <+> quotes
(ppr con_name
) <+> text
"has" <+> speakN n_flds
]
3248 badSigTyDecl
:: Name
-> SDoc
3249 badSigTyDecl tc_name
3250 = vcat
[ text
"Illegal kind signature" <+>
3251 quotes
(ppr tc_name
)
3252 , nest
2 (parens
$ text
"Use KindSignatures to allow kind signatures") ]
3254 emptyConDeclsErr
:: Name
-> SDoc
3255 emptyConDeclsErr tycon
3256 = sep
[quotes
(ppr tycon
) <+> text
"has no constructors",
3257 nest
2 $ text
"(EmptyDataDecls permits this)"]
3259 wrongKindOfFamily
:: TyCon
-> SDoc
3260 wrongKindOfFamily family
3261 = text
"Wrong category of family instance; declaration was for a"
3264 kindOfFamily | isTypeFamilyTyCon family
= text
"type family"
3265 | isDataFamilyTyCon family
= text
"data family"
3266 |
otherwise = pprPanic
"wrongKindOfFamily" (ppr family
)
3268 wrongNumberOfParmsErr
:: Arity
-> SDoc
3269 wrongNumberOfParmsErr max_args
3270 = text
"Number of parameters must match family declaration; expected"
3273 defaultAssocKindErr
:: TyCon
-> SDoc
3274 defaultAssocKindErr fam_tc
3275 = text
"Kind mis-match on LHS of default declaration for"
3276 <+> quotes
(ppr fam_tc
)
3278 wrongTyFamName
:: Name
-> Name
-> SDoc
3279 wrongTyFamName fam_tc_name eqn_tc_name
3280 = hang
(text
"Mismatched type name in type family instance.")
3281 2 (vcat
[ text
"Expected:" <+> ppr fam_tc_name
3282 , text
" Actual:" <+> ppr eqn_tc_name
])
3284 badRoleAnnot
:: Name
-> Role
-> Role
-> SDoc
3285 badRoleAnnot var annot inferred
3286 = hang
(text
"Role mismatch on variable" <+> ppr var
<> colon
)
3287 2 (sep
[ text
"Annotation says", ppr annot
3288 , text
"but role", ppr inferred
3289 , text
"is required" ])
3291 wrongNumberOfRoles
:: [a
] -> LRoleAnnotDecl GhcRn
-> SDoc
3292 wrongNumberOfRoles tyvars d
@(L _
(RoleAnnotDecl _ annots
))
3293 = hang
(text
"Wrong number of roles listed in role annotation;" $$
3294 text
"Expected" <+> (ppr
$ length tyvars
) <> comma
<+>
3295 text
"got" <+> (ppr
$ length annots
) <> colon
)
3298 illegalRoleAnnotDecl
:: LRoleAnnotDecl GhcRn
-> TcM
()
3299 illegalRoleAnnotDecl
(L loc
(RoleAnnotDecl tycon _
))
3302 addErrTc
(text
"Illegal role annotation for" <+> ppr tycon
<> char
';' $$
3303 text
"they are allowed only for datatypes and classes.")
3305 needXRoleAnnotations
:: TyCon
-> SDoc
3306 needXRoleAnnotations tc
3307 = text
"Illegal role annotation for" <+> ppr tc
<> char
';' $$
3308 text
"did you intend to use RoleAnnotations?"
3310 incoherentRoles
:: SDoc
3311 incoherentRoles
= (text
"Roles other than" <+> quotes
(text
"nominal") <+>
3312 text
"for class parameters can lead to incoherence.") $$
3313 (text
"Use IncoherentInstances to allow this; bad role found")
3315 addTyConCtxt
:: TyCon
-> TcM a
-> TcM a
3320 flav
= ppr
(tyConFlavour tc
)
3321 ctxt
= hsep
[ text
"In the", flav
3322 , text
"declaration for", quotes
(ppr name
) ]
3324 addRoleAnnotCtxt
:: Name
-> TcM a
-> TcM a
3325 addRoleAnnotCtxt name
3327 text
"while checking a role annotation for" <+> quotes
(ppr name
)