2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
6 Monadic type operations
8 This module contains monadic operations over types that contain
13 TcTyVar, TcKind, TcType, TcTauType, TcThetaType, TcTyVarSet,
15 --------------------------------
16 -- Creating new mutable type variables
18 newFlexiTyVarTy, -- Kind -> TcM TcType
19 newFlexiTyVarTys, -- Int -> Kind -> TcM [TcType]
20 newKindVar, newKindVars,
21 lookupTcTyVar, LookupTyVarResult(..),
22 newMetaTyVar, readMetaTyVar, writeMetaTyVar,
24 --------------------------------
25 -- Boxy type variables
26 newBoxyTyVar, newBoxyTyVars, newBoxyTyVarTys, readFilledBox,
28 --------------------------------
29 -- Creating new coercion variables
32 --------------------------------
34 tcInstTyVar, tcInstType, tcInstTyVars, tcInstBoxyTyVar,
35 tcInstSigTyVars, zonkSigTyVar,
36 tcInstSkolTyVar, tcInstSkolTyVars, tcInstSkolType,
37 tcSkolSigType, tcSkolSigTyVars,
39 --------------------------------
40 -- Checking type validity
41 Rank, UserTypeCtxt(..), checkValidType,
42 SourceTyCtxt(..), checkValidTheta, checkFreeness,
43 checkValidInstHead, checkValidInstance, checkAmbiguity,
47 --------------------------------
49 zonkType, zonkTcPredType,
50 zonkTcTyVar, zonkTcTyVars, zonkTcTyVarsAndFV,
51 zonkQuantifiedTyVar, zonkQuantifiedTyVars,
52 zonkTcType, zonkTcTypes, zonkTcClassConstraints, zonkTcThetaType,
53 zonkTcKindToKind, zonkTcKind, zonkTopTyVar,
55 readKindVar, writeKindVar
59 #include "HsVersions.h"
72 import TcRnMonad -- TcType, amongst others
85 import Control.Monad ( when )
86 import Data.List ( (\\) )
90 %************************************************************************
92 Instantiation in general
94 %************************************************************************
97 tcInstType :: ([TyVar] -> TcM [TcTyVar]) -- How to instantiate the type variables
98 -> TcType -- Type to instantiate
99 -> TcM ([TcTyVar], TcThetaType, TcType) -- Result
100 tcInstType inst_tyvars ty
101 = case tcSplitForAllTys ty of
102 ([], rho) -> let -- There may be overloading despite no type variables;
103 -- (?x :: Int) => Int -> Int
104 (theta, tau) = tcSplitPhiTy rho
106 return ([], theta, tau)
108 (tyvars, rho) -> do { tyvars' <- inst_tyvars tyvars
110 ; let tenv = zipTopTvSubst tyvars (mkTyVarTys tyvars')
111 -- Either the tyvars are freshly made, by inst_tyvars,
112 -- or (in the call from tcSkolSigType) any nested foralls
113 -- have different binders. Either way, zipTopTvSubst is ok
115 ; let (theta, tau) = tcSplitPhiTy (substTy tenv rho)
116 ; return (tyvars', theta, tau) }
120 %************************************************************************
124 %************************************************************************
127 newCoVars :: [(TcType,TcType)] -> TcM [CoVar]
129 = do { us <- newUniqueSupply
130 ; return [ mkCoVar (mkSysTvName uniq FSLIT("co"))
132 | ((ty1,ty2), uniq) <- spec `zip` uniqsFromSupply us] }
134 newKindVar :: TcM TcKind
135 newKindVar = do { uniq <- newUnique
136 ; ref <- newMutVar Flexi
137 ; return (mkTyVarTy (mkKindVar uniq ref)) }
139 newKindVars :: Int -> TcM [TcKind]
140 newKindVars n = mappM (\ _ -> newKindVar) (nOfThem n ())
144 %************************************************************************
146 SkolemTvs (immutable)
148 %************************************************************************
151 mkSkolTyVar :: Name -> Kind -> SkolemInfo -> TcTyVar
152 mkSkolTyVar name kind info = mkTcTyVar name kind (SkolemTv info)
154 tcSkolSigType :: SkolemInfo -> Type -> TcM ([TcTyVar], TcThetaType, TcType)
155 -- Instantiate a type signature with skolem constants, but
156 -- do *not* give them fresh names, because we want the name to
157 -- be in the type environment -- it is lexically scoped.
158 tcSkolSigType info ty = tcInstType (\tvs -> return (tcSkolSigTyVars info tvs)) ty
160 tcSkolSigTyVars :: SkolemInfo -> [TyVar] -> [TcTyVar]
161 -- Make skolem constants, but do *not* give them new names, as above
162 tcSkolSigTyVars info tyvars = [ mkSkolTyVar (tyVarName tv) (tyVarKind tv) info
165 tcInstSkolTyVar :: SkolemInfo -> Maybe SrcLoc -> TyVar -> TcM TcTyVar
166 -- Instantiate the tyvar, using
167 -- * the occ-name and kind of the supplied tyvar,
168 -- * the unique from the monad,
169 -- * the location either from the tyvar (mb_loc = Nothing)
170 -- or from mb_loc (Just loc)
171 tcInstSkolTyVar info mb_loc tyvar
172 = do { uniq <- newUnique
173 ; let old_name = tyVarName tyvar
174 kind = tyVarKind tyvar
175 loc = mb_loc `orElse` getSrcLoc old_name
176 new_name = mkInternalName uniq (nameOccName old_name) loc
177 ; return (mkSkolTyVar new_name kind info) }
179 tcInstSkolTyVars :: SkolemInfo -> [TyVar] -> TcM [TcTyVar]
180 -- Get the location from the monad
181 tcInstSkolTyVars info tyvars
182 = do { span <- getSrcSpanM
183 ; mapM (tcInstSkolTyVar info (Just (srcSpanStart span))) tyvars }
185 tcInstSkolType :: SkolemInfo -> TcType -> TcM ([TcTyVar], TcThetaType, TcType)
186 -- Instantiate a type with fresh skolem constants
187 -- Binding location comes from the monad
188 tcInstSkolType info ty = tcInstType (tcInstSkolTyVars info) ty
192 %************************************************************************
194 MetaTvs (meta type variables; mutable)
196 %************************************************************************
199 newMetaTyVar :: BoxInfo -> Kind -> TcM TcTyVar
200 -- Make a new meta tyvar out of thin air
201 newMetaTyVar box_info kind
202 = do { uniq <- newUnique
203 ; ref <- newMutVar Flexi ;
204 ; let name = mkSysTvName uniq fs
205 fs = case box_info of
208 SigTv _ -> FSLIT("a")
209 -- We give BoxTv and TauTv the same string, because
210 -- otherwise we get user-visible differences in error
211 -- messages, which are confusing. If you want to see
212 -- the box_info of each tyvar, use -dppr-debug
213 ; return (mkTcTyVar name kind (MetaTv box_info ref)) }
215 instMetaTyVar :: BoxInfo -> TyVar -> TcM TcTyVar
216 -- Make a new meta tyvar whose Name and Kind
217 -- come from an existing TyVar
218 instMetaTyVar box_info tyvar
219 = do { uniq <- newUnique
220 ; ref <- newMutVar Flexi ;
221 ; let name = setNameUnique (tyVarName tyvar) uniq
222 kind = tyVarKind tyvar
223 ; return (mkTcTyVar name kind (MetaTv box_info ref)) }
225 readMetaTyVar :: TyVar -> TcM MetaDetails
226 readMetaTyVar tyvar = ASSERT2( isMetaTyVar tyvar, ppr tyvar )
227 readMutVar (metaTvRef tyvar)
229 writeMetaTyVar :: TcTyVar -> TcType -> TcM ()
231 writeMetaTyVar tyvar ty = writeMutVar (metaTvRef tyvar) (Indirect ty)
233 writeMetaTyVar tyvar ty
234 | not (isMetaTyVar tyvar)
235 = pprTrace "writeMetaTyVar" (ppr tyvar) $
239 = ASSERT( isMetaTyVar tyvar )
240 ASSERT2( k2 `isSubKind` k1, (ppr tyvar <+> ppr k1) $$ (ppr ty <+> ppr k2) )
241 do { ASSERTM2( do { details <- readMetaTyVar tyvar; return (isFlexi details) }, ppr tyvar )
242 ; writeMutVar (metaTvRef tyvar) (Indirect ty) }
250 %************************************************************************
254 %************************************************************************
257 newFlexiTyVar :: Kind -> TcM TcTyVar
258 newFlexiTyVar kind = newMetaTyVar TauTv kind
260 newFlexiTyVarTy :: Kind -> TcM TcType
262 = newFlexiTyVar kind `thenM` \ tc_tyvar ->
263 returnM (TyVarTy tc_tyvar)
265 newFlexiTyVarTys :: Int -> Kind -> TcM [TcType]
266 newFlexiTyVarTys n kind = mappM newFlexiTyVarTy (nOfThem n kind)
268 tcInstTyVar :: TyVar -> TcM TcTyVar
269 -- Instantiate with a META type variable
270 tcInstTyVar tyvar = instMetaTyVar TauTv tyvar
272 tcInstTyVars :: [TyVar] -> TcM ([TcTyVar], [TcType], TvSubst)
273 -- Instantiate with META type variables
275 = do { tc_tvs <- mapM tcInstTyVar tyvars
276 ; let tys = mkTyVarTys tc_tvs
277 ; returnM (tc_tvs, tys, zipTopTvSubst tyvars tys) }
278 -- Since the tyvars are freshly made,
279 -- they cannot possibly be captured by
280 -- any existing for-alls. Hence zipTopTvSubst
284 %************************************************************************
288 %************************************************************************
291 tcInstSigTyVars :: Bool -> SkolemInfo -> [TyVar] -> TcM [TcTyVar]
292 -- Instantiate with skolems or meta SigTvs; depending on use_skols
293 -- Always take location info from the supplied tyvars
294 tcInstSigTyVars use_skols skol_info tyvars
296 = mapM (tcInstSkolTyVar skol_info Nothing) tyvars
299 = mapM (instMetaTyVar (SigTv skol_info)) tyvars
301 zonkSigTyVar :: TcTyVar -> TcM TcTyVar
303 | isSkolemTyVar sig_tv
304 = return sig_tv -- Happens in the call in TcBinds.checkDistinctTyVars
306 = ASSERT( isSigTyVar sig_tv )
307 do { ty <- zonkTcTyVar sig_tv
308 ; return (tcGetTyVar "zonkSigTyVar" ty) }
309 -- 'ty' is bound to be a type variable, because SigTvs
310 -- can only be unified with type variables
314 %************************************************************************
318 %************************************************************************
321 newBoxyTyVar :: Kind -> TcM BoxyTyVar
322 newBoxyTyVar kind = newMetaTyVar BoxTv kind
324 newBoxyTyVars :: [Kind] -> TcM [BoxyTyVar]
325 newBoxyTyVars kinds = mapM newBoxyTyVar kinds
327 newBoxyTyVarTys :: [Kind] -> TcM [BoxyType]
328 newBoxyTyVarTys kinds = do { tvs <- mapM newBoxyTyVar kinds; return (mkTyVarTys tvs) }
330 readFilledBox :: BoxyTyVar -> TcM TcType
331 -- Read the contents of the box, which should be filled in by now
332 readFilledBox box_tv = ASSERT( isBoxyTyVar box_tv )
333 do { cts <- readMetaTyVar box_tv
335 Flexi -> pprPanic "readFilledBox" (ppr box_tv)
336 Indirect ty -> return ty }
338 tcInstBoxyTyVar :: TyVar -> TcM BoxyTyVar
339 -- Instantiate with a BOXY type variable
340 tcInstBoxyTyVar tyvar = instMetaTyVar BoxTv tyvar
344 %************************************************************************
346 \subsection{Putting and getting mutable type variables}
348 %************************************************************************
350 But it's more fun to short out indirections on the way: If this
351 version returns a TyVar, then that TyVar is unbound. If it returns
352 any other type, then there might be bound TyVars embedded inside it.
354 We return Nothing iff the original box was unbound.
357 data LookupTyVarResult -- The result of a lookupTcTyVar call
358 = DoneTv TcTyVarDetails -- SkolemTv or virgin MetaTv
361 lookupTcTyVar :: TcTyVar -> TcM LookupTyVarResult
363 = ASSERT( isTcTyVar tyvar )
365 SkolemTv _ -> return (DoneTv details)
366 MetaTv _ ref -> do { meta_details <- readMutVar ref
367 ; case meta_details of
368 Indirect ty -> return (IndirectTv ty)
369 Flexi -> return (DoneTv details) }
371 details = tcTyVarDetails tyvar
374 -- gaw 2004 We aren't shorting anything out anymore, at least for now
376 | not (isTcTyVar tyvar)
377 = pprTrace "getTcTyVar" (ppr tyvar) $
378 returnM (Just (mkTyVarTy tyvar))
381 = ASSERT2( isTcTyVar tyvar, ppr tyvar )
382 readMetaTyVar tyvar `thenM` \ maybe_ty ->
384 Just ty -> short_out ty `thenM` \ ty' ->
385 writeMetaTyVar tyvar (Just ty') `thenM_`
388 Nothing -> returnM Nothing
390 short_out :: TcType -> TcM TcType
391 short_out ty@(TyVarTy tyvar)
392 | not (isTcTyVar tyvar)
396 = readMetaTyVar tyvar `thenM` \ maybe_ty ->
398 Just ty' -> short_out ty' `thenM` \ ty' ->
399 writeMetaTyVar tyvar (Just ty') `thenM_`
404 short_out other_ty = returnM other_ty
409 %************************************************************************
411 \subsection{Zonking -- the exernal interfaces}
413 %************************************************************************
415 ----------------- Type variables
418 zonkTcTyVars :: [TcTyVar] -> TcM [TcType]
419 zonkTcTyVars tyvars = mappM zonkTcTyVar tyvars
421 zonkTcTyVarsAndFV :: [TcTyVar] -> TcM TcTyVarSet
422 zonkTcTyVarsAndFV tyvars = mappM zonkTcTyVar tyvars `thenM` \ tys ->
423 returnM (tyVarsOfTypes tys)
425 zonkTcTyVar :: TcTyVar -> TcM TcType
426 zonkTcTyVar tyvar = ASSERT( isTcTyVar tyvar )
427 zonk_tc_tyvar (\ tv -> returnM (TyVarTy tv)) tyvar
430 ----------------- Types
433 zonkTcType :: TcType -> TcM TcType
434 zonkTcType ty = zonkType (\ tv -> returnM (TyVarTy tv)) ty
436 zonkTcTypes :: [TcType] -> TcM [TcType]
437 zonkTcTypes tys = mappM zonkTcType tys
439 zonkTcClassConstraints cts = mappM zonk cts
440 where zonk (clas, tys)
441 = zonkTcTypes tys `thenM` \ new_tys ->
442 returnM (clas, new_tys)
444 zonkTcThetaType :: TcThetaType -> TcM TcThetaType
445 zonkTcThetaType theta = mappM zonkTcPredType theta
447 zonkTcPredType :: TcPredType -> TcM TcPredType
448 zonkTcPredType (ClassP c ts)
449 = zonkTcTypes ts `thenM` \ new_ts ->
450 returnM (ClassP c new_ts)
451 zonkTcPredType (IParam n t)
452 = zonkTcType t `thenM` \ new_t ->
453 returnM (IParam n new_t)
454 zonkTcPredType (EqPred t1 t2)
455 = zonkTcType t1 `thenM` \ new_t1 ->
456 zonkTcType t2 `thenM` \ new_t2 ->
457 returnM (EqPred new_t1 new_t2)
460 ------------------- These ...ToType, ...ToKind versions
461 are used at the end of type checking
464 zonkTopTyVar :: TcTyVar -> TcM TcTyVar
465 -- zonkTopTyVar is used, at the top level, on any un-instantiated meta type variables
466 -- to default the kind of ? and ?? etc to *. This is important to ensure that
467 -- instance declarations match. For example consider
468 -- instance Show (a->b)
469 -- foo x = show (\_ -> True)
470 -- Then we'll get a constraint (Show (p ->q)) where p has argTypeKind (printed ??),
471 -- and that won't match the typeKind (*) in the instance decl.
473 -- Because we are at top level, no further constraints are going to affect these
474 -- type variables, so it's time to do it by hand. However we aren't ready
475 -- to default them fully to () or whatever, because the type-class defaulting
476 -- rules have yet to run.
479 | k `eqKind` default_k = return tv
481 = do { tv' <- newFlexiTyVar default_k
482 ; writeMetaTyVar tv (mkTyVarTy tv')
486 default_k = defaultKind k
488 zonkQuantifiedTyVars :: [TcTyVar] -> TcM [TyVar]
489 zonkQuantifiedTyVars = mappM zonkQuantifiedTyVar
491 zonkQuantifiedTyVar :: TcTyVar -> TcM TyVar
492 -- zonkQuantifiedTyVar is applied to the a TcTyVar when quantifying over it.
494 -- The quantified type variables often include meta type variables
495 -- we want to freeze them into ordinary type variables, and
496 -- default their kind (e.g. from OpenTypeKind to TypeKind)
497 -- -- see notes with Kind.defaultKind
498 -- The meta tyvar is updated to point to the new regular TyVar. Now any
499 -- bound occurences of the original type variable will get zonked to
500 -- the immutable version.
502 -- We leave skolem TyVars alone; they are immutable.
503 zonkQuantifiedTyVar tv
504 | ASSERT( isTcTyVar tv )
505 isSkolemTyVar tv = return tv
506 -- It might be a skolem type variable,
507 -- for example from a user type signature
509 | otherwise -- It's a meta-type-variable
510 = do { details <- readMetaTyVar tv
512 -- Create the new, frozen, regular type variable
513 ; let final_kind = defaultKind (tyVarKind tv)
514 final_tv = mkTyVar (tyVarName tv) final_kind
516 -- Bind the meta tyvar to the new tyvar
518 Indirect ty -> WARN( True, ppr tv $$ ppr ty )
520 -- [Sept 04] I don't think this should happen
521 -- See note [Silly Type Synonym]
523 Flexi -> writeMetaTyVar tv (mkTyVarTy final_tv)
525 -- Return the new tyvar
529 [Silly Type Synonyms]
532 type C u a = u -- Note 'a' unused
534 foo :: (forall a. C u a -> C u a) -> u
538 bar = foo (\t -> t + t)
540 * From the (\t -> t+t) we get type {Num d} => d -> d
543 * Now unify with type of foo's arg, and we get:
544 {Num (C d a)} => C d a -> C d a
547 * Now abstract over the 'a', but float out the Num (C d a) constraint
548 because it does not 'really' mention a. (see exactTyVarsOfType)
549 The arg to foo becomes
552 * So we get a dict binding for Num (C d a), which is zonked to give
554 [Note Sept 04: now that we are zonking quantified type variables
555 on construction, the 'a' will be frozen as a regular tyvar on
556 quantification, so the floated dict will still have type (C d a).
557 Which renders this whole note moot; happily!]
559 * Then the /\a abstraction has a zonked 'a' in it.
561 All very silly. I think its harmless to ignore the problem. We'll end up with
562 a /\a in the final result but all the occurrences of a will be zonked to ()
565 %************************************************************************
567 \subsection{Zonking -- the main work-horses: zonkType, zonkTyVar}
569 %* For internal use only! *
571 %************************************************************************
574 -- For unbound, mutable tyvars, zonkType uses the function given to it
575 -- For tyvars bound at a for-all, zonkType zonks them to an immutable
576 -- type variable and zonks the kind too
578 zonkType :: (TcTyVar -> TcM Type) -- What to do with unbound mutable type variables
579 -- see zonkTcType, and zonkTcTypeToType
582 zonkType unbound_var_fn ty
585 go (NoteTy _ ty2) = go ty2 -- Discard free-tyvar annotations
587 go (TyConApp tc tys) = mappM go tys `thenM` \ tys' ->
588 returnM (TyConApp tc tys')
590 go (PredTy p) = go_pred p `thenM` \ p' ->
593 go (FunTy arg res) = go arg `thenM` \ arg' ->
594 go res `thenM` \ res' ->
595 returnM (FunTy arg' res')
597 go (AppTy fun arg) = go fun `thenM` \ fun' ->
598 go arg `thenM` \ arg' ->
599 returnM (mkAppTy fun' arg')
600 -- NB the mkAppTy; we might have instantiated a
601 -- type variable to a type constructor, so we need
602 -- to pull the TyConApp to the top.
604 -- The two interesting cases!
605 go (TyVarTy tyvar) | isTcTyVar tyvar = zonk_tc_tyvar unbound_var_fn tyvar
606 | otherwise = return (TyVarTy tyvar)
607 -- Ordinary (non Tc) tyvars occur inside quantified types
609 go (ForAllTy tyvar ty) = ASSERT( isImmutableTyVar tyvar )
610 go ty `thenM` \ ty' ->
611 returnM (ForAllTy tyvar ty')
613 go_pred (ClassP c tys) = mappM go tys `thenM` \ tys' ->
614 returnM (ClassP c tys')
615 go_pred (IParam n ty) = go ty `thenM` \ ty' ->
616 returnM (IParam n ty')
617 go_pred (EqPred ty1 ty2) = go ty1 `thenM` \ ty1' ->
618 go ty2 `thenM` \ ty2' ->
619 returnM (EqPred ty1' ty2')
621 zonk_tc_tyvar :: (TcTyVar -> TcM Type) -- What to do for an unbound mutable variable
622 -> TcTyVar -> TcM TcType
623 zonk_tc_tyvar unbound_var_fn tyvar
624 | not (isMetaTyVar tyvar) -- Skolems
625 = returnM (TyVarTy tyvar)
627 | otherwise -- Mutables
628 = do { cts <- readMetaTyVar tyvar
630 Flexi -> unbound_var_fn tyvar -- Unbound meta type variable
631 Indirect ty -> zonkType unbound_var_fn ty }
636 %************************************************************************
640 %************************************************************************
643 readKindVar :: KindVar -> TcM (MetaDetails)
644 writeKindVar :: KindVar -> TcKind -> TcM ()
645 readKindVar kv = readMutVar (kindVarRef kv)
646 writeKindVar kv val = writeMutVar (kindVarRef kv) (Indirect val)
649 zonkTcKind :: TcKind -> TcM TcKind
650 zonkTcKind k = zonkTcType k
653 zonkTcKindToKind :: TcKind -> TcM Kind
654 -- When zonking a TcKind to a kind, we need to instantiate kind variables,
655 -- Haskell specifies that * is to be used, so we follow that.
656 zonkTcKindToKind k = zonkType (\ _ -> return liftedTypeKind) k
659 %************************************************************************
661 \subsection{Checking a user type}
663 %************************************************************************
665 When dealing with a user-written type, we first translate it from an HsType
666 to a Type, performing kind checking, and then check various things that should
667 be true about it. We don't want to perform these checks at the same time
668 as the initial translation because (a) they are unnecessary for interface-file
669 types and (b) when checking a mutually recursive group of type and class decls,
670 we can't "look" at the tycons/classes yet. Also, the checks are are rather
671 diverse, and used to really mess up the other code.
673 One thing we check for is 'rank'.
675 Rank 0: monotypes (no foralls)
676 Rank 1: foralls at the front only, Rank 0 inside
677 Rank 2: foralls at the front, Rank 1 on left of fn arrow,
679 basic ::= tyvar | T basic ... basic
681 r2 ::= forall tvs. cxt => r2a
682 r2a ::= r1 -> r2a | basic
683 r1 ::= forall tvs. cxt => r0
684 r0 ::= r0 -> r0 | basic
686 Another thing is to check that type synonyms are saturated.
687 This might not necessarily show up in kind checking.
689 data T k = MkT (k Int)
694 checkValidType :: UserTypeCtxt -> Type -> TcM ()
695 -- Checks that the type is valid for the given context
696 checkValidType ctxt ty
697 = traceTc (text "checkValidType" <+> ppr ty) `thenM_`
698 doptM Opt_GlasgowExts `thenM` \ gla_exts ->
700 rank | gla_exts = Arbitrary
702 = case ctxt of -- Haskell 98
704 LamPatSigCtxt -> Rank 0
705 BindPatSigCtxt -> Rank 0
706 DefaultDeclCtxt-> Rank 0
708 TySynCtxt _ -> Rank 0
709 ExprSigCtxt -> Rank 1
710 FunSigCtxt _ -> Rank 1
711 ConArgCtxt _ -> Rank 1 -- We are given the type of the entire
712 -- constructor, hence rank 1
713 ForSigCtxt _ -> Rank 1
714 SpecInstCtxt -> Rank 1
716 actual_kind = typeKind ty
718 kind_ok = case ctxt of
719 TySynCtxt _ -> True -- Any kind will do
720 ResSigCtxt -> isSubOpenTypeKind actual_kind
721 ExprSigCtxt -> isSubOpenTypeKind actual_kind
722 GenPatCtxt -> isLiftedTypeKind actual_kind
723 ForSigCtxt _ -> isLiftedTypeKind actual_kind
724 other -> isSubArgTypeKind actual_kind
726 ubx_tup | not gla_exts = UT_NotOk
727 | otherwise = case ctxt of
731 -- Unboxed tuples ok in function results,
732 -- but for type synonyms we allow them even at
735 -- Check that the thing has kind Type, and is lifted if necessary
736 checkTc kind_ok (kindErr actual_kind) `thenM_`
738 -- Check the internal validity of the type itself
739 check_poly_type rank ubx_tup ty `thenM_`
741 traceTc (text "checkValidType done" <+> ppr ty)
746 data Rank = Rank Int | Arbitrary
748 decRank :: Rank -> Rank
749 decRank Arbitrary = Arbitrary
750 decRank (Rank n) = Rank (n-1)
752 ----------------------------------------
753 data UbxTupFlag = UT_Ok | UT_NotOk
754 -- The "Ok" version means "ok if -fglasgow-exts is on"
756 ----------------------------------------
757 check_poly_type :: Rank -> UbxTupFlag -> Type -> TcM ()
758 check_poly_type (Rank 0) ubx_tup ty
759 = check_tau_type (Rank 0) ubx_tup ty
761 check_poly_type rank ubx_tup ty
762 | null tvs && null theta
763 = check_tau_type rank ubx_tup ty
765 = do { check_valid_theta SigmaCtxt theta
766 ; check_poly_type rank ubx_tup tau -- Allow foralls to right of arrow
767 ; checkFreeness tvs theta
768 ; checkAmbiguity tvs theta (tyVarsOfType tau) }
770 (tvs, theta, tau) = tcSplitSigmaTy ty
772 ----------------------------------------
773 check_arg_type :: Type -> TcM ()
774 -- The sort of type that can instantiate a type variable,
775 -- or be the argument of a type constructor.
776 -- Not an unboxed tuple, but now *can* be a forall (since impredicativity)
777 -- Other unboxed types are very occasionally allowed as type
778 -- arguments depending on the kind of the type constructor
780 -- For example, we want to reject things like:
782 -- instance Ord a => Ord (forall s. T s a)
784 -- g :: T s (forall b.b)
786 -- NB: unboxed tuples can have polymorphic or unboxed args.
787 -- This happens in the workers for functions returning
788 -- product types with polymorphic components.
789 -- But not in user code.
790 -- Anyway, they are dealt with by a special case in check_tau_type
793 = check_poly_type Arbitrary UT_NotOk ty `thenM_`
794 checkTc (not (isUnLiftedType ty)) (unliftedArgErr ty)
796 ----------------------------------------
797 check_tau_type :: Rank -> UbxTupFlag -> Type -> TcM ()
798 -- Rank is allowed rank for function args
799 -- No foralls otherwise
801 check_tau_type rank ubx_tup ty@(ForAllTy _ _) = failWithTc (forAllTyErr ty)
802 check_tau_type rank ubx_tup ty@(FunTy (PredTy _) _) = failWithTc (forAllTyErr ty)
803 -- Reject e.g. (Maybe (?x::Int => Int)), with a decent error message
805 -- Naked PredTys don't usually show up, but they can as a result of
806 -- {-# SPECIALISE instance Ord Char #-}
807 -- The Right Thing would be to fix the way that SPECIALISE instance pragmas
808 -- are handled, but the quick thing is just to permit PredTys here.
809 check_tau_type rank ubx_tup (PredTy sty) = getDOpts `thenM` \ dflags ->
810 check_pred_ty dflags TypeCtxt sty
812 check_tau_type rank ubx_tup (TyVarTy _) = returnM ()
813 check_tau_type rank ubx_tup ty@(FunTy arg_ty res_ty)
814 = check_poly_type (decRank rank) UT_NotOk arg_ty `thenM_`
815 check_poly_type rank UT_Ok res_ty
817 check_tau_type rank ubx_tup (AppTy ty1 ty2)
818 = check_arg_type ty1 `thenM_` check_arg_type ty2
820 check_tau_type rank ubx_tup (NoteTy other_note ty)
821 = check_tau_type rank ubx_tup ty
823 check_tau_type rank ubx_tup ty@(TyConApp tc tys)
825 = do { -- It's OK to have an *over-applied* type synonym
826 -- data Tree a b = ...
827 -- type Foo a = Tree [a]
828 -- f :: Foo a b -> ...
830 Just ty' -> check_tau_type rank ubx_tup ty' -- Check expansion
831 Nothing -> failWithTc arity_msg
833 ; gla_exts <- doptM Opt_GlasgowExts
835 -- If -fglasgow-exts then don't check the type arguments
836 -- This allows us to instantiate a synonym defn with a
837 -- for-all type, or with a partially-applied type synonym.
838 -- e.g. type T a b = a
841 -- Here, T is partially applied, so it's illegal in H98.
842 -- But if you expand S first, then T we get just
847 -- For H98, do check the type args
848 mappM_ check_arg_type tys
851 | isUnboxedTupleTyCon tc
852 = doptM Opt_GlasgowExts `thenM` \ gla_exts ->
853 checkTc (ubx_tup_ok gla_exts) ubx_tup_msg `thenM_`
854 mappM_ (check_tau_type (Rank 0) UT_Ok) tys
855 -- Args are allowed to be unlifted, or
856 -- more unboxed tuples, so can't use check_arg_ty
859 = mappM_ check_arg_type tys
862 ubx_tup_ok gla_exts = case ubx_tup of { UT_Ok -> gla_exts; other -> False }
865 tc_arity = tyConArity tc
867 arity_msg = arityErr "Type synonym" (tyConName tc) tc_arity n_args
868 ubx_tup_msg = ubxArgTyErr ty
870 ----------------------------------------
871 forAllTyErr ty = ptext SLIT("Illegal polymorphic or qualified type:") <+> ppr ty
872 unliftedArgErr ty = ptext SLIT("Illegal unlifted type argument:") <+> ppr ty
873 ubxArgTyErr ty = ptext SLIT("Illegal unboxed tuple type as function argument:") <+> ppr ty
874 kindErr kind = ptext SLIT("Expecting an ordinary type, but found a type of kind") <+> ppr kind
879 %************************************************************************
881 \subsection{Checking a theta or source type}
883 %************************************************************************
886 -- Enumerate the contexts in which a "source type", <S>, can occur
890 -- or (N a) where N is a newtype
893 = ClassSCCtxt Name -- Superclasses of clas
894 -- class <S> => C a where ...
895 | SigmaCtxt -- Theta part of a normal for-all type
896 -- f :: <S> => a -> a
897 | DataTyCtxt Name -- Theta part of a data decl
898 -- data <S> => T a = MkT a
899 | TypeCtxt -- Source type in an ordinary type
901 | InstThetaCtxt -- Context of an instance decl
902 -- instance <S> => C [a] where ...
904 pprSourceTyCtxt (ClassSCCtxt c) = ptext SLIT("the super-classes of class") <+> quotes (ppr c)
905 pprSourceTyCtxt SigmaCtxt = ptext SLIT("the context of a polymorphic type")
906 pprSourceTyCtxt (DataTyCtxt tc) = ptext SLIT("the context of the data type declaration for") <+> quotes (ppr tc)
907 pprSourceTyCtxt InstThetaCtxt = ptext SLIT("the context of an instance declaration")
908 pprSourceTyCtxt TypeCtxt = ptext SLIT("the context of a type")
912 checkValidTheta :: SourceTyCtxt -> ThetaType -> TcM ()
913 checkValidTheta ctxt theta
914 = addErrCtxt (checkThetaCtxt ctxt theta) (check_valid_theta ctxt theta)
916 -------------------------
917 check_valid_theta ctxt []
919 check_valid_theta ctxt theta
920 = getDOpts `thenM` \ dflags ->
921 warnTc (notNull dups) (dupPredWarn dups) `thenM_`
922 mappM_ (check_pred_ty dflags ctxt) theta
924 (_,dups) = removeDups tcCmpPred theta
926 -------------------------
927 check_pred_ty dflags ctxt pred@(ClassP cls tys)
928 = -- Class predicates are valid in all contexts
929 checkTc (arity == n_tys) arity_err `thenM_`
931 -- Check the form of the argument types
932 mappM_ check_arg_type tys `thenM_`
933 checkTc (check_class_pred_tys dflags ctxt tys)
934 (predTyVarErr pred $$ how_to_allow)
937 class_name = className cls
938 arity = classArity cls
940 arity_err = arityErr "Class" class_name arity n_tys
941 how_to_allow = parens (ptext SLIT("Use -fglasgow-exts to permit this"))
943 check_pred_ty dflags SigmaCtxt (IParam _ ty) = check_arg_type ty
944 -- Implicit parameters only allows in type
945 -- signatures; not in instance decls, superclasses etc
946 -- The reason for not allowing implicit params in instances is a bit subtle
947 -- If we allowed instance (?x::Int, Eq a) => Foo [a] where ...
948 -- then when we saw (e :: (?x::Int) => t) it would be unclear how to
949 -- discharge all the potential usas of the ?x in e. For example, a
950 -- constraint Foo [Int] might come out of e,and applying the
951 -- instance decl would show up two uses of ?x.
954 check_pred_ty dflags ctxt sty = failWithTc (badPredTyErr sty)
956 -------------------------
957 check_class_pred_tys dflags ctxt tys
959 TypeCtxt -> True -- {-# SPECIALISE instance Eq (T Int) #-} is fine
960 InstThetaCtxt -> gla_exts || undecidable_ok || all tcIsTyVarTy tys
961 -- Further checks on head and theta in
962 -- checkInstTermination
963 other -> gla_exts || all tyvar_head tys
965 gla_exts = dopt Opt_GlasgowExts dflags
966 undecidable_ok = dopt Opt_AllowUndecidableInstances dflags
968 -------------------------
969 tyvar_head ty -- Haskell 98 allows predicates of form
970 | tcIsTyVarTy ty = True -- C (a ty1 .. tyn)
971 | otherwise -- where a is a type variable
972 = case tcSplitAppTy_maybe ty of
973 Just (ty, _) -> tyvar_head ty
980 is ambiguous if P contains generic variables
981 (i.e. one of the Vs) that are not mentioned in tau
983 However, we need to take account of functional dependencies
984 when we speak of 'mentioned in tau'. Example:
985 class C a b | a -> b where ...
987 forall x y. (C x y) => x
988 is not ambiguous because x is mentioned and x determines y
990 NB; the ambiguity check is only used for *user* types, not for types
991 coming from inteface files. The latter can legitimately have
992 ambiguous types. Example
994 class S a where s :: a -> (Int,Int)
995 instance S Char where s _ = (1,1)
996 f:: S a => [a] -> Int -> (Int,Int)
997 f (_::[a]) x = (a*x,b)
998 where (a,b) = s (undefined::a)
1000 Here the worker for f gets the type
1001 fw :: forall a. S a => Int -> (# Int, Int #)
1003 If the list of tv_names is empty, we have a monotype, and then we
1004 don't need to check for ambiguity either, because the test can't fail
1008 checkAmbiguity :: [TyVar] -> ThetaType -> TyVarSet -> TcM ()
1009 checkAmbiguity forall_tyvars theta tau_tyvars
1010 = mappM_ complain (filter is_ambig theta)
1012 complain pred = addErrTc (ambigErr pred)
1013 extended_tau_vars = grow theta tau_tyvars
1015 -- Only a *class* predicate can give rise to ambiguity
1016 -- An *implicit parameter* cannot. For example:
1017 -- foo :: (?x :: [a]) => Int
1019 -- is fine. The call site will suppply a particular 'x'
1020 is_ambig pred = isClassPred pred &&
1021 any ambig_var (varSetElems (tyVarsOfPred pred))
1023 ambig_var ct_var = (ct_var `elem` forall_tyvars) &&
1024 not (ct_var `elemVarSet` extended_tau_vars)
1027 = sep [ptext SLIT("Ambiguous constraint") <+> quotes (pprPred pred),
1028 nest 4 (ptext SLIT("At least one of the forall'd type variables mentioned by the constraint") $$
1029 ptext SLIT("must be reachable from the type after the '=>'"))]
1032 In addition, GHC insists that at least one type variable
1033 in each constraint is in V. So we disallow a type like
1034 forall a. Eq b => b -> b
1035 even in a scope where b is in scope.
1038 checkFreeness forall_tyvars theta
1039 = do { gla_exts <- doptM Opt_GlasgowExts
1040 ; if gla_exts then return () -- New! Oct06
1041 else mappM_ complain (filter is_free theta) }
1043 is_free pred = not (isIPPred pred)
1044 && not (any bound_var (varSetElems (tyVarsOfPred pred)))
1045 bound_var ct_var = ct_var `elem` forall_tyvars
1046 complain pred = addErrTc (freeErr pred)
1049 = sep [ptext SLIT("All of the type variables in the constraint") <+> quotes (pprPred pred) <+>
1050 ptext SLIT("are already in scope"),
1051 nest 4 (ptext SLIT("(at least one must be universally quantified here)"))
1056 checkThetaCtxt ctxt theta
1057 = vcat [ptext SLIT("In the context:") <+> pprTheta theta,
1058 ptext SLIT("While checking") <+> pprSourceTyCtxt ctxt ]
1060 badPredTyErr sty = ptext SLIT("Illegal constraint") <+> pprPred sty
1061 predTyVarErr pred = sep [ptext SLIT("Non type-variable argument"),
1062 nest 2 (ptext SLIT("in the constraint:") <+> pprPred pred)]
1063 dupPredWarn dups = ptext SLIT("Duplicate constraint(s):") <+> pprWithCommas pprPred (map head dups)
1065 arityErr kind name n m
1066 = hsep [ text kind, quotes (ppr name), ptext SLIT("should have"),
1067 n_arguments <> comma, text "but has been given", int m]
1069 n_arguments | n == 0 = ptext SLIT("no arguments")
1070 | n == 1 = ptext SLIT("1 argument")
1071 | True = hsep [int n, ptext SLIT("arguments")]
1075 %************************************************************************
1077 \subsection{Checking for a decent instance head type}
1079 %************************************************************************
1081 @checkValidInstHead@ checks the type {\em and} its syntactic constraints:
1082 it must normally look like: @instance Foo (Tycon a b c ...) ...@
1084 The exceptions to this syntactic checking: (1)~if the @GlasgowExts@
1085 flag is on, or (2)~the instance is imported (they must have been
1086 compiled elsewhere). In these cases, we let them go through anyway.
1088 We can also have instances for functions: @instance Foo (a -> b) ...@.
1091 checkValidInstHead :: Type -> TcM (Class, [TcType])
1093 checkValidInstHead ty -- Should be a source type
1094 = case tcSplitPredTy_maybe ty of {
1095 Nothing -> failWithTc (instTypeErr (ppr ty) empty) ;
1098 case getClassPredTys_maybe pred of {
1099 Nothing -> failWithTc (instTypeErr (pprPred pred) empty) ;
1102 getDOpts `thenM` \ dflags ->
1103 mappM_ check_arg_type tys `thenM_`
1104 check_inst_head dflags clas tys `thenM_`
1108 check_inst_head dflags clas tys
1109 -- If GlasgowExts then check at least one isn't a type variable
1110 | dopt Opt_GlasgowExts dflags
1111 = mapM_ check_one tys
1113 -- WITH HASKELL 98, MUST HAVE C (T a b c)
1115 = checkTc (isSingleton tys && tcValidInstHeadTy first_ty)
1116 (instTypeErr (pprClassPred clas tys) head_shape_msg)
1119 (first_ty : _) = tys
1121 head_shape_msg = parens (text "The instance type must be of form (T a b c)" $$
1122 text "where T is not a synonym, and a,b,c are distinct type variables")
1124 -- For now, I only allow tau-types (not polytypes) in
1125 -- the head of an instance decl.
1126 -- E.g. instance C (forall a. a->a) is rejected
1127 -- One could imagine generalising that, but I'm not sure
1128 -- what all the consequences might be
1129 check_one ty = do { check_tau_type (Rank 0) UT_NotOk ty
1130 ; checkTc (not (isUnLiftedType ty)) (unliftedArgErr ty) }
1132 instTypeErr pp_ty msg
1133 = sep [ptext SLIT("Illegal instance declaration for") <+> quotes pp_ty,
1138 %************************************************************************
1140 \subsection{Checking instance for termination}
1142 %************************************************************************
1146 checkValidInstance :: [TyVar] -> ThetaType -> Class -> [TcType] -> TcM ()
1147 checkValidInstance tyvars theta clas inst_tys
1148 = do { gla_exts <- doptM Opt_GlasgowExts
1149 ; undecidable_ok <- doptM Opt_AllowUndecidableInstances
1151 ; checkValidTheta InstThetaCtxt theta
1152 ; checkAmbiguity tyvars theta (tyVarsOfTypes inst_tys)
1154 -- Check that instance inference will terminate (if we care)
1155 -- For Haskell 98, checkValidTheta has already done that
1156 ; when (gla_exts && not undecidable_ok) $
1157 mapM_ failWithTc (checkInstTermination inst_tys theta)
1159 -- The Coverage Condition
1160 ; checkTc (undecidable_ok || checkInstCoverage clas inst_tys)
1161 (instTypeErr (pprClassPred clas inst_tys) msg)
1164 msg = parens (vcat [ptext SLIT("the Coverage Condition fails for one of the functional dependencies;"),
1168 Termination test: each assertion in the context satisfies
1169 (1) no variable has more occurrences in the assertion than in the head, and
1170 (2) the assertion has fewer constructors and variables (taken together
1171 and counting repetitions) than the head.
1172 This is only needed with -fglasgow-exts, as Haskell 98 restrictions
1173 (which have already been checked) guarantee termination.
1175 The underlying idea is that
1177 for any ground substitution, each assertion in the
1178 context has fewer type constructors than the head.
1182 checkInstTermination :: [TcType] -> ThetaType -> [Message]
1183 checkInstTermination tys theta
1184 = mapCatMaybes check theta
1187 size = sizeTypes tys
1189 | not (null (fvPred pred \\ fvs))
1190 = Just (predUndecErr pred nomoreMsg $$ parens undecidableMsg)
1191 | sizePred pred >= size
1192 = Just (predUndecErr pred smallerMsg $$ parens undecidableMsg)
1196 predUndecErr pred msg = sep [msg,
1197 nest 2 (ptext SLIT("in the constraint:") <+> pprPred pred)]
1199 nomoreMsg = ptext SLIT("Variable occurs more often in a constraint than in the instance head")
1200 smallerMsg = ptext SLIT("Constraint is no smaller than the instance head")
1201 undecidableMsg = ptext SLIT("Use -fallow-undecidable-instances to permit this")
1203 -- Free variables of a type, retaining repetitions, and expanding synonyms
1204 fvType :: Type -> [TyVar]
1205 fvType ty | Just exp_ty <- tcView ty = fvType exp_ty
1206 fvType (TyVarTy tv) = [tv]
1207 fvType (TyConApp _ tys) = fvTypes tys
1208 fvType (NoteTy _ ty) = fvType ty
1209 fvType (PredTy pred) = fvPred pred
1210 fvType (FunTy arg res) = fvType arg ++ fvType res
1211 fvType (AppTy fun arg) = fvType fun ++ fvType arg
1212 fvType (ForAllTy tyvar ty) = filter (/= tyvar) (fvType ty)
1214 fvTypes :: [Type] -> [TyVar]
1215 fvTypes tys = concat (map fvType tys)
1217 fvPred :: PredType -> [TyVar]
1218 fvPred (ClassP _ tys') = fvTypes tys'
1219 fvPred (IParam _ ty) = fvType ty
1220 fvPred (EqPred ty1 ty2) = fvType ty1 ++ fvType ty2
1222 -- Size of a type: the number of variables and constructors
1223 sizeType :: Type -> Int
1224 sizeType ty | Just exp_ty <- tcView ty = sizeType exp_ty
1225 sizeType (TyVarTy _) = 1
1226 sizeType (TyConApp _ tys) = sizeTypes tys + 1
1227 sizeType (NoteTy _ ty) = sizeType ty
1228 sizeType (PredTy pred) = sizePred pred
1229 sizeType (FunTy arg res) = sizeType arg + sizeType res + 1
1230 sizeType (AppTy fun arg) = sizeType fun + sizeType arg
1231 sizeType (ForAllTy _ ty) = sizeType ty
1233 sizeTypes :: [Type] -> Int
1234 sizeTypes xs = sum (map sizeType xs)
1236 sizePred :: PredType -> Int
1237 sizePred (ClassP _ tys') = sizeTypes tys'
1238 sizePred (IParam _ ty) = sizeType ty
1239 sizePred (EqPred ty1 ty2) = sizeType ty1 + sizeType ty2