Treat isConstraintKind more consistently
[ghc.git] / compiler / typecheck / TcValidity.hs
1 {-
2 (c) The University of Glasgow 2006
3 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 -}
5
6 {-# LANGUAGE CPP, TupleSections, ViewPatterns #-}
7
8 module TcValidity (
9 Rank, UserTypeCtxt(..), checkValidType, checkValidMonoType,
10 ContextKind(..), expectedKindInCtxt,
11 checkValidTheta, checkValidFamPats,
12 checkValidInstance, checkValidInstHead, validDerivPred,
13 checkTySynRhs,
14 ClsInstInfo, checkValidCoAxiom, checkValidCoAxBranch,
15 checkValidTyFamEqn,
16 arityErr, badATErr,
17 checkValidTelescope,
18 allDistinctTyVars
19 ) where
20
21 #include "HsVersions.h"
22
23 import GhcPrelude
24
25 import Maybes
26
27 -- friends:
28 import TcUnify ( tcSubType_NC )
29 import TcSimplify ( simplifyAmbiguityCheck )
30 import TyCoRep
31 import TcType hiding ( sizeType, sizeTypes )
32 import PrelNames
33 import Type
34 import Coercion
35 import CoAxiom
36 import Class
37 import TyCon
38
39 -- others:
40 import HsSyn -- HsType
41 import TcRnMonad -- TcType, amongst others
42 import TcEnv ( tcGetInstEnvs, tcInitTidyEnv, tcInitOpenTidyEnv )
43 import FunDeps
44 import InstEnv ( InstMatch, lookupInstEnv )
45 import FamInstEnv ( isDominatedBy, injectiveBranches,
46 InjectivityCheckResult(..) )
47 import FamInst ( makeInjectivityErrors )
48 import Name
49 import VarEnv
50 import VarSet
51 import Var ( TyVarBndr(..), mkTyVar )
52 import ErrUtils
53 import DynFlags
54 import Util
55 import ListSetOps
56 import SrcLoc
57 import Outputable
58 import Module
59 import Unique ( mkAlphaTyVarUnique )
60 import qualified GHC.LanguageExtensions as LangExt
61
62 import Control.Monad
63 import Data.List ( (\\) )
64 import qualified Data.List.NonEmpty as NE
65
66 {-
67 ************************************************************************
68 * *
69 Checking for ambiguity
70 * *
71 ************************************************************************
72
73 Note [The ambiguity check for type signatures]
74 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
75 checkAmbiguity is a check on *user-supplied type signatures*. It is
76 *purely* there to report functions that cannot possibly be called. So for
77 example we want to reject:
78 f :: C a => Int
79 The idea is there can be no legal calls to 'f' because every call will
80 give rise to an ambiguous constraint. We could soundly omit the
81 ambiguity check on type signatures entirely, at the expense of
82 delaying ambiguity errors to call sites. Indeed, the flag
83 -XAllowAmbiguousTypes switches off the ambiguity check.
84
85 What about things like this:
86 class D a b | a -> b where ..
87 h :: D Int b => Int
88 The Int may well fix 'b' at the call site, so that signature should
89 not be rejected. Moreover, using *visible* fundeps is too
90 conservative. Consider
91 class X a b where ...
92 class D a b | a -> b where ...
93 instance D a b => X [a] b where...
94 h :: X a b => a -> a
95 Here h's type looks ambiguous in 'b', but here's a legal call:
96 ...(h [True])...
97 That gives rise to a (X [Bool] beta) constraint, and using the
98 instance means we need (D Bool beta) and that fixes 'beta' via D's
99 fundep!
100
101 Behind all these special cases there is a simple guiding principle.
102 Consider
103
104 f :: <type>
105 f = ...blah...
106
107 g :: <type>
108 g = f
109
110 You would think that the definition of g would surely typecheck!
111 After all f has exactly the same type, and g=f. But in fact f's type
112 is instantiated and the instantiated constraints are solved against
113 the originals, so in the case an ambiguous type it won't work.
114 Consider our earlier example f :: C a => Int. Then in g's definition,
115 we'll instantiate to (C alpha) and try to deduce (C alpha) from (C a),
116 and fail.
117
118 So in fact we use this as our *definition* of ambiguity. We use a
119 very similar test for *inferred* types, to ensure that they are
120 unambiguous. See Note [Impedance matching] in TcBinds.
121
122 This test is very conveniently implemented by calling
123 tcSubType <type> <type>
124 This neatly takes account of the functional dependecy stuff above,
125 and implicit parameter (see Note [Implicit parameters and ambiguity]).
126 And this is what checkAmbiguity does.
127
128 What about this, though?
129 g :: C [a] => Int
130 Is every call to 'g' ambiguous? After all, we might have
131 instance C [a] where ...
132 at the call site. So maybe that type is ok! Indeed even f's
133 quintessentially ambiguous type might, just possibly be callable:
134 with -XFlexibleInstances we could have
135 instance C a where ...
136 and now a call could be legal after all! Well, we'll reject this
137 unless the instance is available *here*.
138
139 Note [When to call checkAmbiguity]
140 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
141 We call checkAmbiguity
142 (a) on user-specified type signatures
143 (b) in checkValidType
144
145 Conncerning (b), you might wonder about nested foralls. What about
146 f :: forall b. (forall a. Eq a => b) -> b
147 The nested forall is ambiguous. Originally we called checkAmbiguity
148 in the forall case of check_type, but that had two bad consequences:
149 * We got two error messages about (Eq b) in a nested forall like this:
150 g :: forall a. Eq a => forall b. Eq b => a -> a
151 * If we try to check for ambiguity of a nested forall like
152 (forall a. Eq a => b), the implication constraint doesn't bind
153 all the skolems, which results in "No skolem info" in error
154 messages (see Trac #10432).
155
156 To avoid this, we call checkAmbiguity once, at the top, in checkValidType.
157 (I'm still a bit worried about unbound skolems when the type mentions
158 in-scope type variables.)
159
160 In fact, because of the co/contra-variance implemented in tcSubType,
161 this *does* catch function f above. too.
162
163 Concerning (a) the ambiguity check is only used for *user* types, not
164 for types coming from inteface files. The latter can legitimately
165 have ambiguous types. Example
166
167 class S a where s :: a -> (Int,Int)
168 instance S Char where s _ = (1,1)
169 f:: S a => [a] -> Int -> (Int,Int)
170 f (_::[a]) x = (a*x,b)
171 where (a,b) = s (undefined::a)
172
173 Here the worker for f gets the type
174 fw :: forall a. S a => Int -> (# Int, Int #)
175
176
177 Note [Implicit parameters and ambiguity]
178 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
179 Only a *class* predicate can give rise to ambiguity
180 An *implicit parameter* cannot. For example:
181 foo :: (?x :: [a]) => Int
182 foo = length ?x
183 is fine. The call site will supply a particular 'x'
184
185 Furthermore, the type variables fixed by an implicit parameter
186 propagate to the others. E.g.
187 foo :: (Show a, ?x::[a]) => Int
188 foo = show (?x++?x)
189 The type of foo looks ambiguous. But it isn't, because at a call site
190 we might have
191 let ?x = 5::Int in foo
192 and all is well. In effect, implicit parameters are, well, parameters,
193 so we can take their type variables into account as part of the
194 "tau-tvs" stuff. This is done in the function 'FunDeps.grow'.
195 -}
196
197 checkAmbiguity :: UserTypeCtxt -> Type -> TcM ()
198 checkAmbiguity ctxt ty
199 | wantAmbiguityCheck ctxt
200 = do { traceTc "Ambiguity check for" (ppr ty)
201 -- Solve the constraints eagerly because an ambiguous type
202 -- can cause a cascade of further errors. Since the free
203 -- tyvars are skolemised, we can safely use tcSimplifyTop
204 ; allow_ambiguous <- xoptM LangExt.AllowAmbiguousTypes
205 ; (_wrap, wanted) <- addErrCtxt (mk_msg allow_ambiguous) $
206 captureConstraints $
207 tcSubType_NC ctxt ty ty
208 ; simplifyAmbiguityCheck ty wanted
209
210 ; traceTc "Done ambiguity check for" (ppr ty) }
211
212 | otherwise
213 = return ()
214 where
215 mk_msg allow_ambiguous
216 = vcat [ text "In the ambiguity check for" <+> what
217 , ppUnless allow_ambiguous ambig_msg ]
218 ambig_msg = text "To defer the ambiguity check to use sites, enable AllowAmbiguousTypes"
219 what | Just n <- isSigMaybe ctxt = quotes (ppr n)
220 | otherwise = pprUserTypeCtxt ctxt
221
222 wantAmbiguityCheck :: UserTypeCtxt -> Bool
223 wantAmbiguityCheck ctxt
224 = case ctxt of -- See Note [When we don't check for ambiguity]
225 GhciCtxt -> False
226 TySynCtxt {} -> False
227 TypeAppCtxt -> False
228 _ -> True
229
230 checkUserTypeError :: Type -> TcM ()
231 -- Check to see if the type signature mentions "TypeError blah"
232 -- anywhere in it, and fail if so.
233 --
234 -- Very unsatisfactorily (Trac #11144) we need to tidy the type
235 -- because it may have come from an /inferred/ signature, not a
236 -- user-supplied one. This is really only a half-baked fix;
237 -- the other errors in checkValidType don't do tidying, and so
238 -- may give bad error messages when given an inferred type.
239 checkUserTypeError = check
240 where
241 check ty
242 | Just msg <- userTypeError_maybe ty = fail_with msg
243 | Just (_,ts) <- splitTyConApp_maybe ty = mapM_ check ts
244 | Just (t1,t2) <- splitAppTy_maybe ty = check t1 >> check t2
245 | Just (_,t1) <- splitForAllTy_maybe ty = check t1
246 | otherwise = return ()
247
248 fail_with msg = do { env0 <- tcInitTidyEnv
249 ; let (env1, tidy_msg) = tidyOpenType env0 msg
250 ; failWithTcM (env1, pprUserTypeErrorTy tidy_msg) }
251
252
253 {- Note [When we don't check for ambiguity]
254 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
255 In a few places we do not want to check a user-specified type for ambiguity
256
257 * GhciCtxt: Allow ambiguous types in GHCi's :kind command
258 E.g. type family T a :: * -- T :: forall k. k -> *
259 Then :k T should work in GHCi, not complain that
260 (T k) is ambiguous!
261
262 * TySynCtxt: type T a b = C a b => blah
263 It may be that when we /use/ T, we'll give an 'a' or 'b' that somehow
264 cure the ambiguity. So we defer the ambiguity check to the use site.
265
266 There is also an implementation reason (Trac #11608). In the RHS of
267 a type synonym we don't (currently) instantiate 'a' and 'b' with
268 TcTyVars before calling checkValidType, so we get asertion failures
269 from doing an ambiguity check on a type with TyVars in it. Fixing this
270 would not be hard, but let's wait till there's a reason.
271
272 * TypeAppCtxt: visible type application
273 f @ty
274 No need to check ty for ambiguity
275
276
277 ************************************************************************
278 * *
279 Checking validity of a user-defined type
280 * *
281 ************************************************************************
282
283 When dealing with a user-written type, we first translate it from an HsType
284 to a Type, performing kind checking, and then check various things that should
285 be true about it. We don't want to perform these checks at the same time
286 as the initial translation because (a) they are unnecessary for interface-file
287 types and (b) when checking a mutually recursive group of type and class decls,
288 we can't "look" at the tycons/classes yet. Also, the checks are rather
289 diverse, and used to really mess up the other code.
290
291 One thing we check for is 'rank'.
292
293 Rank 0: monotypes (no foralls)
294 Rank 1: foralls at the front only, Rank 0 inside
295 Rank 2: foralls at the front, Rank 1 on left of fn arrow,
296
297 basic ::= tyvar | T basic ... basic
298
299 r2 ::= forall tvs. cxt => r2a
300 r2a ::= r1 -> r2a | basic
301 r1 ::= forall tvs. cxt => r0
302 r0 ::= r0 -> r0 | basic
303
304 Another thing is to check that type synonyms are saturated.
305 This might not necessarily show up in kind checking.
306 type A i = i
307 data T k = MkT (k Int)
308 f :: T A -- BAD!
309 -}
310
311 checkValidType :: UserTypeCtxt -> Type -> TcM ()
312 -- Checks that a user-written type is valid for the given context
313 -- Assumes argument is fully zonked
314 -- Not used for instance decls; checkValidInstance instead
315 checkValidType ctxt ty
316 = do { traceTc "checkValidType" (ppr ty <+> text "::" <+> ppr (typeKind ty))
317 ; rankn_flag <- xoptM LangExt.RankNTypes
318 ; impred_flag <- xoptM LangExt.ImpredicativeTypes
319 ; let gen_rank :: Rank -> Rank
320 gen_rank r | rankn_flag = ArbitraryRank
321 | otherwise = r
322
323 rank1 = gen_rank r1
324 rank0 = gen_rank r0
325
326 r0 = rankZeroMonoType
327 r1 = LimitedRank True r0
328
329 rank
330 = case ctxt of
331 DefaultDeclCtxt-> MustBeMonoType
332 ResSigCtxt -> MustBeMonoType
333 PatSigCtxt -> rank0
334 RuleSigCtxt _ -> rank1
335 TySynCtxt _ -> rank0
336
337 ExprSigCtxt -> rank1
338 KindSigCtxt -> rank1
339 TypeAppCtxt | impred_flag -> ArbitraryRank
340 | otherwise -> tyConArgMonoType
341 -- Normally, ImpredicativeTypes is handled in check_arg_type,
342 -- but visible type applications don't go through there.
343 -- So we do this check here.
344
345 FunSigCtxt {} -> rank1
346 InfSigCtxt _ -> ArbitraryRank -- Inferred type
347 ConArgCtxt _ -> rank1 -- We are given the type of the entire
348 -- constructor, hence rank 1
349 PatSynCtxt _ -> rank1
350
351 ForSigCtxt _ -> rank1
352 SpecInstCtxt -> rank1
353 ThBrackCtxt -> rank1
354 GhciCtxt -> ArbitraryRank
355
356 TyVarBndrKindCtxt _ -> rank0
357 DataKindCtxt _ -> rank1
358 TySynKindCtxt _ -> rank1
359 TyFamResKindCtxt _ -> rank1
360
361 _ -> panic "checkValidType"
362 -- Can't happen; not used for *user* sigs
363
364 ; env <- tcInitOpenTidyEnv (tyCoVarsOfTypeList ty)
365
366 -- Check the internal validity of the type itself
367 ; check_type env ctxt rank ty
368
369 ; checkUserTypeError ty
370
371 -- Check for ambiguous types. See Note [When to call checkAmbiguity]
372 -- NB: this will happen even for monotypes, but that should be cheap;
373 -- and there may be nested foralls for the subtype test to examine
374 ; checkAmbiguity ctxt ty
375
376 ; traceTc "checkValidType done" (ppr ty <+> text "::" <+> ppr (typeKind ty)) }
377
378 checkValidMonoType :: Type -> TcM ()
379 -- Assumes argument is fully zonked
380 checkValidMonoType ty
381 = do { env <- tcInitOpenTidyEnv (tyCoVarsOfTypeList ty)
382 ; check_type env SigmaCtxt MustBeMonoType ty }
383
384 checkTySynRhs :: UserTypeCtxt -> TcType -> TcM ()
385 checkTySynRhs ctxt ty
386 | tcReturnsConstraintKind actual_kind
387 = do { ck <- xoptM LangExt.ConstraintKinds
388 ; if ck
389 then when (tcIsConstraintKind actual_kind)
390 (do { dflags <- getDynFlags
391 ; check_pred_ty emptyTidyEnv dflags ctxt ty })
392 else addErrTcM (constraintSynErr emptyTidyEnv actual_kind) }
393
394 | otherwise
395 = return ()
396 where
397 actual_kind = typeKind ty
398
399 -- | The kind expected in a certain context.
400 data ContextKind = TheKind Kind -- ^ a specific kind
401 | AnythingKind -- ^ any kind will do
402 | OpenKind -- ^ something of the form @TYPE _@
403
404 -- Depending on the context, we might accept any kind (for instance, in a TH
405 -- splice), or only certain kinds (like in type signatures).
406 expectedKindInCtxt :: UserTypeCtxt -> ContextKind
407 expectedKindInCtxt (TySynCtxt _) = AnythingKind
408 expectedKindInCtxt ThBrackCtxt = AnythingKind
409 expectedKindInCtxt GhciCtxt = AnythingKind
410 -- The types in a 'default' decl can have varying kinds
411 -- See Note [Extended defaults]" in TcEnv
412 expectedKindInCtxt DefaultDeclCtxt = AnythingKind
413 expectedKindInCtxt TypeAppCtxt = AnythingKind
414 expectedKindInCtxt (ForSigCtxt _) = TheKind liftedTypeKind
415 expectedKindInCtxt InstDeclCtxt = TheKind constraintKind
416 expectedKindInCtxt SpecInstCtxt = TheKind constraintKind
417 expectedKindInCtxt _ = OpenKind
418
419 {-
420 Note [Higher rank types]
421 ~~~~~~~~~~~~~~~~~~~~~~~~
422 Technically
423 Int -> forall a. a->a
424 is still a rank-1 type, but it's not Haskell 98 (Trac #5957). So the
425 validity checker allow a forall after an arrow only if we allow it
426 before -- that is, with Rank2Types or RankNTypes
427 -}
428
429 data Rank = ArbitraryRank -- Any rank ok
430
431 | LimitedRank -- Note [Higher rank types]
432 Bool -- Forall ok at top
433 Rank -- Use for function arguments
434
435 | MonoType SDoc -- Monotype, with a suggestion of how it could be a polytype
436
437 | MustBeMonoType -- Monotype regardless of flags
438
439
440 rankZeroMonoType, tyConArgMonoType, synArgMonoType, constraintMonoType :: Rank
441 rankZeroMonoType = MonoType (text "Perhaps you intended to use RankNTypes or Rank2Types")
442 tyConArgMonoType = MonoType (text "GHC doesn't yet support impredicative polymorphism")
443 synArgMonoType = MonoType (text "Perhaps you intended to use LiberalTypeSynonyms")
444 constraintMonoType = MonoType (vcat [ text "A constraint must be a monotype"
445 , text "Perhaps you intended to use QuantifiedConstraints" ])
446
447 funArgResRank :: Rank -> (Rank, Rank) -- Function argument and result
448 funArgResRank (LimitedRank _ arg_rank) = (arg_rank, LimitedRank (forAllAllowed arg_rank) arg_rank)
449 funArgResRank other_rank = (other_rank, other_rank)
450
451 forAllAllowed :: Rank -> Bool
452 forAllAllowed ArbitraryRank = True
453 forAllAllowed (LimitedRank forall_ok _) = forall_ok
454 forAllAllowed _ = False
455
456 ----------------------------------------
457 check_type :: TidyEnv -> UserTypeCtxt -> Rank -> Type -> TcM ()
458 -- The args say what the *type context* requires, independent
459 -- of *flag* settings. You test the flag settings at usage sites.
460 --
461 -- Rank is allowed rank for function args
462 -- Rank 0 means no for-alls anywhere
463
464 check_type env ctxt rank ty
465 | not (null tvbs && null theta)
466 = do { traceTc "check_type" (ppr ty $$ ppr (forAllAllowed rank))
467 ; checkTcM (forAllAllowed rank) (forAllTyErr env rank ty)
468 -- Reject e.g. (Maybe (?x::Int => Int)),
469 -- with a decent error message
470
471 ; check_valid_theta env' SigmaCtxt theta
472 -- Allow type T = ?x::Int => Int -> Int
473 -- but not type T = ?x::Int
474
475 ; check_type env' ctxt rank tau -- Allow foralls to right of arrow
476
477 ; checkTcM (not (any (`elemVarSet` tyCoVarsOfType phi_kind) tvs))
478 (forAllEscapeErr env' ty tau_kind)
479 }
480 where
481 (tvbs, phi) = tcSplitForAllTyVarBndrs ty
482 (theta, tau) = tcSplitPhiTy phi
483
484 tvs = binderVars tvbs
485 (env', _) = tidyTyCoVarBndrs env tvs
486
487 tau_kind = typeKind tau
488 phi_kind | null theta = tau_kind
489 | otherwise = liftedTypeKind
490 -- If there are any constraints, the kind is *. (#11405)
491
492 check_type _ _ _ (TyVarTy _) = return ()
493
494 check_type env ctxt rank (FunTy arg_ty res_ty)
495 = do { check_type env ctxt arg_rank arg_ty
496 ; check_type env ctxt res_rank res_ty }
497 where
498 (arg_rank, res_rank) = funArgResRank rank
499
500 check_type env ctxt rank (AppTy ty1 ty2)
501 = do { check_type env ctxt rank ty1
502 ; check_arg_type env ctxt rank ty2 }
503
504 check_type env ctxt rank ty@(TyConApp tc tys)
505 | isTypeSynonymTyCon tc || isTypeFamilyTyCon tc
506 = check_syn_tc_app env ctxt rank ty tc tys
507 | isUnboxedTupleTyCon tc = check_ubx_tuple env ctxt ty tys
508 | otherwise = mapM_ (check_arg_type env ctxt rank) tys
509
510 check_type _ _ _ (LitTy {}) = return ()
511
512 check_type env ctxt rank (CastTy ty _) = check_type env ctxt rank ty
513
514 check_type _ _ _ ty = pprPanic "check_type" (ppr ty)
515
516 ----------------------------------------
517 check_syn_tc_app :: TidyEnv -> UserTypeCtxt -> Rank -> KindOrType
518 -> TyCon -> [KindOrType] -> TcM ()
519 -- Used for type synonyms and type synonym families,
520 -- which must be saturated,
521 -- but not data families, which need not be saturated
522 check_syn_tc_app env ctxt rank ty tc tys
523 | tys `lengthAtLeast` tc_arity -- Saturated
524 -- Check that the synonym has enough args
525 -- This applies equally to open and closed synonyms
526 -- It's OK to have an *over-applied* type synonym
527 -- data Tree a b = ...
528 -- type Foo a = Tree [a]
529 -- f :: Foo a b -> ...
530 = do { -- See Note [Liberal type synonyms]
531 ; liberal <- xoptM LangExt.LiberalTypeSynonyms
532 ; if not liberal || isTypeFamilyTyCon tc then
533 -- For H98 and synonym families, do check the type args
534 mapM_ check_arg tys
535
536 else -- In the liberal case (only for closed syns), expand then check
537 case tcView ty of
538 Just ty' -> check_type env ctxt rank ty'
539 Nothing -> pprPanic "check_tau_type" (ppr ty) }
540
541 | GhciCtxt <- ctxt -- Accept under-saturated type synonyms in
542 -- GHCi :kind commands; see Trac #7586
543 = mapM_ check_arg tys
544
545 | otherwise
546 = failWithTc (tyConArityErr tc tys)
547 where
548 tc_arity = tyConArity tc
549 check_arg | isTypeFamilyTyCon tc = check_arg_type env ctxt rank
550 | otherwise = check_type env ctxt synArgMonoType
551
552 ----------------------------------------
553 check_ubx_tuple :: TidyEnv -> UserTypeCtxt -> KindOrType
554 -> [KindOrType] -> TcM ()
555 check_ubx_tuple env ctxt ty tys
556 = do { ub_tuples_allowed <- xoptM LangExt.UnboxedTuples
557 ; checkTcM ub_tuples_allowed (ubxArgTyErr env ty)
558
559 ; impred <- xoptM LangExt.ImpredicativeTypes
560 ; let rank' = if impred then ArbitraryRank else tyConArgMonoType
561 -- c.f. check_arg_type
562 -- However, args are allowed to be unlifted, or
563 -- more unboxed tuples, so can't use check_arg_ty
564 ; mapM_ (check_type env ctxt rank') tys }
565
566 ----------------------------------------
567 check_arg_type :: TidyEnv -> UserTypeCtxt -> Rank -> KindOrType -> TcM ()
568 -- The sort of type that can instantiate a type variable,
569 -- or be the argument of a type constructor.
570 -- Not an unboxed tuple, but now *can* be a forall (since impredicativity)
571 -- Other unboxed types are very occasionally allowed as type
572 -- arguments depending on the kind of the type constructor
573 --
574 -- For example, we want to reject things like:
575 --
576 -- instance Ord a => Ord (forall s. T s a)
577 -- and
578 -- g :: T s (forall b.b)
579 --
580 -- NB: unboxed tuples can have polymorphic or unboxed args.
581 -- This happens in the workers for functions returning
582 -- product types with polymorphic components.
583 -- But not in user code.
584 -- Anyway, they are dealt with by a special case in check_tau_type
585
586 check_arg_type _ _ _ (CoercionTy {}) = return ()
587
588 check_arg_type env ctxt rank ty
589 = do { impred <- xoptM LangExt.ImpredicativeTypes
590 ; let rank' = case rank of -- Predictive => must be monotype
591 MustBeMonoType -> MustBeMonoType -- Monotype, regardless
592 _other | impred -> ArbitraryRank
593 | otherwise -> tyConArgMonoType
594 -- Make sure that MustBeMonoType is propagated,
595 -- so that we don't suggest -XImpredicativeTypes in
596 -- (Ord (forall a.a)) => a -> a
597 -- and so that if it Must be a monotype, we check that it is!
598
599 ; check_type env ctxt rank' ty }
600
601 ----------------------------------------
602 forAllTyErr :: TidyEnv -> Rank -> Type -> (TidyEnv, SDoc)
603 forAllTyErr env rank ty
604 = ( env
605 , vcat [ hang herald 2 (ppr_tidy env ty)
606 , suggestion ] )
607 where
608 (tvs, _theta, _tau) = tcSplitSigmaTy ty
609 herald | null tvs = text "Illegal qualified type:"
610 | otherwise = text "Illegal polymorphic type:"
611 suggestion = case rank of
612 LimitedRank {} -> text "Perhaps you intended to use RankNTypes or Rank2Types"
613 MonoType d -> d
614 _ -> Outputable.empty -- Polytype is always illegal
615
616 forAllEscapeErr :: TidyEnv -> Type -> Kind -> (TidyEnv, SDoc)
617 forAllEscapeErr env ty tau_kind
618 = ( env
619 , hang (vcat [ text "Quantified type's kind mentions quantified type variable"
620 , text "(skolem escape)" ])
621 2 (vcat [ text " type:" <+> ppr_tidy env ty
622 , text "of kind:" <+> ppr_tidy env tau_kind ]) )
623
624 ubxArgTyErr :: TidyEnv -> Type -> (TidyEnv, SDoc)
625 ubxArgTyErr env ty
626 = ( env, vcat [ sep [ text "Illegal unboxed tuple type as function argument:"
627 , ppr_tidy env ty ]
628 , text "Perhaps you intended to use UnboxedTuples" ] )
629
630 {-
631 Note [Liberal type synonyms]
632 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
633 If -XLiberalTypeSynonyms is on, expand closed type synonyms *before*
634 doing validity checking. This allows us to instantiate a synonym defn
635 with a for-all type, or with a partially-applied type synonym.
636 e.g. type T a b = a
637 type S m = m ()
638 f :: S (T Int)
639 Here, T is partially applied, so it's illegal in H98. But if you
640 expand S first, then T we get just
641 f :: Int
642 which is fine.
643
644 IMPORTANT: suppose T is a type synonym. Then we must do validity
645 checking on an appliation (T ty1 ty2)
646
647 *either* before expansion (i.e. check ty1, ty2)
648 *or* after expansion (i.e. expand T ty1 ty2, and then check)
649 BUT NOT BOTH
650
651 If we do both, we get exponential behaviour!!
652
653 data TIACons1 i r c = c i ::: r c
654 type TIACons2 t x = TIACons1 t (TIACons1 t x)
655 type TIACons3 t x = TIACons2 t (TIACons1 t x)
656 type TIACons4 t x = TIACons2 t (TIACons2 t x)
657 type TIACons7 t x = TIACons4 t (TIACons3 t x)
658
659
660 ************************************************************************
661 * *
662 \subsection{Checking a theta or source type}
663 * *
664 ************************************************************************
665
666 Note [Implicit parameters in instance decls]
667 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
668 Implicit parameters _only_ allowed in type signatures; not in instance
669 decls, superclasses etc. The reason for not allowing implicit params in
670 instances is a bit subtle. If we allowed
671 instance (?x::Int, Eq a) => Foo [a] where ...
672 then when we saw
673 (e :: (?x::Int) => t)
674 it would be unclear how to discharge all the potential uses of the ?x
675 in e. For example, a constraint Foo [Int] might come out of e, and
676 applying the instance decl would show up two uses of ?x. Trac #8912.
677 -}
678
679 checkValidTheta :: UserTypeCtxt -> ThetaType -> TcM ()
680 -- Assumes argument is fully zonked
681 checkValidTheta ctxt theta
682 = do { env <- tcInitOpenTidyEnv (tyCoVarsOfTypesList theta)
683 ; addErrCtxtM (checkThetaCtxt ctxt theta) $
684 check_valid_theta env ctxt theta }
685
686 -------------------------
687 check_valid_theta :: TidyEnv -> UserTypeCtxt -> [PredType] -> TcM ()
688 check_valid_theta _ _ []
689 = return ()
690 check_valid_theta env ctxt theta
691 = do { dflags <- getDynFlags
692 ; warnTcM (Reason Opt_WarnDuplicateConstraints)
693 (wopt Opt_WarnDuplicateConstraints dflags && notNull dups)
694 (dupPredWarn env dups)
695 ; traceTc "check_valid_theta" (ppr theta)
696 ; mapM_ (check_pred_ty env dflags ctxt) theta }
697 where
698 (_,dups) = removeDups nonDetCmpType theta
699 -- It's OK to use nonDetCmpType because dups only appears in the
700 -- warning
701
702 -------------------------
703 {- Note [Validity checking for constraints]
704 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
705 We look through constraint synonyms so that we can see the underlying
706 constraint(s). For example
707 type Foo = ?x::Int
708 instance Foo => C T
709 We should reject the instance because it has an implicit parameter in
710 the context.
711
712 But we record, in 'under_syn', whether we have looked under a synonym
713 to avoid requiring language extensions at the use site. Main example
714 (Trac #9838):
715
716 {-# LANGUAGE ConstraintKinds #-}
717 module A where
718 type EqShow a = (Eq a, Show a)
719
720 module B where
721 import A
722 foo :: EqShow a => a -> String
723
724 We don't want to require ConstraintKinds in module B.
725 -}
726
727 check_pred_ty :: TidyEnv -> DynFlags -> UserTypeCtxt -> PredType -> TcM ()
728 -- Check the validity of a predicate in a signature
729 -- See Note [Validity checking for constraints]
730 check_pred_ty env dflags ctxt pred
731 = do { check_type env SigmaCtxt rank pred
732 ; check_pred_help False env dflags ctxt pred }
733 where
734 rank | xopt LangExt.QuantifiedConstraints dflags
735 = ArbitraryRank
736 | otherwise
737 = constraintMonoType
738
739 check_pred_help :: Bool -- True <=> under a type synonym
740 -> TidyEnv
741 -> DynFlags -> UserTypeCtxt
742 -> PredType -> TcM ()
743 check_pred_help under_syn env dflags ctxt pred
744 | Just pred' <- tcView pred -- Switch on under_syn when going under a
745 -- synonym (Trac #9838, yuk)
746 = check_pred_help True env dflags ctxt pred'
747
748 | otherwise -- A bit like classifyPredType, but not the same
749 -- E.g. we treat (~) like (~#); and we look inside tuples
750 = case splitTyConApp_maybe pred of
751 Just (tc, tys)
752 | isTupleTyCon tc
753 -> check_tuple_pred under_syn env dflags ctxt pred tys
754
755 | tc `hasKey` heqTyConKey ||
756 tc `hasKey` eqTyConKey ||
757 tc `hasKey` eqPrimTyConKey
758 -- NB: this equality check must come first,
759 -- because (~) is a class,too.
760 -> check_eq_pred env dflags pred tc tys
761
762 | Just cls <- tyConClass_maybe tc
763 -- Includes Coercible
764 -> check_class_pred env dflags ctxt pred cls tys
765
766 _ -> check_irred_pred under_syn env dflags ctxt pred
767
768 check_eq_pred :: TidyEnv -> DynFlags -> PredType -> TyCon -> [TcType] -> TcM ()
769 check_eq_pred env dflags pred tc tys
770 = -- Equational constraints are valid in all contexts if type
771 -- families are permitted
772 do { checkTc (tys `lengthIs` tyConArity tc) (tyConArityErr tc tys)
773 ; checkTcM (xopt LangExt.TypeFamilies dflags
774 || xopt LangExt.GADTs dflags)
775 (eqPredTyErr env pred) }
776
777 check_tuple_pred :: Bool -> TidyEnv -> DynFlags -> UserTypeCtxt -> PredType -> [PredType] -> TcM ()
778 check_tuple_pred under_syn env dflags ctxt pred ts
779 = do { -- See Note [ConstraintKinds in predicates]
780 checkTcM (under_syn || xopt LangExt.ConstraintKinds dflags)
781 (predTupleErr env pred)
782 ; mapM_ (check_pred_help under_syn env dflags ctxt) ts }
783 -- This case will not normally be executed because without
784 -- -XConstraintKinds tuple types are only kind-checked as *
785
786 check_irred_pred :: Bool -> TidyEnv -> DynFlags -> UserTypeCtxt -> PredType -> TcM ()
787 check_irred_pred under_syn env dflags ctxt pred
788 -- The predicate looks like (X t1 t2) or (x t1 t2) :: Constraint
789 -- where X is a type function
790 = do { -- If it looks like (x t1 t2), require ConstraintKinds
791 -- see Note [ConstraintKinds in predicates]
792 -- But (X t1 t2) is always ok because we just require ConstraintKinds
793 -- at the definition site (Trac #9838)
794 failIfTcM (not under_syn && not (xopt LangExt.ConstraintKinds dflags)
795 && hasTyVarHead pred)
796 (predIrredErr env pred)
797
798 -- Make sure it is OK to have an irred pred in this context
799 -- See Note [Irreducible predicates in superclasses]
800 ; failIfTcM (is_superclass ctxt
801 && not (xopt LangExt.UndecidableInstances dflags)
802 && has_tyfun_head pred)
803 (predSuperClassErr env pred) }
804 where
805 is_superclass ctxt = case ctxt of { ClassSCCtxt _ -> True; _ -> False }
806 has_tyfun_head ty
807 = case tcSplitTyConApp_maybe ty of
808 Just (tc, _) -> isTypeFamilyTyCon tc
809 Nothing -> False
810
811 {- Note [ConstraintKinds in predicates]
812 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
813 Don't check for -XConstraintKinds under a type synonym, because that
814 was done at the type synonym definition site; see Trac #9838
815 e.g. module A where
816 type C a = (Eq a, Ix a) -- Needs -XConstraintKinds
817 module B where
818 import A
819 f :: C a => a -> a -- Does *not* need -XConstraintKinds
820
821 Note [Irreducible predicates in superclasses]
822 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
823 Allowing type-family calls in class superclasses is somewhat dangerous
824 because we can write:
825
826 type family Fooish x :: * -> Constraint
827 type instance Fooish () = Foo
828 class Fooish () a => Foo a where
829
830 This will cause the constraint simplifier to loop because every time we canonicalise a
831 (Foo a) class constraint we add a (Fooish () a) constraint which will be immediately
832 solved to add+canonicalise another (Foo a) constraint. -}
833
834 -------------------------
835 check_class_pred :: TidyEnv -> DynFlags -> UserTypeCtxt -> PredType -> Class -> [TcType] -> TcM ()
836 check_class_pred env dflags ctxt pred cls tys
837 | isIPClass cls
838 = do { check_arity
839 ; checkTcM (okIPCtxt ctxt) (badIPPred env pred) }
840
841 | otherwise
842 = do { check_arity
843 ; warn_simp <- woptM Opt_WarnSimplifiableClassConstraints
844 ; when warn_simp check_simplifiable_class_constraint
845 ; checkTcM arg_tys_ok (predTyVarErr env pred) }
846 where
847 check_arity = checkTc (tys `lengthIs` classArity cls)
848 (tyConArityErr (classTyCon cls) tys)
849
850 -- Check the arguments of a class constraint
851 flexible_contexts = xopt LangExt.FlexibleContexts dflags
852 undecidable_ok = xopt LangExt.UndecidableInstances dflags
853 arg_tys_ok = case ctxt of
854 SpecInstCtxt -> True -- {-# SPECIALISE instance Eq (T Int) #-} is fine
855 InstDeclCtxt -> checkValidClsArgs (flexible_contexts || undecidable_ok) cls tys
856 -- Further checks on head and theta
857 -- in checkInstTermination
858 _ -> checkValidClsArgs flexible_contexts cls tys
859
860 -- See Note [Simplifiable given constraints]
861 check_simplifiable_class_constraint
862 | xopt LangExt.MonoLocalBinds dflags
863 = return ()
864 | DataTyCtxt {} <- ctxt -- Don't do this check for the "stupid theta"
865 = return () -- of a data type declaration
866 | otherwise
867 = do { envs <- tcGetInstEnvs
868 ; case lookupInstEnv False envs cls tys of
869 ([m], [], _) -> addWarnTc (Reason Opt_WarnSimplifiableClassConstraints)
870 (simplifiable_constraint_warn m)
871 _ -> return () }
872
873 simplifiable_constraint_warn :: InstMatch -> SDoc
874 simplifiable_constraint_warn (match, _)
875 = vcat [ hang (text "The constraint" <+> quotes (ppr (tidyType env pred)))
876 2 (text "matches an instance declaration")
877 , ppr match
878 , hang (text "This makes type inference for inner bindings fragile;")
879 2 (text "either use MonoLocalBinds, or simplify it using the instance") ]
880
881 {- Note [Simplifiable given constraints]
882 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
883 A type signature like
884 f :: Eq [(a,b)] => a -> b
885 is very fragile, for reasons described at length in TcInteract
886 Note [Instance and Given overlap]. As that Note discusses, for the
887 most part the clever stuff in TcInteract means that we don't use a
888 top-level instance if a local Given might fire, so there is no
889 fragility. But if we /infer/ the type of a local let-binding, things
890 can go wrong (Trac #11948 is an example, discussed in the Note).
891
892 So this warning is switched on only if we have NoMonoLocalBinds; in
893 that case the warning discourages users from writing simplifiable
894 class constraints.
895
896 The warning only fires if the constraint in the signature
897 matches the top-level instances in only one way, and with no
898 unifiers -- that is, under the same circumstances that
899 TcInteract.matchInstEnv fires an interaction with the top
900 level instances. For example (Trac #13526), consider
901
902 instance {-# OVERLAPPABLE #-} Eq (T a) where ...
903 instance Eq (T Char) where ..
904 f :: Eq (T a) => ...
905
906 We don't want to complain about this, even though the context
907 (Eq (T a)) matches an instance, because the user may be
908 deliberately deferring the choice so that the Eq (T Char)
909 has a chance to fire when 'f' is called. And the fragility
910 only matters when there's a risk that the instance might
911 fire instead of the local 'given'; and there is no such
912 risk in this case. Just use the same rules as for instance
913 firing!
914 -}
915
916 -------------------------
917 okIPCtxt :: UserTypeCtxt -> Bool
918 -- See Note [Implicit parameters in instance decls]
919 okIPCtxt (FunSigCtxt {}) = True
920 okIPCtxt (InfSigCtxt {}) = True
921 okIPCtxt ExprSigCtxt = True
922 okIPCtxt TypeAppCtxt = True
923 okIPCtxt PatSigCtxt = True
924 okIPCtxt ResSigCtxt = True
925 okIPCtxt GenSigCtxt = True
926 okIPCtxt (ConArgCtxt {}) = True
927 okIPCtxt (ForSigCtxt {}) = True -- ??
928 okIPCtxt ThBrackCtxt = True
929 okIPCtxt GhciCtxt = True
930 okIPCtxt SigmaCtxt = True
931 okIPCtxt (DataTyCtxt {}) = True
932 okIPCtxt (PatSynCtxt {}) = True
933 okIPCtxt (TySynCtxt {}) = True -- e.g. type Blah = ?x::Int
934 -- Trac #11466
935
936 okIPCtxt (KindSigCtxt {}) = False
937 okIPCtxt (ClassSCCtxt {}) = False
938 okIPCtxt (InstDeclCtxt {}) = False
939 okIPCtxt (SpecInstCtxt {}) = False
940 okIPCtxt (RuleSigCtxt {}) = False
941 okIPCtxt DefaultDeclCtxt = False
942 okIPCtxt DerivClauseCtxt = False
943 okIPCtxt (TyVarBndrKindCtxt {}) = False
944 okIPCtxt (DataKindCtxt {}) = False
945 okIPCtxt (TySynKindCtxt {}) = False
946 okIPCtxt (TyFamResKindCtxt {}) = False
947
948 {-
949 Note [Kind polymorphic type classes]
950 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
951 MultiParam check:
952
953 class C f where... -- C :: forall k. k -> Constraint
954 instance C Maybe where...
955
956 The dictionary gets type [C * Maybe] even if it's not a MultiParam
957 type class.
958
959 Flexibility check:
960
961 class C f where... -- C :: forall k. k -> Constraint
962 data D a = D a
963 instance C D where
964
965 The dictionary gets type [C * (D *)]. IA0_TODO it should be
966 generalized actually.
967 -}
968
969 checkThetaCtxt :: UserTypeCtxt -> ThetaType -> TidyEnv -> TcM (TidyEnv, SDoc)
970 checkThetaCtxt ctxt theta env
971 = return ( env
972 , vcat [ text "In the context:" <+> pprTheta (tidyTypes env theta)
973 , text "While checking" <+> pprUserTypeCtxt ctxt ] )
974
975 eqPredTyErr, predTupleErr, predIrredErr, predSuperClassErr :: TidyEnv -> PredType -> (TidyEnv, SDoc)
976 eqPredTyErr env pred
977 = ( env
978 , text "Illegal equational constraint" <+> ppr_tidy env pred $$
979 parens (text "Use GADTs or TypeFamilies to permit this") )
980 predTupleErr env pred
981 = ( env
982 , hang (text "Illegal tuple constraint:" <+> ppr_tidy env pred)
983 2 (parens constraintKindsMsg) )
984 predIrredErr env pred
985 = ( env
986 , hang (text "Illegal constraint:" <+> ppr_tidy env pred)
987 2 (parens constraintKindsMsg) )
988 predSuperClassErr env pred
989 = ( env
990 , hang (text "Illegal constraint" <+> quotes (ppr_tidy env pred)
991 <+> text "in a superclass context")
992 2 (parens undecidableMsg) )
993
994 predTyVarErr :: TidyEnv -> PredType -> (TidyEnv, SDoc)
995 predTyVarErr env pred
996 = (env
997 , vcat [ hang (text "Non type-variable argument")
998 2 (text "in the constraint:" <+> ppr_tidy env pred)
999 , parens (text "Use FlexibleContexts to permit this") ])
1000
1001 badIPPred :: TidyEnv -> PredType -> (TidyEnv, SDoc)
1002 badIPPred env pred
1003 = ( env
1004 , text "Illegal implicit parameter" <+> quotes (ppr_tidy env pred) )
1005
1006 constraintSynErr :: TidyEnv -> Type -> (TidyEnv, SDoc)
1007 constraintSynErr env kind
1008 = ( env
1009 , hang (text "Illegal constraint synonym of kind:" <+> quotes (ppr_tidy env kind))
1010 2 (parens constraintKindsMsg) )
1011
1012 dupPredWarn :: TidyEnv -> [NE.NonEmpty PredType] -> (TidyEnv, SDoc)
1013 dupPredWarn env dups
1014 = ( env
1015 , text "Duplicate constraint" <> plural primaryDups <> text ":"
1016 <+> pprWithCommas (ppr_tidy env) primaryDups )
1017 where
1018 primaryDups = map NE.head dups
1019
1020 tyConArityErr :: TyCon -> [TcType] -> SDoc
1021 -- For type-constructor arity errors, be careful to report
1022 -- the number of /visible/ arguments required and supplied,
1023 -- ignoring the /invisible/ arguments, which the user does not see.
1024 -- (e.g. Trac #10516)
1025 tyConArityErr tc tks
1026 = arityErr (ppr (tyConFlavour tc)) (tyConName tc)
1027 tc_type_arity tc_type_args
1028 where
1029 vis_tks = filterOutInvisibleTypes tc tks
1030
1031 -- tc_type_arity = number of *type* args expected
1032 -- tc_type_args = number of *type* args encountered
1033 tc_type_arity = count isVisibleTyConBinder (tyConBinders tc)
1034 tc_type_args = length vis_tks
1035
1036 arityErr :: Outputable a => SDoc -> a -> Int -> Int -> SDoc
1037 arityErr what name n m
1038 = hsep [ text "The" <+> what, quotes (ppr name), text "should have",
1039 n_arguments <> comma, text "but has been given",
1040 if m==0 then text "none" else int m]
1041 where
1042 n_arguments | n == 0 = text "no arguments"
1043 | n == 1 = text "1 argument"
1044 | True = hsep [int n, text "arguments"]
1045
1046 {-
1047 ************************************************************************
1048 * *
1049 \subsection{Checking for a decent instance head type}
1050 * *
1051 ************************************************************************
1052
1053 @checkValidInstHead@ checks the type {\em and} its syntactic constraints:
1054 it must normally look like: @instance Foo (Tycon a b c ...) ...@
1055
1056 The exceptions to this syntactic checking: (1)~if the @GlasgowExts@
1057 flag is on, or (2)~the instance is imported (they must have been
1058 compiled elsewhere). In these cases, we let them go through anyway.
1059
1060 We can also have instances for functions: @instance Foo (a -> b) ...@.
1061 -}
1062
1063 checkValidInstHead :: UserTypeCtxt -> Class -> [Type] -> TcM ()
1064 checkValidInstHead ctxt clas cls_args
1065 = do { dflags <- getDynFlags
1066
1067 ; mod <- getModule
1068 ; checkTc (getUnique clas `notElem` abstractClassKeys ||
1069 nameModule (getName clas) == mod)
1070 (instTypeErr clas cls_args abstract_class_msg)
1071
1072 ; when (clas `hasKey` hasFieldClassNameKey) $
1073 checkHasFieldInst clas cls_args
1074
1075 -- Check language restrictions;
1076 -- but not for SPECIALISE instance pragmas or deriving clauses
1077 ; let ty_args = filterOutInvisibleTypes (classTyCon clas) cls_args
1078 ; unless (spec_inst_prag || deriv_clause) $
1079 do { checkTc (xopt LangExt.TypeSynonymInstances dflags ||
1080 all tcInstHeadTyNotSynonym ty_args)
1081 (instTypeErr clas cls_args head_type_synonym_msg)
1082 ; checkTc (xopt LangExt.FlexibleInstances dflags ||
1083 all tcInstHeadTyAppAllTyVars ty_args)
1084 (instTypeErr clas cls_args head_type_args_tyvars_msg)
1085 ; checkTc (xopt LangExt.MultiParamTypeClasses dflags ||
1086 lengthIs ty_args 1 || -- Only count type arguments
1087 (xopt LangExt.NullaryTypeClasses dflags &&
1088 null ty_args))
1089 (instTypeErr clas cls_args head_one_type_msg) }
1090
1091 ; mapM_ checkValidTypePat ty_args }
1092 where
1093 spec_inst_prag = case ctxt of { SpecInstCtxt -> True; _ -> False }
1094 deriv_clause = case ctxt of { DerivClauseCtxt -> True; _ -> False }
1095
1096 head_type_synonym_msg = parens (
1097 text "All instance types must be of the form (T t1 ... tn)" $$
1098 text "where T is not a synonym." $$
1099 text "Use TypeSynonymInstances if you want to disable this.")
1100
1101 head_type_args_tyvars_msg = parens (vcat [
1102 text "All instance types must be of the form (T a1 ... an)",
1103 text "where a1 ... an are *distinct type variables*,",
1104 text "and each type variable appears at most once in the instance head.",
1105 text "Use FlexibleInstances if you want to disable this."])
1106
1107 head_one_type_msg = parens (
1108 text "Only one type can be given in an instance head." $$
1109 text "Use MultiParamTypeClasses if you want to allow more, or zero.")
1110
1111 abstract_class_msg =
1112 text "Manual instances of this class are not permitted."
1113
1114 tcInstHeadTyNotSynonym :: Type -> Bool
1115 -- Used in Haskell-98 mode, for the argument types of an instance head
1116 -- These must not be type synonyms, but everywhere else type synonyms
1117 -- are transparent, so we need a special function here
1118 tcInstHeadTyNotSynonym ty
1119 = case ty of -- Do not use splitTyConApp,
1120 -- because that expands synonyms!
1121 TyConApp tc _ -> not (isTypeSynonymTyCon tc)
1122 _ -> True
1123
1124 tcInstHeadTyAppAllTyVars :: Type -> Bool
1125 -- Used in Haskell-98 mode, for the argument types of an instance head
1126 -- These must be a constructor applied to type variable arguments
1127 -- or a type-level literal.
1128 -- But we allow kind instantiations.
1129 tcInstHeadTyAppAllTyVars ty
1130 | Just (tc, tys) <- tcSplitTyConApp_maybe (dropCasts ty)
1131 = ok (filterOutInvisibleTypes tc tys) -- avoid kinds
1132 | LitTy _ <- ty = True -- accept type literals (Trac #13833)
1133 | otherwise
1134 = False
1135 where
1136 -- Check that all the types are type variables,
1137 -- and that each is distinct
1138 ok tys = equalLength tvs tys && hasNoDups tvs
1139 where
1140 tvs = mapMaybe tcGetTyVar_maybe tys
1141
1142 dropCasts :: Type -> Type
1143 -- See Note [Casts during validity checking]
1144 -- This function can turn a well-kinded type into an ill-kinded
1145 -- one, so I've kept it local to this module
1146 -- To consider: drop only HoleCo casts
1147 dropCasts (CastTy ty _) = dropCasts ty
1148 dropCasts (AppTy t1 t2) = mkAppTy (dropCasts t1) (dropCasts t2)
1149 dropCasts (FunTy t1 t2) = mkFunTy (dropCasts t1) (dropCasts t2)
1150 dropCasts (TyConApp tc tys) = mkTyConApp tc (map dropCasts tys)
1151 dropCasts (ForAllTy b ty) = ForAllTy (dropCastsB b) (dropCasts ty)
1152 dropCasts ty = ty -- LitTy, TyVarTy, CoercionTy
1153
1154 dropCastsB :: TyVarBinder -> TyVarBinder
1155 dropCastsB b = b -- Don't bother in the kind of a forall
1156
1157 abstractClassKeys :: [Unique]
1158 abstractClassKeys = [ heqTyConKey
1159 , eqTyConKey
1160 , coercibleTyConKey
1161 ] -- See Note [Equality class instances]
1162
1163 instTypeErr :: Class -> [Type] -> SDoc -> SDoc
1164 instTypeErr cls tys msg
1165 = hang (hang (text "Illegal instance declaration for")
1166 2 (quotes (pprClassPred cls tys)))
1167 2 msg
1168
1169 -- | See Note [Validity checking of HasField instances]
1170 checkHasFieldInst :: Class -> [Type] -> TcM ()
1171 checkHasFieldInst cls tys@[_k_ty, x_ty, r_ty, _a_ty] =
1172 case splitTyConApp_maybe r_ty of
1173 Nothing -> whoops (text "Record data type must be specified")
1174 Just (tc, _)
1175 | isFamilyTyCon tc
1176 -> whoops (text "Record data type may not be a data family")
1177 | otherwise -> case isStrLitTy x_ty of
1178 Just lbl
1179 | isJust (lookupTyConFieldLabel lbl tc)
1180 -> whoops (ppr tc <+> text "already has a field"
1181 <+> quotes (ppr lbl))
1182 | otherwise -> return ()
1183 Nothing
1184 | null (tyConFieldLabels tc) -> return ()
1185 | otherwise -> whoops (ppr tc <+> text "has fields")
1186 where
1187 whoops = addErrTc . instTypeErr cls tys
1188 checkHasFieldInst _ tys = pprPanic "checkHasFieldInst" (ppr tys)
1189
1190 {- Note [Casts during validity checking]
1191 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1192 Consider the (bogus)
1193 instance Eq Char#
1194 We elaborate to 'Eq (Char# |> UnivCo(hole))' where the hole is an
1195 insoluble equality constraint for * ~ #. We'll report the insoluble
1196 constraint separately, but we don't want to *also* complain that Eq is
1197 not applied to a type constructor. So we look gaily look through
1198 CastTys here.
1199
1200 Another example: Eq (Either a). Then we actually get a cast in
1201 the middle:
1202 Eq ((Either |> g) a)
1203
1204
1205 Note [Validity checking of HasField instances]
1206 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1207 The HasField class has magic constraint solving behaviour (see Note
1208 [HasField instances] in TcInteract). However, we permit users to
1209 declare their own instances, provided they do not clash with the
1210 built-in behaviour. In particular, we forbid:
1211
1212 1. `HasField _ r _` where r is a variable
1213
1214 2. `HasField _ (T ...) _` if T is a data family
1215 (because it might have fields introduced later)
1216
1217 3. `HasField x (T ...) _` where x is a variable,
1218 if T has any fields at all
1219
1220 4. `HasField "foo" (T ...) _` if T has a "foo" field
1221
1222 The usual functional dependency checks also apply.
1223
1224
1225 Note [Valid 'deriving' predicate]
1226 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1227 validDerivPred checks for OK 'deriving' context. See Note [Exotic
1228 derived instance contexts] in TcDeriv. However the predicate is
1229 here because it uses sizeTypes, fvTypes.
1230
1231 It checks for three things
1232
1233 * No repeated variables (hasNoDups fvs)
1234
1235 * No type constructors. This is done by comparing
1236 sizeTypes tys == length (fvTypes tys)
1237 sizeTypes counts variables and constructors; fvTypes returns variables.
1238 So if they are the same, there must be no constructors. But there
1239 might be applications thus (f (g x)).
1240
1241 Note that tys only includes the visible arguments of the class type
1242 constructor. Including the non-visible arguments can cause the following,
1243 perfectly valid instance to be rejected:
1244 class Category (cat :: k -> k -> *) where ...
1245 newtype T (c :: * -> * -> *) a b = MkT (c a b)
1246 instance Category c => Category (T c) where ...
1247 since the first argument to Category is a non-visible *, which sizeTypes
1248 would count as a constructor! See Trac #11833.
1249
1250 * Also check for a bizarre corner case, when the derived instance decl
1251 would look like
1252 instance C a b => D (T a) where ...
1253 Note that 'b' isn't a parameter of T. This gives rise to all sorts of
1254 problems; in particular, it's hard to compare solutions for equality
1255 when finding the fixpoint, and that means the inferContext loop does
1256 not converge. See Trac #5287.
1257
1258 Note [Equality class instances]
1259 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1260 We can't have users writing instances for the equality classes. But we
1261 still need to be able to write instances for them ourselves. So we allow
1262 instances only in the defining module.
1263
1264 -}
1265
1266 validDerivPred :: TyVarSet -> PredType -> Bool
1267 -- See Note [Valid 'deriving' predicate]
1268 validDerivPred tv_set pred
1269 = case classifyPredType pred of
1270 ClassPred cls tys -> cls `hasKey` typeableClassKey
1271 -- Typeable constraints are bigger than they appear due
1272 -- to kind polymorphism, but that's OK
1273 || check_tys cls tys
1274 EqPred {} -> False -- reject equality constraints
1275 _ -> True -- Non-class predicates are ok
1276 where
1277 check_tys cls tys
1278 = hasNoDups fvs
1279 -- use sizePred to ignore implicit args
1280 && lengthIs fvs (sizePred pred)
1281 && all (`elemVarSet` tv_set) fvs
1282 where tys' = filterOutInvisibleTypes (classTyCon cls) tys
1283 fvs = fvTypes tys'
1284
1285 {-
1286 ************************************************************************
1287 * *
1288 \subsection{Checking instance for termination}
1289 * *
1290 ************************************************************************
1291 -}
1292
1293 {- Note [Instances and constraint synonyms]
1294 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1295 Currently, we don't allow instances for constraint synonyms at all.
1296 Consider these (Trac #13267):
1297 type C1 a = Show (a -> Bool)
1298 instance C1 Int where -- I1
1299 show _ = "ur"
1300
1301 This elicits "show is not a (visible) method of class C1", which isn't
1302 a great message. But it comes from the renamer, so it's hard to improve.
1303
1304 This needs a bit more care:
1305 type C2 a = (Show a, Show Int)
1306 instance C2 Int -- I2
1307
1308 If we use (splitTyConApp_maybe tau) in checkValidInstance to decompose
1309 the instance head, we'll expand the synonym on fly, and it'll look like
1310 instance (%,%) (Show Int, Show Int)
1311 and we /really/ don't want that. So we carefully do /not/ expand
1312 synonyms, by matching on TyConApp directly.
1313 -}
1314
1315 checkValidInstance :: UserTypeCtxt -> LHsSigType GhcRn -> Type
1316 -> TcM ([TyVar], ThetaType, Class, [Type])
1317 checkValidInstance ctxt hs_type ty
1318 | not is_tc_app
1319 = failWithTc (hang (text "Instance head is not headed by a class:")
1320 2 ( ppr tau))
1321
1322 | isNothing mb_cls
1323 = failWithTc (vcat [ text "Illegal instance for a" <+> ppr (tyConFlavour tc)
1324 , text "A class instance must be for a class" ])
1325
1326 | not arity_ok
1327 = failWithTc (text "Arity mis-match in instance head")
1328
1329 | otherwise
1330 = do { setSrcSpan head_loc (checkValidInstHead ctxt clas inst_tys)
1331 ; traceTc "checkValidInstance {" (ppr ty)
1332 ; checkValidTheta ctxt theta
1333
1334 -- The Termination and Coverate Conditions
1335 -- Check that instance inference will terminate (if we care)
1336 -- For Haskell 98 this will already have been done by checkValidTheta,
1337 -- but as we may be using other extensions we need to check.
1338 --
1339 -- Note that the Termination Condition is *more conservative* than
1340 -- the checkAmbiguity test we do on other type signatures
1341 -- e.g. Bar a => Bar Int is ambiguous, but it also fails
1342 -- the termination condition, because 'a' appears more often
1343 -- in the constraint than in the head
1344 ; undecidable_ok <- xoptM LangExt.UndecidableInstances
1345 ; if undecidable_ok
1346 then checkAmbiguity ctxt ty
1347 else checkInstTermination theta tau
1348
1349 ; traceTc "cvi 2" (ppr ty)
1350
1351 ; case (checkInstCoverage undecidable_ok clas theta inst_tys) of
1352 IsValid -> return () -- Check succeeded
1353 NotValid msg -> addErrTc (instTypeErr clas inst_tys msg)
1354
1355 ; traceTc "End checkValidInstance }" empty
1356
1357 ; return (tvs, theta, clas, inst_tys) }
1358 where
1359 (tvs, theta, tau) = tcSplitSigmaTy ty
1360 is_tc_app = case tau of { TyConApp {} -> True; _ -> False }
1361 TyConApp tc inst_tys = tau -- See Note [Instances and constraint synonyms]
1362 mb_cls = tyConClass_maybe tc
1363 Just clas = mb_cls
1364 arity_ok = inst_tys `lengthIs` classArity clas
1365
1366 -- The location of the "head" of the instance
1367 head_loc = getLoc (getLHsInstDeclHead hs_type)
1368
1369 {-
1370 Note [Paterson conditions]
1371 ~~~~~~~~~~~~~~~~~~~~~~~~~~
1372 Termination test: the so-called "Paterson conditions" (see Section 5 of
1373 "Understanding functional dependencies via Constraint Handling Rules,
1374 JFP Jan 2007).
1375
1376 We check that each assertion in the context satisfies:
1377 (1) no variable has more occurrences in the assertion than in the head, and
1378 (2) the assertion has fewer constructors and variables (taken together
1379 and counting repetitions) than the head.
1380 This is only needed with -fglasgow-exts, as Haskell 98 restrictions
1381 (which have already been checked) guarantee termination.
1382
1383 The underlying idea is that
1384
1385 for any ground substitution, each assertion in the
1386 context has fewer type constructors than the head.
1387 -}
1388
1389 checkInstTermination :: ThetaType -> TcPredType -> TcM ()
1390 -- See Note [Paterson conditions]
1391 checkInstTermination theta head_pred
1392 = check_preds emptyVarSet theta
1393 where
1394 head_fvs = fvType head_pred
1395 head_size = sizeType head_pred
1396
1397 check_preds :: VarSet -> [PredType] -> TcM ()
1398 check_preds foralld_tvs preds = mapM_ (check foralld_tvs) preds
1399
1400 check :: VarSet -> PredType -> TcM ()
1401 check foralld_tvs pred
1402 = case classifyPredType pred of
1403 EqPred {} -> return () -- See Trac #4200.
1404 IrredPred {} -> check2 foralld_tvs pred (sizeType pred)
1405 ClassPred cls tys
1406 | isTerminatingClass cls
1407 -> return ()
1408
1409 | isCTupleClass cls -- Look inside tuple predicates; Trac #8359
1410 -> check_preds foralld_tvs tys
1411
1412 | otherwise -- Other ClassPreds
1413 -> check2 foralld_tvs pred bogus_size
1414 where
1415 bogus_size = 1 + sizeTypes (filterOutInvisibleTypes (classTyCon cls) tys)
1416 -- See Note [Invisible arguments and termination]
1417
1418 ForAllPred tvs theta' head_pred'
1419 -> do { check (foralld_tvs `extendVarSetList` binderVars tvs) head_pred'
1420 ; addErrCtxt (text "In the quantified constraint"
1421 <+> quotes (ppr pred)) $
1422 checkInstTermination theta' head_pred' }
1423
1424 check2 foralld_tvs pred pred_size
1425 | not (null bad_tvs) = addErrTc (noMoreMsg bad_tvs what (ppr head_pred))
1426 | not (isTyFamFree pred) = addErrTc (nestedMsg what)
1427 | pred_size >= head_size = addErrTc (smallerMsg what (ppr head_pred))
1428 | otherwise = return ()
1429 -- isTyFamFree: see Note [Type families in instance contexts]
1430 where
1431 what = text "constraint" <+> quotes (ppr pred)
1432 bad_tvs = filterOut (`elemVarSet` foralld_tvs) (fvType pred)
1433 \\ head_fvs
1434
1435 smallerMsg :: SDoc -> SDoc -> SDoc
1436 smallerMsg what inst_head
1437 = vcat [ hang (text "The" <+> what)
1438 2 (sep [ text "is no smaller than"
1439 , text "the instance head" <+> quotes inst_head ])
1440 , parens undecidableMsg ]
1441
1442 noMoreMsg :: [TcTyVar] -> SDoc -> SDoc -> SDoc
1443 noMoreMsg tvs what inst_head
1444 = vcat [ hang (text "Variable" <> plural tvs <+> quotes (pprWithCommas ppr tvs)
1445 <+> occurs <+> text "more often")
1446 2 (sep [ text "in the" <+> what
1447 , text "than in the instance head" <+> quotes inst_head ])
1448 , parens undecidableMsg ]
1449 where
1450 occurs = if isSingleton tvs then text "occurs"
1451 else text "occur"
1452
1453 undecidableMsg, constraintKindsMsg :: SDoc
1454 undecidableMsg = text "Use UndecidableInstances to permit this"
1455 constraintKindsMsg = text "Use ConstraintKinds to permit this"
1456
1457 {- Note [Type families in instance contexts]
1458 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1459 Are these OK?
1460 type family F a
1461 instance F a => C (Maybe [a]) where ...
1462 intance C (F a) => C [[[a]]] where ...
1463
1464 No: the type family in the instance head might blow up to an
1465 arbitrarily large type, depending on how 'a' is instantiated.
1466 So we require UndecidableInstances if we have a type family
1467 in the instance head. Trac #15172.
1468
1469 Note [Associated type instances]
1470 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1471 We allow this:
1472 class C a where
1473 type T x a
1474 instance C Int where
1475 type T (S y) Int = y
1476 type T Z Int = Char
1477
1478 Note that
1479 a) The variable 'x' is not bound by the class decl
1480 b) 'x' is instantiated to a non-type-variable in the instance
1481 c) There are several type instance decls for T in the instance
1482
1483 All this is fine. Of course, you can't give any *more* instances
1484 for (T ty Int) elsewhere, because it's an *associated* type.
1485
1486 Note [Checking consistent instantiation]
1487 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1488 See Trac #11450 for background discussion on this check.
1489
1490 class C a b where
1491 type T a x b
1492
1493 With this class decl, if we have an instance decl
1494 instance C ty1 ty2 where ...
1495 then the type instance must look like
1496 type T ty1 v ty2 = ...
1497 with exactly 'ty1' for 'a', 'ty2' for 'b', and some type 'v' for 'x'.
1498 For example:
1499
1500 instance C [p] Int
1501 type T [p] y Int = (p,y,y)
1502
1503 Note that
1504
1505 * We used to allow completely different bound variables in the
1506 associated type instance; e.g.
1507 instance C [p] Int
1508 type T [q] y Int = ...
1509 But from GHC 8.2 onwards, we don't. It's much simpler this way.
1510 See Trac #11450.
1511
1512 * When the class variable isn't used on the RHS of the type instance,
1513 it's tempting to allow wildcards, thus
1514 instance C [p] Int
1515 type T [_] y Int = (y,y)
1516 But it's awkward to do the test, and it doesn't work if the
1517 variable is repeated:
1518 instance C (p,p) Int
1519 type T (_,_) y Int = (y,y)
1520 Even though 'p' is not used on the RHS, we still need to use 'p'
1521 on the LHS to establish the repeated pattern. So to keep it simple
1522 we just require equality.
1523
1524 * For variables in associated type families that are not bound by the class
1525 itself, we do _not_ check if they are over-specific. In other words,
1526 it's perfectly acceptable to have an instance like this:
1527
1528 instance C [p] Int where
1529 type T [p] (Maybe x) Int = x
1530
1531 While the first and third arguments to T are required to be exactly [p] and
1532 Int, respectively, since they are bound by C, the second argument is allowed
1533 to be more specific than just a type variable. Furthermore, it is permissible
1534 to define multiple equations for T that differ only in the non-class-bound
1535 argument:
1536
1537 instance C [p] Int where
1538 type T [p] (Maybe x) Int = x
1539 type T [p] (Either x y) Int = x -> y
1540
1541 We once considered requiring that non-class-bound variables in associated
1542 type family instances be instantiated with distinct type variables. However,
1543 that requirement proved too restrictive in practice, as there were examples
1544 of extremely simple associated type family instances that this check would
1545 reject, and fixing them required tiresome boilerplate in the form of
1546 auxiliary type families. For instance, you would have to define the above
1547 example as:
1548
1549 instance C [p] Int where
1550 type T [p] x Int = CAux x
1551
1552 type family CAux x where
1553 CAux (Maybe x) = x
1554 CAux (Either x y) = x -> y
1555
1556 We decided that this restriction wasn't buying us much, so we opted not
1557 to pursue that design (see also GHC Trac #13398).
1558
1559 Implementation
1560 * Form the mini-envt from the class type variables a,b
1561 to the instance decl types [p],Int: [a->[p], b->Int]
1562
1563 * Look at the tyvars a,x,b of the type family constructor T
1564 (it shares tyvars with the class C)
1565
1566 * Apply the mini-evnt to them, and check that the result is
1567 consistent with the instance types [p] y Int. (where y can be any type, as
1568 it is not scoped over the class type variables.
1569
1570 We make all the instance type variables scope over the
1571 type instances, of course, which picks up non-obvious kinds. Eg
1572 class Foo (a :: k) where
1573 type F a
1574 instance Foo (b :: k -> k) where
1575 type F b = Int
1576 Here the instance is kind-indexed and really looks like
1577 type F (k->k) (b::k->k) = Int
1578 But if the 'b' didn't scope, we would make F's instance too
1579 poly-kinded.
1580
1581 Note [Invisible arguments and termination]
1582 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1583 When checking the ​Paterson conditions for termination an instance
1584 declaration, we check for the number of "constructors and variables"
1585 in the instance head and constraints. Question: Do we look at
1586
1587 * All the arguments, visible or invisible?
1588 * Just the visible arguments?
1589
1590 I think both will ensure termination, provided we are consistent.
1591 Currently we are /not/ consistent, which is really a bug. It's
1592 described in Trac #15177, which contains a number of examples.
1593 The suspicious bits are the calls to filterOutInvisibleTypes.
1594 -}
1595
1596 -- | Extra information about the parent instance declaration, needed
1597 -- when type-checking associated types. The 'Class' is the enclosing
1598 -- class, the [TyVar] are the type variable of the instance decl,
1599 -- and and the @VarEnv Type@ maps class variables to their instance
1600 -- types.
1601 type ClsInstInfo = (Class, [TyVar], VarEnv Type)
1602
1603 type AssocInstArgShape = (Maybe Type, Type)
1604 -- AssocInstArgShape is used only for associated family instances
1605 -- (mb_exp, actual)
1606 -- mb_exp = Just ty => this arg corresponds to a class variable
1607 -- = Nothing => it doesn't correspond to a class variable
1608 -- e.g. class C b where
1609 -- type F a b c
1610 -- instance C [x] where
1611 -- type F p [x] q
1612 -- We get [AssocInstArgShape] = [ (Nothing, p)
1613 -- , (Just [x], [x])
1614 -- , (Nothing, q)]
1615
1616 checkConsistentFamInst
1617 :: Maybe ClsInstInfo
1618 -> TyCon -- ^ Family tycon
1619 -> [Type] -- ^ Type patterns from instance
1620 -> SDoc -- ^ pretty-printed user-written instance head
1621 -> TcM ()
1622 -- See Note [Checking consistent instantiation]
1623
1624 checkConsistentFamInst Nothing _ _ _ = return ()
1625 checkConsistentFamInst (Just (clas, inst_tvs, mini_env)) fam_tc at_tys pp_hs_pats
1626 = do { -- Check that the associated type indeed comes from this class
1627 -- See [Mismatched class methods and associated type families]
1628 -- in TcInstDecls.
1629 checkTc (Just clas == tyConAssoc_maybe fam_tc)
1630 (badATErr (className clas) (tyConName fam_tc))
1631
1632 -- Check type args first (more comprehensible)
1633 ; checkTc (all check_arg type_shapes) pp_wrong_at_arg
1634
1635 -- And now kind args
1636 ; checkTcM (all check_arg kind_shapes)
1637 (tidy_env2, pp_wrong_at_arg $$ ppSuggestExplicitKinds)
1638
1639 ; traceTc "cfi" (vcat [ ppr inst_tvs
1640 , ppr arg_shapes
1641 , ppr mini_env ]) }
1642 where
1643 arg_shapes :: [AssocInstArgShape]
1644 arg_shapes = [ (lookupVarEnv mini_env fam_tc_tv, at_ty)
1645 | (fam_tc_tv, at_ty) <- tyConTyVars fam_tc `zip` at_tys ]
1646
1647 (kind_shapes, type_shapes) = partitionInvisibles fam_tc snd arg_shapes
1648
1649 check_arg :: AssocInstArgShape -> Bool
1650 check_arg (Just exp_ty, at_ty) = exp_ty `tcEqType` at_ty
1651 check_arg (Nothing, _ ) = True -- Arg position does not correspond
1652 -- to a class variable
1653
1654 pp_wrong_at_arg
1655 = vcat [ text "Type indexes must match class instance head"
1656 , pp_exp_act ]
1657
1658 pp_exp_act
1659 = vcat [ text "Expected:" <+> ppr (mkTyConApp fam_tc expected_args)
1660 , text " Actual:" <+> pp_hs_pats
1661 , sdocWithDynFlags $ \dflags ->
1662 ppWhen (has_poly_args dflags) $
1663 vcat [ text "where the `<tv>' arguments are type variables,"
1664 , text "distinct from each other and from the instance variables" ] ]
1665
1666 -- We need to tidy, since it's possible that expected_args will contain
1667 -- inferred kind variables with names identical to those in at_tys. If we
1668 -- don't, we'll end up with horrible messages like this one (#13972):
1669 --
1670 -- Expected: T (a -> Either a b)
1671 -- Actual: T (a -> Either a b)
1672 (tidy_env1, _) = tidyOpenTypes emptyTidyEnv at_tys
1673 (tidy_env2, expected_args)
1674 = tidyOpenTypes tidy_env1 [ exp_ty `orElse` mk_tv at_ty
1675 | (exp_ty, at_ty) <- arg_shapes ]
1676 mk_tv at_ty = mkTyVarTy (mkTyVar tv_name (typeKind at_ty))
1677 tv_name = mkInternalName (mkAlphaTyVarUnique 1) (mkTyVarOcc "<tv>") noSrcSpan
1678
1679 has_poly_args dflags = any (isNothing . fst) shapes
1680 where
1681 shapes | gopt Opt_PrintExplicitKinds dflags = arg_shapes
1682 | otherwise = type_shapes
1683
1684 badATErr :: Name -> Name -> SDoc
1685 badATErr clas op
1686 = hsep [text "Class", quotes (ppr clas),
1687 text "does not have an associated type", quotes (ppr op)]
1688
1689
1690 {-
1691 ************************************************************************
1692 * *
1693 Checking type instance well-formedness and termination
1694 * *
1695 ************************************************************************
1696 -}
1697
1698 checkValidCoAxiom :: CoAxiom Branched -> TcM ()
1699 checkValidCoAxiom ax@(CoAxiom { co_ax_tc = fam_tc, co_ax_branches = branches })
1700 = do { mapM_ (checkValidCoAxBranch Nothing fam_tc) branch_list
1701 ; foldlM_ check_branch_compat [] branch_list }
1702 where
1703 branch_list = fromBranches branches
1704 injectivity = tyConInjectivityInfo fam_tc
1705
1706 check_branch_compat :: [CoAxBranch] -- previous branches in reverse order
1707 -> CoAxBranch -- current branch
1708 -> TcM [CoAxBranch]-- current branch : previous branches
1709 -- Check for
1710 -- (a) this branch is dominated by previous ones
1711 -- (b) failure of injectivity
1712 check_branch_compat prev_branches cur_branch
1713 | cur_branch `isDominatedBy` prev_branches
1714 = do { addWarnAt NoReason (coAxBranchSpan cur_branch) $
1715 inaccessibleCoAxBranch ax cur_branch
1716 ; return prev_branches }
1717 | otherwise
1718 = do { check_injectivity prev_branches cur_branch
1719 ; return (cur_branch : prev_branches) }
1720
1721 -- Injectivity check: check whether a new (CoAxBranch) can extend
1722 -- already checked equations without violating injectivity
1723 -- annotation supplied by the user.
1724 -- See Note [Verifying injectivity annotation] in FamInstEnv
1725 check_injectivity prev_branches cur_branch
1726 | Injective inj <- injectivity
1727 = do { let conflicts =
1728 fst $ foldl (gather_conflicts inj prev_branches cur_branch)
1729 ([], 0) prev_branches
1730 ; mapM_ (\(err, span) -> setSrcSpan span $ addErr err)
1731 (makeInjectivityErrors ax cur_branch inj conflicts) }
1732 | otherwise
1733 = return ()
1734
1735 gather_conflicts inj prev_branches cur_branch (acc, n) branch
1736 -- n is 0-based index of branch in prev_branches
1737 = case injectiveBranches inj cur_branch branch of
1738 InjectivityUnified ax1 ax2
1739 | ax1 `isDominatedBy` (replace_br prev_branches n ax2)
1740 -> (acc, n + 1)
1741 | otherwise
1742 -> (branch : acc, n + 1)
1743 InjectivityAccepted -> (acc, n + 1)
1744
1745 -- Replace n-th element in the list. Assumes 0-based indexing.
1746 replace_br :: [CoAxBranch] -> Int -> CoAxBranch -> [CoAxBranch]
1747 replace_br brs n br = take n brs ++ [br] ++ drop (n+1) brs
1748
1749
1750 -- Check that a "type instance" is well-formed (which includes decidability
1751 -- unless -XUndecidableInstances is given).
1752 --
1753 checkValidCoAxBranch :: Maybe ClsInstInfo
1754 -> TyCon -> CoAxBranch -> TcM ()
1755 checkValidCoAxBranch mb_clsinfo fam_tc
1756 (CoAxBranch { cab_tvs = tvs, cab_cvs = cvs
1757 , cab_lhs = typats
1758 , cab_rhs = rhs, cab_loc = loc })
1759 = checkValidTyFamEqn mb_clsinfo fam_tc tvs cvs typats rhs pp_lhs loc
1760 where
1761 pp_lhs = ppr (mkTyConApp fam_tc typats)
1762
1763 -- | Do validity checks on a type family equation, including consistency
1764 -- with any enclosing class instance head, termination, and lack of
1765 -- polytypes.
1766 checkValidTyFamEqn :: Maybe ClsInstInfo
1767 -> TyCon -- ^ of the type family
1768 -> [TyVar] -- ^ bound tyvars in the equation
1769 -> [CoVar] -- ^ bound covars in the equation
1770 -> [Type] -- ^ type patterns
1771 -> Type -- ^ rhs
1772 -> SDoc -- ^ user-written LHS
1773 -> SrcSpan
1774 -> TcM ()
1775 checkValidTyFamEqn mb_clsinfo fam_tc tvs cvs typats rhs pp_lhs loc
1776 = setSrcSpan loc $
1777 do { checkValidFamPats mb_clsinfo fam_tc tvs cvs typats [] pp_lhs
1778
1779 -- The argument patterns, and RHS, are all boxed tau types
1780 -- E.g Reject type family F (a :: k1) :: k2
1781 -- type instance F (forall a. a->a) = ...
1782 -- type instance F Int# = ...
1783 -- type instance F Int = forall a. a->a
1784 -- type instance F Int = Int#
1785 -- See Trac #9357
1786 ; checkValidMonoType rhs
1787
1788 -- We have a decidable instance unless otherwise permitted
1789 ; undecidable_ok <- xoptM LangExt.UndecidableInstances
1790 ; traceTc "checkVTFE" (pp_lhs $$ ppr rhs $$ ppr (tcTyFamInsts rhs))
1791 ; unless undecidable_ok $
1792 mapM_ addErrTc (checkFamInstRhs fam_tc typats (tcTyFamInsts rhs)) }
1793
1794 -- Make sure that each type family application is
1795 -- (1) strictly smaller than the lhs,
1796 -- (2) mentions no type variable more often than the lhs, and
1797 -- (3) does not contain any further type family instances.
1798 --
1799 checkFamInstRhs :: TyCon -> [Type] -- LHS
1800 -> [(TyCon, [Type])] -- type family calls in RHS
1801 -> [MsgDoc]
1802 checkFamInstRhs tc lhsTys famInsts
1803 = mapMaybe check famInsts
1804 where
1805 lhs_size = sizeTyConAppArgs tc lhsTys
1806 fvs = fvTypes lhsTys
1807 check (tc, tys)
1808 | not (all isTyFamFree tys) = Just (nestedMsg what)
1809 | not (null bad_tvs) = Just (noMoreMsg bad_tvs what inst_head)
1810 | lhs_size <= fam_app_size = Just (smallerMsg what inst_head)
1811 | otherwise = Nothing
1812 where
1813 what = text "type family application"
1814 <+> quotes (pprType (TyConApp tc tys))
1815 inst_head = pprType (TyConApp tc lhsTys)
1816 bad_tvs = fvTypes tys \\ fvs
1817 fam_app_size = sizeTyConAppArgs tc tys
1818
1819 checkValidFamPats :: Maybe ClsInstInfo -> TyCon -> [TyVar] -> [CoVar]
1820 -> [Type] -- ^ patterns the user wrote
1821 -> [Type] -- ^ "extra" patterns from a data instance kind sig
1822 -> SDoc -- ^ pretty-printed user-written instance head
1823 -> TcM ()
1824 -- Patterns in a 'type instance' or 'data instance' decl should
1825 -- a) contain no type family applications
1826 -- (vanilla synonyms are fine, though)
1827 -- b) properly bind all their free type variables
1828 -- e.g. we disallow (Trac #7536)
1829 -- type T a = Int
1830 -- type instance F (T a) = a
1831 -- c) For associated types, are consistently instantiated
1832 checkValidFamPats mb_clsinfo fam_tc tvs cvs user_ty_pats extra_ty_pats pp_hs_pats
1833 = do { mapM_ checkValidTypePat user_ty_pats
1834
1835 ; let unbound_tcvs = filterOut (`elemVarSet` exactTyCoVarsOfTypes user_ty_pats)
1836 (tvs ++ cvs)
1837 ; checkTc (null unbound_tcvs) (famPatErr fam_tc unbound_tcvs user_ty_pats)
1838
1839 -- Check that type patterns match the class instance head
1840 ; checkConsistentFamInst mb_clsinfo fam_tc (user_ty_pats `chkAppend` extra_ty_pats) pp_hs_pats }
1841
1842 checkValidTypePat :: Type -> TcM ()
1843 -- Used for type patterns in class instances,
1844 -- and in type/data family instances
1845 checkValidTypePat pat_ty
1846 = do { -- Check that pat_ty is a monotype
1847 checkValidMonoType pat_ty
1848 -- One could imagine generalising to allow
1849 -- instance C (forall a. a->a)
1850 -- but we don't know what all the consequences might be
1851
1852 -- Ensure that no type family instances occur a type pattern
1853 ; checkTc (isTyFamFree pat_ty) $
1854 tyFamInstIllegalErr pat_ty }
1855
1856 -- Error messages
1857
1858 inaccessibleCoAxBranch :: CoAxiom br -> CoAxBranch -> SDoc
1859 inaccessibleCoAxBranch fi_ax cur_branch
1860 = text "Type family instance equation is overlapped:" $$
1861 nest 2 (pprCoAxBranch fi_ax cur_branch)
1862
1863 tyFamInstIllegalErr :: Type -> SDoc
1864 tyFamInstIllegalErr ty
1865 = hang (text "Illegal type synonym family application in instance" <>
1866 colon) 2 $
1867 ppr ty
1868
1869 nestedMsg :: SDoc -> SDoc
1870 nestedMsg what
1871 = sep [ text "Illegal nested" <+> what
1872 , parens undecidableMsg ]
1873
1874 famPatErr :: TyCon -> [TyVar] -> [Type] -> SDoc
1875 famPatErr fam_tc tvs pats
1876 = hang (text "Family instance purports to bind type variable" <> plural tvs
1877 <+> pprQuotedList tvs)
1878 2 (hang (text "but the real LHS (expanding synonyms) is:")
1879 2 (pprTypeApp fam_tc (map expandTypeSynonyms pats) <+>
1880 text "= ..."))
1881
1882 {-
1883 ************************************************************************
1884 * *
1885 Telescope checking
1886 * *
1887 ************************************************************************
1888
1889 Note [Bad telescopes]
1890 ~~~~~~~~~~~~~~~~~~~~~
1891 Now that we can mix type and kind variables, there are an awful lot of
1892 ways to shoot yourself in the foot. Here are some.
1893
1894 data SameKind :: k -> k -> * -- just to force unification
1895
1896 1. data T1 a k (b :: k) (x :: SameKind a b)
1897
1898 The problem here is that we discover that a and b should have the same
1899 kind. But this kind mentions k, which is bound *after* a.
1900 (Testcase: dependent/should_fail/BadTelescope)
1901
1902 2. data T2 a (c :: Proxy b) (d :: Proxy a) (x :: SameKind b d)
1903
1904 Note that b is not bound. Yet its kind mentions a. Because we have
1905 a nice rule that all implicitly bound variables come before others,
1906 this is bogus. (We could probably figure out to put b between a and c.
1907 But I think this is doing users a disservice, in the long run.)
1908 (Testcase: dependent/should_fail/BadTelescope4)
1909
1910 To catch these errors, we call checkValidTelescope during kind-checking
1911 datatype declarations. This must be done *before* kind-generalization,
1912 because kind-generalization might observe, say, T1, see that k is free
1913 in a's kind, and generalize over it, producing nonsense. It also must
1914 be done *after* kind-generalization, in order to catch the T2 case, which
1915 becomes apparent only after generalizing.
1916
1917 Note [Keeping scoped variables in order: Explicit] discusses how this
1918 check works for `forall x y z.` written in a type.
1919
1920 -}
1921
1922 -- | Check a list of binders to see if they make a valid telescope.
1923 -- The key property we're checking for is scoping. For example:
1924 -- > data SameKind :: k -> k -> *
1925 -- > data X a k (b :: k) (c :: SameKind a b)
1926 -- Kind inference says that a's kind should be k. But that's impossible,
1927 -- because k isn't in scope when a is bound. This check has to come before
1928 -- general validity checking, because once we kind-generalise, this sort
1929 -- of problem is harder to spot (as we'll generalise over the unbound
1930 -- k in a's type.) See also Note [Bad telescopes].
1931 checkValidTelescope :: [TyConBinder] -- explicit vars (zonked)
1932 -> SDoc -- original, user-written telescope
1933 -> SDoc -- extra text to print
1934 -> TcM ()
1935 checkValidTelescope tvbs user_tyvars extra
1936 = do { let tvs = binderVars tvbs
1937
1938 (_, sorted_tidied_tvs) = tidyTyCoVarBndrs emptyTidyEnv $
1939 toposortTyVars tvs
1940 ; unless (go [] emptyVarSet (binderVars tvbs)) $
1941 addErr $
1942 vcat [ hang (text "These kind and type variables:" <+> user_tyvars $$
1943 text "are out of dependency order. Perhaps try this ordering:")
1944 2 (pprTyVars sorted_tidied_tvs)
1945 , extra ] }
1946
1947 where
1948 go :: [TyVar] -- misplaced variables
1949 -> TyVarSet -> [TyVar] -> Bool
1950 go errs in_scope [] = null (filter (`elemVarSet` in_scope) errs)
1951 -- report an error only when the variable in the kind is brought
1952 -- into scope later in the telescope. Otherwise, we'll just quantify
1953 -- over it in kindGeneralize, as we should.
1954
1955 go errs in_scope (tv:tvs)
1956 = let bad_tvs = filterOut (`elemVarSet` in_scope) $
1957 tyCoVarsOfTypeList (tyVarKind tv)
1958 in go (bad_tvs ++ errs) (in_scope `extendVarSet` tv) tvs
1959
1960 {-
1961 ************************************************************************
1962 * *
1963 \subsection{Auxiliary functions}
1964 * *
1965 ************************************************************************
1966 -}
1967
1968 -- Free variables of a type, retaining repetitions, and expanding synonyms
1969 fvType :: Type -> [TyCoVar]
1970 fvType ty | Just exp_ty <- tcView ty = fvType exp_ty
1971 fvType (TyVarTy tv) = [tv]
1972 fvType (TyConApp _ tys) = fvTypes tys
1973 fvType (LitTy {}) = []
1974 fvType (AppTy fun arg) = fvType fun ++ fvType arg
1975 fvType (FunTy arg res) = fvType arg ++ fvType res
1976 fvType (ForAllTy (TvBndr tv _) ty)
1977 = fvType (tyVarKind tv) ++
1978 filter (/= tv) (fvType ty)
1979 fvType (CastTy ty co) = fvType ty ++ fvCo co
1980 fvType (CoercionTy co) = fvCo co
1981
1982 fvTypes :: [Type] -> [TyVar]
1983 fvTypes tys = concat (map fvType tys)
1984
1985 fvCo :: Coercion -> [TyCoVar]
1986 fvCo (Refl _ ty) = fvType ty
1987 fvCo (TyConAppCo _ _ args) = concatMap fvCo args
1988 fvCo (AppCo co arg) = fvCo co ++ fvCo arg
1989 fvCo (ForAllCo tv h co) = filter (/= tv) (fvCo co) ++ fvCo h
1990 fvCo (FunCo _ co1 co2) = fvCo co1 ++ fvCo co2
1991 fvCo (CoVarCo v) = [v]
1992 fvCo (AxiomInstCo _ _ args) = concatMap fvCo args
1993 fvCo (UnivCo p _ t1 t2) = fvProv p ++ fvType t1 ++ fvType t2
1994 fvCo (SymCo co) = fvCo co
1995 fvCo (TransCo co1 co2) = fvCo co1 ++ fvCo co2
1996 fvCo (NthCo _ _ co) = fvCo co
1997 fvCo (LRCo _ co) = fvCo co
1998 fvCo (InstCo co arg) = fvCo co ++ fvCo arg
1999 fvCo (CoherenceCo co1 co2) = fvCo co1 ++ fvCo co2
2000 fvCo (KindCo co) = fvCo co
2001 fvCo (SubCo co) = fvCo co
2002 fvCo (AxiomRuleCo _ cs) = concatMap fvCo cs
2003 fvCo (HoleCo h) = pprPanic "fvCo falls into a hole" (ppr h)
2004
2005 fvProv :: UnivCoProvenance -> [TyCoVar]
2006 fvProv UnsafeCoerceProv = []
2007 fvProv (PhantomProv co) = fvCo co
2008 fvProv (ProofIrrelProv co) = fvCo co
2009 fvProv (PluginProv _) = []
2010
2011 sizeType :: Type -> Int
2012 -- Size of a type: the number of variables and constructors
2013 sizeType ty | Just exp_ty <- tcView ty = sizeType exp_ty
2014 sizeType (TyVarTy {}) = 1
2015 sizeType (TyConApp tc tys) = 1 + sizeTyConAppArgs tc tys
2016 sizeType (LitTy {}) = 1
2017 sizeType (AppTy fun arg) = sizeType fun + sizeType arg
2018 sizeType (FunTy arg res) = sizeType arg + sizeType res + 1
2019 sizeType (ForAllTy _ ty) = sizeType ty
2020 sizeType (CastTy ty _) = sizeType ty
2021 sizeType (CoercionTy _) = 1
2022
2023 sizeTypes :: [Type] -> Int
2024 sizeTypes = foldr ((+) . sizeType) 0
2025
2026 sizeTyConAppArgs :: TyCon -> [Type] -> Int
2027 sizeTyConAppArgs _tc tys = sizeTypes tys -- (filterOutInvisibleTypes tc tys)
2028 -- See Note [Invisible arguments and termination]
2029
2030 -- Size of a predicate
2031 --
2032 -- We are considering whether class constraints terminate.
2033 -- Equality constraints and constraints for the implicit
2034 -- parameter class always terminate so it is safe to say "size 0".
2035 -- See Trac #4200.
2036 sizePred :: PredType -> Int
2037 sizePred ty = goClass ty
2038 where
2039 goClass p = go (classifyPredType p)
2040
2041 go (ClassPred cls tys')
2042 | isTerminatingClass cls = 0
2043 | otherwise = sizeTypes (filterOutInvisibleTypes (classTyCon cls) tys')
2044 -- The filtering looks bogus
2045 -- See Note [Invisible arguments and termination]
2046 go (EqPred {}) = 0
2047 go (IrredPred ty) = sizeType ty
2048 go (ForAllPred _ _ pred) = goClass pred
2049
2050 -- | When this says "True", ignore this class constraint during
2051 -- a termination check
2052 isTerminatingClass :: Class -> Bool
2053 isTerminatingClass cls
2054 = isIPClass cls -- Implicit parameter constraints always terminate because
2055 -- there are no instances for them --- they are only solved
2056 -- by "local instances" in expressions
2057 || cls `hasKey` typeableClassKey
2058 || cls `hasKey` coercibleTyConKey
2059 || cls `hasKey` eqTyConKey
2060 || cls `hasKey` heqTyConKey
2061
2062 -- | Tidy before printing a type
2063 ppr_tidy :: TidyEnv -> Type -> SDoc
2064 ppr_tidy env ty = pprType (tidyType env ty)
2065
2066 allDistinctTyVars :: TyVarSet -> [KindOrType] -> Bool
2067 -- (allDistinctTyVars tvs tys) returns True if tys are
2068 -- a) all tyvars
2069 -- b) all distinct
2070 -- c) disjoint from tvs
2071 allDistinctTyVars _ [] = True
2072 allDistinctTyVars tkvs (ty : tys)
2073 = case getTyVar_maybe ty of
2074 Nothing -> False
2075 Just tv | tv `elemVarSet` tkvs -> False
2076 | otherwise -> allDistinctTyVars (tkvs `extendVarSet` tv) tys