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,
44 checkInstTermination, checkValidTypeInst, checkTyFamFreeness,
47 --------------------------------
49 zonkType, zonkTcPredType,
50 zonkTcTyVar, zonkTcTyVars, zonkTcTyVarsAndFV,
51 zonkQuantifiedTyVar, zonkQuantifiedTyVars,
52 zonkTcType, zonkTcTypes, zonkTcClassConstraints, zonkTcThetaType,
53 zonkTcKindToKind, zonkTcKind, zonkTopTyVar,
55 readKindVar, writeKindVar
58 #include "HsVersions.h"
70 import TcRnMonad -- TcType, amongst others
83 import Control.Monad ( when, unless )
84 import Data.List ( (\\) )
88 %************************************************************************
90 Instantiation in general
92 %************************************************************************
95 tcInstType :: ([TyVar] -> TcM [TcTyVar]) -- How to instantiate the type variables
96 -> TcType -- Type to instantiate
97 -> TcM ([TcTyVar], TcThetaType, TcType) -- Result
98 tcInstType inst_tyvars ty
99 = case tcSplitForAllTys ty of
100 ([], rho) -> let -- There may be overloading despite no type variables;
101 -- (?x :: Int) => Int -> Int
102 (theta, tau) = tcSplitPhiTy rho
104 return ([], theta, tau)
106 (tyvars, rho) -> do { tyvars' <- inst_tyvars tyvars
108 ; let tenv = zipTopTvSubst tyvars (mkTyVarTys tyvars')
109 -- Either the tyvars are freshly made, by inst_tyvars,
110 -- or (in the call from tcSkolSigType) any nested foralls
111 -- have different binders. Either way, zipTopTvSubst is ok
113 ; let (theta, tau) = tcSplitPhiTy (substTy tenv rho)
114 ; return (tyvars', theta, tau) }
118 %************************************************************************
122 %************************************************************************
125 newCoVars :: [(TcType,TcType)] -> TcM [CoVar]
127 = do { us <- newUniqueSupply
128 ; return [ mkCoVar (mkSysTvName uniq FSLIT("co"))
130 | ((ty1,ty2), uniq) <- spec `zip` uniqsFromSupply us] }
132 newKindVar :: TcM TcKind
133 newKindVar = do { uniq <- newUnique
134 ; ref <- newMutVar Flexi
135 ; return (mkTyVarTy (mkKindVar uniq ref)) }
137 newKindVars :: Int -> TcM [TcKind]
138 newKindVars n = mappM (\ _ -> newKindVar) (nOfThem n ())
142 %************************************************************************
144 SkolemTvs (immutable)
146 %************************************************************************
149 mkSkolTyVar :: Name -> Kind -> SkolemInfo -> TcTyVar
150 mkSkolTyVar name kind info = mkTcTyVar name kind (SkolemTv info)
152 tcSkolSigType :: SkolemInfo -> Type -> TcM ([TcTyVar], TcThetaType, TcType)
153 -- Instantiate a type signature with skolem constants, but
154 -- do *not* give them fresh names, because we want the name to
155 -- be in the type environment -- it is lexically scoped.
156 tcSkolSigType info ty = tcInstType (\tvs -> return (tcSkolSigTyVars info tvs)) ty
158 tcSkolSigTyVars :: SkolemInfo -> [TyVar] -> [TcTyVar]
159 -- Make skolem constants, but do *not* give them new names, as above
160 tcSkolSigTyVars info tyvars = [ mkSkolTyVar (tyVarName tv) (tyVarKind tv) info
163 tcInstSkolTyVar :: SkolemInfo -> Maybe SrcSpan -> TyVar -> TcM TcTyVar
164 -- Instantiate the tyvar, using
165 -- * the occ-name and kind of the supplied tyvar,
166 -- * the unique from the monad,
167 -- * the location either from the tyvar (mb_loc = Nothing)
168 -- or from mb_loc (Just loc)
169 tcInstSkolTyVar info mb_loc tyvar
170 = do { uniq <- newUnique
171 ; let old_name = tyVarName tyvar
172 kind = tyVarKind tyvar
173 loc = mb_loc `orElse` getSrcSpan old_name
174 new_name = mkInternalName uniq (nameOccName old_name) loc
175 ; return (mkSkolTyVar new_name kind info) }
177 tcInstSkolTyVars :: SkolemInfo -> [TyVar] -> TcM [TcTyVar]
178 -- Get the location from the monad
179 tcInstSkolTyVars info tyvars
180 = do { span <- getSrcSpanM
181 ; mapM (tcInstSkolTyVar info (Just span)) tyvars }
183 tcInstSkolType :: SkolemInfo -> TcType -> TcM ([TcTyVar], TcThetaType, TcType)
184 -- Instantiate a type with fresh skolem constants
185 -- Binding location comes from the monad
186 tcInstSkolType info ty = tcInstType (tcInstSkolTyVars info) ty
190 %************************************************************************
192 MetaTvs (meta type variables; mutable)
194 %************************************************************************
197 newMetaTyVar :: BoxInfo -> Kind -> TcM TcTyVar
198 -- Make a new meta tyvar out of thin air
199 newMetaTyVar box_info kind
200 = do { uniq <- newUnique
201 ; ref <- newMutVar Flexi
202 ; let name = mkSysTvName uniq fs
203 fs = case box_info of
206 SigTv _ -> FSLIT("a")
207 -- We give BoxTv and TauTv the same string, because
208 -- otherwise we get user-visible differences in error
209 -- messages, which are confusing. If you want to see
210 -- the box_info of each tyvar, use -dppr-debug
211 ; return (mkTcTyVar name kind (MetaTv box_info ref)) }
213 instMetaTyVar :: BoxInfo -> TyVar -> TcM TcTyVar
214 -- Make a new meta tyvar whose Name and Kind
215 -- come from an existing TyVar
216 instMetaTyVar box_info tyvar
217 = do { uniq <- newUnique
218 ; ref <- newMutVar Flexi
219 ; let name = setNameUnique (tyVarName tyvar) uniq
220 kind = tyVarKind tyvar
221 ; return (mkTcTyVar name kind (MetaTv box_info ref)) }
223 readMetaTyVar :: TyVar -> TcM MetaDetails
224 readMetaTyVar tyvar = ASSERT2( isMetaTyVar tyvar, ppr tyvar )
225 readMutVar (metaTvRef tyvar)
227 writeMetaTyVar :: TcTyVar -> TcType -> TcM ()
229 writeMetaTyVar tyvar ty = writeMutVar (metaTvRef tyvar) (Indirect ty)
231 writeMetaTyVar tyvar ty
232 | not (isMetaTyVar tyvar)
233 = pprTrace "writeMetaTyVar" (ppr tyvar) $
237 = ASSERT( isMetaTyVar tyvar )
238 -- TOM: It should also work for coercions
239 -- ASSERT2( k2 `isSubKind` k1, (ppr tyvar <+> ppr k1) $$ (ppr ty <+> ppr k2) )
240 do { ASSERTM2( do { details <- readMetaTyVar tyvar; return (isFlexi details) }, ppr tyvar )
241 ; writeMutVar (metaTvRef tyvar) (Indirect ty) }
249 %************************************************************************
253 %************************************************************************
256 newFlexiTyVar :: Kind -> TcM TcTyVar
257 newFlexiTyVar kind = newMetaTyVar TauTv kind
259 newFlexiTyVarTy :: Kind -> TcM TcType
261 = newFlexiTyVar kind `thenM` \ tc_tyvar ->
262 returnM (TyVarTy tc_tyvar)
264 newFlexiTyVarTys :: Int -> Kind -> TcM [TcType]
265 newFlexiTyVarTys n kind = mappM newFlexiTyVarTy (nOfThem n kind)
267 tcInstTyVar :: TyVar -> TcM TcTyVar
268 -- Instantiate with a META type variable
269 tcInstTyVar tyvar = instMetaTyVar TauTv tyvar
271 tcInstTyVars :: [TyVar] -> TcM ([TcTyVar], [TcType], TvSubst)
272 -- Instantiate with META type variables
274 = do { tc_tvs <- mapM tcInstTyVar tyvars
275 ; let tys = mkTyVarTys tc_tvs
276 ; returnM (tc_tvs, tys, zipTopTvSubst tyvars tys) }
277 -- Since the tyvars are freshly made,
278 -- they cannot possibly be captured by
279 -- any existing for-alls. Hence zipTopTvSubst
283 %************************************************************************
287 %************************************************************************
290 tcInstSigTyVars :: Bool -> SkolemInfo -> [TyVar] -> TcM [TcTyVar]
291 -- Instantiate with skolems or meta SigTvs; depending on use_skols
292 -- Always take location info from the supplied tyvars
293 tcInstSigTyVars use_skols skol_info tyvars
295 = mapM (tcInstSkolTyVar skol_info Nothing) tyvars
298 = mapM (instMetaTyVar (SigTv skol_info)) tyvars
300 zonkSigTyVar :: TcTyVar -> TcM TcTyVar
302 | isSkolemTyVar sig_tv
303 = return sig_tv -- Happens in the call in TcBinds.checkDistinctTyVars
305 = ASSERT( isSigTyVar sig_tv )
306 do { ty <- zonkTcTyVar sig_tv
307 ; return (tcGetTyVar "zonkSigTyVar" ty) }
308 -- 'ty' is bound to be a type variable, because SigTvs
309 -- can only be unified with type variables
313 %************************************************************************
317 %************************************************************************
320 newBoxyTyVar :: Kind -> TcM BoxyTyVar
321 newBoxyTyVar kind = newMetaTyVar BoxTv kind
323 newBoxyTyVars :: [Kind] -> TcM [BoxyTyVar]
324 newBoxyTyVars kinds = mapM newBoxyTyVar kinds
326 newBoxyTyVarTys :: [Kind] -> TcM [BoxyType]
327 newBoxyTyVarTys kinds = do { tvs <- mapM newBoxyTyVar kinds; return (mkTyVarTys tvs) }
329 readFilledBox :: BoxyTyVar -> TcM TcType
330 -- Read the contents of the box, which should be filled in by now
331 readFilledBox box_tv = ASSERT( isBoxyTyVar box_tv )
332 do { cts <- readMetaTyVar box_tv
334 Flexi -> pprPanic "readFilledBox" (ppr box_tv)
335 Indirect ty -> return ty }
337 tcInstBoxyTyVar :: TyVar -> TcM BoxyTyVar
338 -- Instantiate with a BOXY type variable
339 tcInstBoxyTyVar tyvar = instMetaTyVar BoxTv tyvar
343 %************************************************************************
345 \subsection{Putting and getting mutable type variables}
347 %************************************************************************
349 But it's more fun to short out indirections on the way: If this
350 version returns a TyVar, then that TyVar is unbound. If it returns
351 any other type, then there might be bound TyVars embedded inside it.
353 We return Nothing iff the original box was unbound.
356 data LookupTyVarResult -- The result of a lookupTcTyVar call
357 = DoneTv TcTyVarDetails -- SkolemTv or virgin MetaTv
360 lookupTcTyVar :: TcTyVar -> TcM LookupTyVarResult
362 = ASSERT2( isTcTyVar tyvar, ppr tyvar )
364 SkolemTv _ -> return (DoneTv details)
365 MetaTv _ ref -> do { meta_details <- readMutVar ref
366 ; case meta_details of
367 Indirect ty -> return (IndirectTv ty)
368 Flexi -> return (DoneTv details) }
370 details = tcTyVarDetails tyvar
373 -- gaw 2004 We aren't shorting anything out anymore, at least for now
375 | not (isTcTyVar tyvar)
376 = pprTrace "getTcTyVar" (ppr tyvar) $
377 returnM (Just (mkTyVarTy tyvar))
380 = ASSERT2( isTcTyVar tyvar, ppr tyvar )
381 readMetaTyVar tyvar `thenM` \ maybe_ty ->
383 Just ty -> short_out ty `thenM` \ ty' ->
384 writeMetaTyVar tyvar (Just ty') `thenM_`
387 Nothing -> returnM Nothing
389 short_out :: TcType -> TcM TcType
390 short_out ty@(TyVarTy tyvar)
391 | not (isTcTyVar tyvar)
395 = readMetaTyVar tyvar `thenM` \ maybe_ty ->
397 Just ty' -> short_out ty' `thenM` \ ty' ->
398 writeMetaTyVar tyvar (Just ty') `thenM_`
403 short_out other_ty = returnM other_ty
408 %************************************************************************
410 \subsection{Zonking -- the exernal interfaces}
412 %************************************************************************
414 ----------------- Type variables
417 zonkTcTyVars :: [TcTyVar] -> TcM [TcType]
418 zonkTcTyVars tyvars = mappM zonkTcTyVar tyvars
420 zonkTcTyVarsAndFV :: [TcTyVar] -> TcM TcTyVarSet
421 zonkTcTyVarsAndFV tyvars = mappM zonkTcTyVar tyvars `thenM` \ tys ->
422 returnM (tyVarsOfTypes tys)
424 zonkTcTyVar :: TcTyVar -> TcM TcType
425 zonkTcTyVar tyvar = ASSERT2( isTcTyVar tyvar, ppr tyvar)
426 zonk_tc_tyvar (\ tv -> returnM (TyVarTy tv)) tyvar
429 ----------------- Types
432 zonkTcType :: TcType -> TcM TcType
433 zonkTcType ty = zonkType (\ tv -> returnM (TyVarTy tv)) ty
435 zonkTcTypes :: [TcType] -> TcM [TcType]
436 zonkTcTypes tys = mappM zonkTcType tys
438 zonkTcClassConstraints cts = mappM zonk cts
439 where zonk (clas, tys)
440 = zonkTcTypes tys `thenM` \ new_tys ->
441 returnM (clas, new_tys)
443 zonkTcThetaType :: TcThetaType -> TcM TcThetaType
444 zonkTcThetaType theta = mappM zonkTcPredType theta
446 zonkTcPredType :: TcPredType -> TcM TcPredType
447 zonkTcPredType (ClassP c ts)
448 = zonkTcTypes ts `thenM` \ new_ts ->
449 returnM (ClassP c new_ts)
450 zonkTcPredType (IParam n t)
451 = zonkTcType t `thenM` \ new_t ->
452 returnM (IParam n new_t)
453 zonkTcPredType (EqPred t1 t2)
454 = zonkTcType t1 `thenM` \ new_t1 ->
455 zonkTcType t2 `thenM` \ new_t2 ->
456 returnM (EqPred new_t1 new_t2)
459 ------------------- These ...ToType, ...ToKind versions
460 are used at the end of type checking
463 zonkTopTyVar :: TcTyVar -> TcM TcTyVar
464 -- zonkTopTyVar is used, at the top level, on any un-instantiated meta type variables
465 -- to default the kind of ? and ?? etc to *. This is important to ensure that
466 -- instance declarations match. For example consider
467 -- instance Show (a->b)
468 -- foo x = show (\_ -> True)
469 -- Then we'll get a constraint (Show (p ->q)) where p has argTypeKind (printed ??),
470 -- and that won't match the typeKind (*) in the instance decl.
472 -- Because we are at top level, no further constraints are going to affect these
473 -- type variables, so it's time to do it by hand. However we aren't ready
474 -- to default them fully to () or whatever, because the type-class defaulting
475 -- rules have yet to run.
478 | k `eqKind` default_k = return tv
480 = do { tv' <- newFlexiTyVar default_k
481 ; writeMetaTyVar tv (mkTyVarTy tv')
485 default_k = defaultKind k
487 zonkQuantifiedTyVars :: [TcTyVar] -> TcM [TyVar]
488 zonkQuantifiedTyVars = mappM zonkQuantifiedTyVar
490 zonkQuantifiedTyVar :: TcTyVar -> TcM TyVar
491 -- zonkQuantifiedTyVar is applied to the a TcTyVar when quantifying over it.
493 -- The quantified type variables often include meta type variables
494 -- we want to freeze them into ordinary type variables, and
495 -- default their kind (e.g. from OpenTypeKind to TypeKind)
496 -- -- see notes with Kind.defaultKind
497 -- The meta tyvar is updated to point to the new regular TyVar. Now any
498 -- bound occurences of the original type variable will get zonked to
499 -- the immutable version.
501 -- We leave skolem TyVars alone; they are immutable.
502 zonkQuantifiedTyVar tv
503 | ASSERT( isTcTyVar tv )
504 isSkolemTyVar tv = return tv
505 -- It might be a skolem type variable,
506 -- for example from a user type signature
508 | otherwise -- It's a meta-type-variable
509 = do { details <- readMetaTyVar tv
511 -- Create the new, frozen, regular type variable
512 ; let final_kind = defaultKind (tyVarKind tv)
513 final_tv = mkTyVar (tyVarName tv) final_kind
515 -- Bind the meta tyvar to the new tyvar
517 Indirect ty -> WARN( True, ppr tv $$ ppr ty )
519 -- [Sept 04] I don't think this should happen
520 -- See note [Silly Type Synonym]
522 Flexi -> writeMetaTyVar tv (mkTyVarTy final_tv)
524 -- Return the new tyvar
528 [Silly Type Synonyms]
531 type C u a = u -- Note 'a' unused
533 foo :: (forall a. C u a -> C u a) -> u
537 bar = foo (\t -> t + t)
539 * From the (\t -> t+t) we get type {Num d} => d -> d
542 * Now unify with type of foo's arg, and we get:
543 {Num (C d a)} => C d a -> C d a
546 * Now abstract over the 'a', but float out the Num (C d a) constraint
547 because it does not 'really' mention a. (see exactTyVarsOfType)
548 The arg to foo becomes
551 * So we get a dict binding for Num (C d a), which is zonked to give
553 [Note Sept 04: now that we are zonking quantified type variables
554 on construction, the 'a' will be frozen as a regular tyvar on
555 quantification, so the floated dict will still have type (C d a).
556 Which renders this whole note moot; happily!]
558 * Then the /\a abstraction has a zonked 'a' in it.
560 All very silly. I think its harmless to ignore the problem. We'll end up with
561 a /\a in the final result but all the occurrences of a will be zonked to ()
564 %************************************************************************
566 \subsection{Zonking -- the main work-horses: zonkType, zonkTyVar}
568 %* For internal use only! *
570 %************************************************************************
573 -- For unbound, mutable tyvars, zonkType uses the function given to it
574 -- For tyvars bound at a for-all, zonkType zonks them to an immutable
575 -- type variable and zonks the kind too
577 zonkType :: (TcTyVar -> TcM Type) -- What to do with unbound mutable type variables
578 -- see zonkTcType, and zonkTcTypeToType
581 zonkType unbound_var_fn ty
584 go (NoteTy _ ty2) = go ty2 -- Discard free-tyvar annotations
586 go (TyConApp tc tys) = mappM go tys `thenM` \ tys' ->
587 returnM (TyConApp tc tys')
589 go (PredTy p) = go_pred p `thenM` \ p' ->
592 go (FunTy arg res) = go arg `thenM` \ arg' ->
593 go res `thenM` \ res' ->
594 returnM (FunTy arg' res')
596 go (AppTy fun arg) = go fun `thenM` \ fun' ->
597 go arg `thenM` \ arg' ->
598 returnM (mkAppTy fun' arg')
599 -- NB the mkAppTy; we might have instantiated a
600 -- type variable to a type constructor, so we need
601 -- to pull the TyConApp to the top.
603 -- The two interesting cases!
604 go (TyVarTy tyvar) | isTcTyVar tyvar = zonk_tc_tyvar unbound_var_fn tyvar
605 | otherwise = return (TyVarTy tyvar)
606 -- Ordinary (non Tc) tyvars occur inside quantified types
608 go (ForAllTy tyvar ty) = ASSERT( isImmutableTyVar tyvar )
609 go ty `thenM` \ ty' ->
610 returnM (ForAllTy tyvar ty')
612 go_pred (ClassP c tys) = mappM go tys `thenM` \ tys' ->
613 returnM (ClassP c tys')
614 go_pred (IParam n ty) = go ty `thenM` \ ty' ->
615 returnM (IParam n ty')
616 go_pred (EqPred ty1 ty2) = go ty1 `thenM` \ ty1' ->
617 go ty2 `thenM` \ ty2' ->
618 returnM (EqPred ty1' ty2')
620 zonk_tc_tyvar :: (TcTyVar -> TcM Type) -- What to do for an unbound mutable variable
621 -> TcTyVar -> TcM TcType
622 zonk_tc_tyvar unbound_var_fn tyvar
623 | not (isMetaTyVar tyvar) -- Skolems
624 = returnM (TyVarTy tyvar)
626 | otherwise -- Mutables
627 = do { cts <- readMetaTyVar tyvar
629 Flexi -> unbound_var_fn tyvar -- Unbound meta type variable
630 Indirect ty -> zonkType unbound_var_fn ty }
635 %************************************************************************
639 %************************************************************************
642 readKindVar :: KindVar -> TcM (MetaDetails)
643 writeKindVar :: KindVar -> TcKind -> TcM ()
644 readKindVar kv = readMutVar (kindVarRef kv)
645 writeKindVar kv val = writeMutVar (kindVarRef kv) (Indirect val)
648 zonkTcKind :: TcKind -> TcM TcKind
649 zonkTcKind k = zonkTcType k
652 zonkTcKindToKind :: TcKind -> TcM Kind
653 -- When zonking a TcKind to a kind, we need to instantiate kind variables,
654 -- Haskell specifies that * is to be used, so we follow that.
655 zonkTcKindToKind k = zonkType (\ _ -> return liftedTypeKind) k
658 %************************************************************************
660 \subsection{Checking a user type}
662 %************************************************************************
664 When dealing with a user-written type, we first translate it from an HsType
665 to a Type, performing kind checking, and then check various things that should
666 be true about it. We don't want to perform these checks at the same time
667 as the initial translation because (a) they are unnecessary for interface-file
668 types and (b) when checking a mutually recursive group of type and class decls,
669 we can't "look" at the tycons/classes yet. Also, the checks are are rather
670 diverse, and used to really mess up the other code.
672 One thing we check for is 'rank'.
674 Rank 0: monotypes (no foralls)
675 Rank 1: foralls at the front only, Rank 0 inside
676 Rank 2: foralls at the front, Rank 1 on left of fn arrow,
678 basic ::= tyvar | T basic ... basic
680 r2 ::= forall tvs. cxt => r2a
681 r2a ::= r1 -> r2a | basic
682 r1 ::= forall tvs. cxt => r0
683 r0 ::= r0 -> r0 | basic
685 Another thing is to check that type synonyms are saturated.
686 This might not necessarily show up in kind checking.
688 data T k = MkT (k Int)
693 checkValidType :: UserTypeCtxt -> Type -> TcM ()
694 -- Checks that the type is valid for the given context
695 checkValidType ctxt ty
696 = traceTc (text "checkValidType" <+> ppr ty) `thenM_`
697 doptM Opt_UnboxedTuples `thenM` \ unboxed ->
698 doptM Opt_Rank2Types `thenM` \ rank2 ->
699 doptM Opt_RankNTypes `thenM` \ rankn ->
700 doptM Opt_PolymorphicComponents `thenM` \ polycomp ->
702 rank | rankn = Arbitrary
705 = case ctxt of -- Haskell 98
707 LamPatSigCtxt -> Rank 0
708 BindPatSigCtxt -> Rank 0
709 DefaultDeclCtxt-> Rank 0
711 TySynCtxt _ -> Rank 0
712 ExprSigCtxt -> Rank 1
713 FunSigCtxt _ -> Rank 1
714 ConArgCtxt _ -> if polycomp
716 -- We are given the type of the entire
717 -- constructor, hence rank 1
719 ForSigCtxt _ -> Rank 1
720 SpecInstCtxt -> Rank 1
722 actual_kind = typeKind ty
724 kind_ok = case ctxt of
725 TySynCtxt _ -> True -- Any kind will do
726 ResSigCtxt -> isSubOpenTypeKind actual_kind
727 ExprSigCtxt -> isSubOpenTypeKind actual_kind
728 GenPatCtxt -> isLiftedTypeKind actual_kind
729 ForSigCtxt _ -> isLiftedTypeKind actual_kind
730 other -> isSubArgTypeKind actual_kind
732 ubx_tup = case ctxt of
733 TySynCtxt _ | unboxed -> UT_Ok
734 ExprSigCtxt | unboxed -> UT_Ok
737 -- Check that the thing has kind Type, and is lifted if necessary
738 checkTc kind_ok (kindErr actual_kind) `thenM_`
740 -- Check the internal validity of the type itself
741 check_poly_type rank ubx_tup ty `thenM_`
743 traceTc (text "checkValidType done" <+> ppr ty)
748 data Rank = Rank Int | Arbitrary
750 decRank :: Rank -> Rank
751 decRank Arbitrary = Arbitrary
752 decRank (Rank n) = Rank (n-1)
754 ----------------------------------------
755 data UbxTupFlag = UT_Ok | UT_NotOk
756 -- The "Ok" version means "ok if -fglasgow-exts is on"
758 ----------------------------------------
759 check_poly_type :: Rank -> UbxTupFlag -> Type -> TcM ()
760 check_poly_type (Rank 0) ubx_tup ty
761 = check_tau_type (Rank 0) ubx_tup ty
763 check_poly_type rank ubx_tup ty
764 | null tvs && null theta
765 = check_tau_type rank ubx_tup ty
767 = do { check_valid_theta SigmaCtxt theta
768 ; check_poly_type rank ubx_tup tau -- Allow foralls to right of arrow
769 ; checkFreeness tvs theta
770 ; checkAmbiguity tvs theta (tyVarsOfType tau) }
772 (tvs, theta, tau) = tcSplitSigmaTy ty
774 ----------------------------------------
775 check_arg_type :: Type -> TcM ()
776 -- The sort of type that can instantiate a type variable,
777 -- or be the argument of a type constructor.
778 -- Not an unboxed tuple, but now *can* be a forall (since impredicativity)
779 -- Other unboxed types are very occasionally allowed as type
780 -- arguments depending on the kind of the type constructor
782 -- For example, we want to reject things like:
784 -- instance Ord a => Ord (forall s. T s a)
786 -- g :: T s (forall b.b)
788 -- NB: unboxed tuples can have polymorphic or unboxed args.
789 -- This happens in the workers for functions returning
790 -- product types with polymorphic components.
791 -- But not in user code.
792 -- Anyway, they are dealt with by a special case in check_tau_type
795 = check_poly_type Arbitrary UT_NotOk ty `thenM_`
796 checkTc (not (isUnLiftedType ty)) (unliftedArgErr ty)
798 ----------------------------------------
799 check_tau_type :: Rank -> UbxTupFlag -> Type -> TcM ()
800 -- Rank is allowed rank for function args
801 -- No foralls otherwise
803 check_tau_type rank ubx_tup ty@(ForAllTy _ _) = failWithTc (forAllTyErr ty)
804 check_tau_type rank ubx_tup ty@(FunTy (PredTy _) _) = failWithTc (forAllTyErr ty)
805 -- Reject e.g. (Maybe (?x::Int => Int)), with a decent error message
807 -- Naked PredTys don't usually show up, but they can as a result of
808 -- {-# SPECIALISE instance Ord Char #-}
809 -- The Right Thing would be to fix the way that SPECIALISE instance pragmas
810 -- are handled, but the quick thing is just to permit PredTys here.
811 check_tau_type rank ubx_tup (PredTy sty) = getDOpts `thenM` \ dflags ->
812 check_pred_ty dflags TypeCtxt sty
814 check_tau_type rank ubx_tup (TyVarTy _) = returnM ()
815 check_tau_type rank ubx_tup ty@(FunTy arg_ty res_ty)
816 = check_poly_type (decRank rank) UT_NotOk arg_ty `thenM_`
817 check_poly_type rank UT_Ok res_ty
819 check_tau_type rank ubx_tup (AppTy ty1 ty2)
820 = check_arg_type ty1 `thenM_` check_arg_type ty2
822 check_tau_type rank ubx_tup (NoteTy other_note ty)
823 = check_tau_type rank ubx_tup ty
825 check_tau_type rank ubx_tup ty@(TyConApp tc tys)
827 = do { -- It's OK to have an *over-applied* type synonym
828 -- data Tree a b = ...
829 -- type Foo a = Tree [a]
830 -- f :: Foo a b -> ...
832 Just ty' -> check_tau_type rank ubx_tup ty' -- Check expansion
833 Nothing -> unless (isOpenTyCon tc -- No expansion if open
834 && tyConArity tc <= length tys) $
837 ; ok <- doptM Opt_PartiallyAppliedClosedTypeSynonyms
838 ; if ok && not (isOpenTyCon tc) then
839 -- Don't check the type arguments of *closed* synonyms.
840 -- This allows us to instantiate a synonym defn with a
841 -- for-all type, or with a partially-applied type synonym.
842 -- e.g. type T a b = a
845 -- Here, T is partially applied, so it's illegal in H98.
846 -- But if you expand S first, then T we get just
851 -- For H98, do check the type args
852 mappM_ check_arg_type tys
855 | isUnboxedTupleTyCon tc
856 = doptM Opt_UnboxedTuples `thenM` \ ub_tuples_allowed ->
857 checkTc (ubx_tup_ok ub_tuples_allowed) ubx_tup_msg `thenM_`
858 mappM_ (check_tau_type (Rank 0) UT_Ok) tys
859 -- Args are allowed to be unlifted, or
860 -- more unboxed tuples, so can't use check_arg_ty
863 = mappM_ check_arg_type tys
866 ubx_tup_ok ub_tuples_allowed = case ubx_tup of { UT_Ok -> ub_tuples_allowed; other -> False }
869 tc_arity = tyConArity tc
871 arity_msg = arityErr "Type synonym" (tyConName tc) tc_arity n_args
872 ubx_tup_msg = ubxArgTyErr ty
874 ----------------------------------------
875 forAllTyErr ty = ptext SLIT("Illegal polymorphic or qualified type:") <+> ppr ty
876 unliftedArgErr ty = ptext SLIT("Illegal unlifted type argument:") <+> ppr ty
877 ubxArgTyErr ty = ptext SLIT("Illegal unboxed tuple type as function argument:") <+> ppr ty
878 kindErr kind = ptext SLIT("Expecting an ordinary type, but found a type of kind") <+> ppr kind
883 %************************************************************************
885 \subsection{Checking a theta or source type}
887 %************************************************************************
890 -- Enumerate the contexts in which a "source type", <S>, can occur
894 -- or (N a) where N is a newtype
897 = ClassSCCtxt Name -- Superclasses of clas
898 -- class <S> => C a where ...
899 | SigmaCtxt -- Theta part of a normal for-all type
900 -- f :: <S> => a -> a
901 | DataTyCtxt Name -- Theta part of a data decl
902 -- data <S> => T a = MkT a
903 | TypeCtxt -- Source type in an ordinary type
905 | InstThetaCtxt -- Context of an instance decl
906 -- instance <S> => C [a] where ...
908 pprSourceTyCtxt (ClassSCCtxt c) = ptext SLIT("the super-classes of class") <+> quotes (ppr c)
909 pprSourceTyCtxt SigmaCtxt = ptext SLIT("the context of a polymorphic type")
910 pprSourceTyCtxt (DataTyCtxt tc) = ptext SLIT("the context of the data type declaration for") <+> quotes (ppr tc)
911 pprSourceTyCtxt InstThetaCtxt = ptext SLIT("the context of an instance declaration")
912 pprSourceTyCtxt TypeCtxt = ptext SLIT("the context of a type")
916 checkValidTheta :: SourceTyCtxt -> ThetaType -> TcM ()
917 checkValidTheta ctxt theta
918 = addErrCtxt (checkThetaCtxt ctxt theta) (check_valid_theta ctxt theta)
920 -------------------------
921 check_valid_theta ctxt []
923 check_valid_theta ctxt theta
924 = getDOpts `thenM` \ dflags ->
925 warnTc (notNull dups) (dupPredWarn dups) `thenM_`
926 mappM_ (check_pred_ty dflags ctxt) theta
928 (_,dups) = removeDups tcCmpPred theta
930 -------------------------
931 check_pred_ty dflags ctxt pred@(ClassP cls tys)
932 = do { -- Class predicates are valid in all contexts
933 ; checkTc (arity == n_tys) arity_err
935 -- Check the form of the argument types
936 ; mappM_ check_arg_type tys
937 ; checkTc (check_class_pred_tys dflags ctxt tys)
938 (predTyVarErr pred $$ how_to_allow)
941 class_name = className cls
942 arity = classArity cls
944 arity_err = arityErr "Class" class_name arity n_tys
945 how_to_allow = parens (ptext SLIT("Use -XFlexibleContexts to permit this"))
947 check_pred_ty dflags ctxt pred@(EqPred ty1 ty2)
948 = do { -- Equational constraints are valid in all contexts if type
949 -- families are permitted
950 ; checkTc (dopt Opt_TypeFamilies dflags) (eqPredTyErr pred)
952 -- Check the form of the argument types
953 ; check_eq_arg_type ty1
954 ; check_eq_arg_type ty2
957 check_eq_arg_type = check_poly_type (Rank 0) UT_NotOk
959 check_pred_ty dflags SigmaCtxt (IParam _ ty) = check_arg_type ty
960 -- Implicit parameters only allowed in type
961 -- signatures; not in instance decls, superclasses etc
962 -- The reason for not allowing implicit params in instances is a bit
964 -- If we allowed instance (?x::Int, Eq a) => Foo [a] where ...
965 -- then when we saw (e :: (?x::Int) => t) it would be unclear how to
966 -- discharge all the potential usas of the ?x in e. For example, a
967 -- constraint Foo [Int] might come out of e,and applying the
968 -- instance decl would show up two uses of ?x.
971 check_pred_ty dflags ctxt sty = failWithTc (badPredTyErr sty)
973 -------------------------
974 check_class_pred_tys dflags ctxt tys
976 TypeCtxt -> True -- {-# SPECIALISE instance Eq (T Int) #-} is fine
977 InstThetaCtxt -> flexible_contexts || undecidable_ok || all tcIsTyVarTy tys
978 -- Further checks on head and theta in
979 -- checkInstTermination
980 other -> flexible_contexts || all tyvar_head tys
982 flexible_contexts = dopt Opt_FlexibleContexts dflags
983 undecidable_ok = dopt Opt_UndecidableInstances dflags
985 -------------------------
986 tyvar_head ty -- Haskell 98 allows predicates of form
987 | tcIsTyVarTy ty = True -- C (a ty1 .. tyn)
988 | otherwise -- where a is a type variable
989 = case tcSplitAppTy_maybe ty of
990 Just (ty, _) -> tyvar_head ty
997 is ambiguous if P contains generic variables
998 (i.e. one of the Vs) that are not mentioned in tau
1000 However, we need to take account of functional dependencies
1001 when we speak of 'mentioned in tau'. Example:
1002 class C a b | a -> b where ...
1004 forall x y. (C x y) => x
1005 is not ambiguous because x is mentioned and x determines y
1007 NB; the ambiguity check is only used for *user* types, not for types
1008 coming from inteface files. The latter can legitimately have
1009 ambiguous types. Example
1011 class S a where s :: a -> (Int,Int)
1012 instance S Char where s _ = (1,1)
1013 f:: S a => [a] -> Int -> (Int,Int)
1014 f (_::[a]) x = (a*x,b)
1015 where (a,b) = s (undefined::a)
1017 Here the worker for f gets the type
1018 fw :: forall a. S a => Int -> (# Int, Int #)
1020 If the list of tv_names is empty, we have a monotype, and then we
1021 don't need to check for ambiguity either, because the test can't fail
1025 checkAmbiguity :: [TyVar] -> ThetaType -> TyVarSet -> TcM ()
1026 checkAmbiguity forall_tyvars theta tau_tyvars
1027 = mappM_ complain (filter is_ambig theta)
1029 complain pred = addErrTc (ambigErr pred)
1030 extended_tau_vars = grow theta tau_tyvars
1032 -- Only a *class* predicate can give rise to ambiguity
1033 -- An *implicit parameter* cannot. For example:
1034 -- foo :: (?x :: [a]) => Int
1036 -- is fine. The call site will suppply a particular 'x'
1037 is_ambig pred = isClassPred pred &&
1038 any ambig_var (varSetElems (tyVarsOfPred pred))
1040 ambig_var ct_var = (ct_var `elem` forall_tyvars) &&
1041 not (ct_var `elemVarSet` extended_tau_vars)
1044 = sep [ptext SLIT("Ambiguous constraint") <+> quotes (pprPred pred),
1045 nest 4 (ptext SLIT("At least one of the forall'd type variables mentioned by the constraint") $$
1046 ptext SLIT("must be reachable from the type after the '=>'"))]
1049 In addition, GHC insists that at least one type variable
1050 in each constraint is in V. So we disallow a type like
1051 forall a. Eq b => b -> b
1052 even in a scope where b is in scope.
1055 checkFreeness forall_tyvars theta
1056 = do { flexible_contexts <- doptM Opt_FlexibleContexts
1057 ; unless flexible_contexts $ mappM_ complain (filter is_free theta) }
1059 is_free pred = not (isIPPred pred)
1060 && not (any bound_var (varSetElems (tyVarsOfPred pred)))
1061 bound_var ct_var = ct_var `elem` forall_tyvars
1062 complain pred = addErrTc (freeErr pred)
1065 = sep [ptext SLIT("All of the type variables in the constraint") <+> quotes (pprPred pred) <+>
1066 ptext SLIT("are already in scope"),
1067 nest 4 (ptext SLIT("(at least one must be universally quantified here)"))
1072 checkThetaCtxt ctxt theta
1073 = vcat [ptext SLIT("In the context:") <+> pprTheta theta,
1074 ptext SLIT("While checking") <+> pprSourceTyCtxt ctxt ]
1076 badPredTyErr sty = ptext SLIT("Illegal constraint") <+> pprPred sty
1077 eqPredTyErr sty = ptext SLIT("Illegal equational constraint") <+> pprPred sty
1079 parens (ptext SLIT("Use -ftype-families to permit this"))
1080 predTyVarErr pred = sep [ptext SLIT("Non type-variable argument"),
1081 nest 2 (ptext SLIT("in the constraint:") <+> pprPred pred)]
1082 dupPredWarn dups = ptext SLIT("Duplicate constraint(s):") <+> pprWithCommas pprPred (map head dups)
1084 arityErr kind name n m
1085 = hsep [ text kind, quotes (ppr name), ptext SLIT("should have"),
1086 n_arguments <> comma, text "but has been given", int m]
1088 n_arguments | n == 0 = ptext SLIT("no arguments")
1089 | n == 1 = ptext SLIT("1 argument")
1090 | True = hsep [int n, ptext SLIT("arguments")]
1094 %************************************************************************
1096 \subsection{Checking for a decent instance head type}
1098 %************************************************************************
1100 @checkValidInstHead@ checks the type {\em and} its syntactic constraints:
1101 it must normally look like: @instance Foo (Tycon a b c ...) ...@
1103 The exceptions to this syntactic checking: (1)~if the @GlasgowExts@
1104 flag is on, or (2)~the instance is imported (they must have been
1105 compiled elsewhere). In these cases, we let them go through anyway.
1107 We can also have instances for functions: @instance Foo (a -> b) ...@.
1110 checkValidInstHead :: Type -> TcM (Class, [TcType])
1112 checkValidInstHead ty -- Should be a source type
1113 = case tcSplitPredTy_maybe ty of {
1114 Nothing -> failWithTc (instTypeErr (ppr ty) empty) ;
1117 case getClassPredTys_maybe pred of {
1118 Nothing -> failWithTc (instTypeErr (pprPred pred) empty) ;
1121 getDOpts `thenM` \ dflags ->
1122 mappM_ check_arg_type tys `thenM_`
1123 check_inst_head dflags clas tys `thenM_`
1127 check_inst_head dflags clas tys
1128 -- If GlasgowExts then check at least one isn't a type variable
1129 = do checkTc (dopt Opt_TypeSynonymInstances dflags ||
1130 all tcInstHeadTyNotSynonym tys)
1131 (instTypeErr (pprClassPred clas tys) head_type_synonym_msg)
1132 checkTc (dopt Opt_FlexibleInstances dflags ||
1133 all tcInstHeadTyAppAllTyVars tys)
1134 (instTypeErr (pprClassPred clas tys) head_type_args_tyvars_msg)
1135 checkTc (dopt Opt_MultiParamTypeClasses dflags ||
1137 (instTypeErr (pprClassPred clas tys) head_one_type_msg)
1140 head_type_synonym_msg = parens (
1141 text "All instance types must be of the form (T t1 ... tn)" $$
1142 text "where T is not a synonym." $$
1143 text "Use -XTypeSynonymInstances if you want to disable this.")
1145 head_type_args_tyvars_msg = parens (
1146 text "All instance types must be of the form (T a1 ... an)" $$
1147 text "where a1 ... an are distinct type *variables*" $$
1148 text "Use -XFlexibleInstances if you want to disable this.")
1150 head_one_type_msg = parens (
1151 text "Only one type can be given in an instance head." $$
1152 text "Use -XMultiParamTypeClasses if you want to allow more.")
1154 -- For now, I only allow tau-types (not polytypes) in
1155 -- the head of an instance decl.
1156 -- E.g. instance C (forall a. a->a) is rejected
1157 -- One could imagine generalising that, but I'm not sure
1158 -- what all the consequences might be
1159 check_one ty = do { check_tau_type (Rank 0) UT_NotOk ty
1160 ; checkTc (not (isUnLiftedType ty)) (unliftedArgErr ty) }
1162 instTypeErr pp_ty msg
1163 = sep [ptext SLIT("Illegal instance declaration for") <+> quotes pp_ty,
1168 %************************************************************************
1170 \subsection{Checking instance for termination}
1172 %************************************************************************
1176 checkValidInstance :: [TyVar] -> ThetaType -> Class -> [TcType] -> TcM ()
1177 checkValidInstance tyvars theta clas inst_tys
1178 = do { undecidable_ok <- doptM Opt_UndecidableInstances
1180 ; checkValidTheta InstThetaCtxt theta
1181 ; checkAmbiguity tyvars theta (tyVarsOfTypes inst_tys)
1183 -- Check that instance inference will terminate (if we care)
1184 -- For Haskell 98 this will already have been done by checkValidTheta,
1185 -- but as we may be using other extensions we need to check.
1186 ; unless undecidable_ok $
1187 mapM_ addErrTc (checkInstTermination inst_tys theta)
1189 -- The Coverage Condition
1190 ; checkTc (undecidable_ok || checkInstCoverage clas inst_tys)
1191 (instTypeErr (pprClassPred clas inst_tys) msg)
1194 msg = parens (vcat [ptext SLIT("the Coverage Condition fails for one of the functional dependencies;"),
1198 Termination test: the so-called "Paterson conditions" (see Section 5 of
1199 "Understanding functionsl dependencies via Constraint Handling Rules,
1202 We check that each assertion in the context satisfies:
1203 (1) no variable has more occurrences in the assertion than in the head, and
1204 (2) the assertion has fewer constructors and variables (taken together
1205 and counting repetitions) than the head.
1206 This is only needed with -fglasgow-exts, as Haskell 98 restrictions
1207 (which have already been checked) guarantee termination.
1209 The underlying idea is that
1211 for any ground substitution, each assertion in the
1212 context has fewer type constructors than the head.
1216 checkInstTermination :: [TcType] -> ThetaType -> [Message]
1217 checkInstTermination tys theta
1218 = mapCatMaybes check theta
1221 size = sizeTypes tys
1223 | not (null (fvPred pred \\ fvs))
1224 = Just (predUndecErr pred nomoreMsg $$ parens undecidableMsg)
1225 | sizePred pred >= size
1226 = Just (predUndecErr pred smallerMsg $$ parens undecidableMsg)
1230 predUndecErr pred msg = sep [msg,
1231 nest 2 (ptext SLIT("in the constraint:") <+> pprPred pred)]
1233 nomoreMsg = ptext SLIT("Variable occurs more often in a constraint than in the instance head")
1234 smallerMsg = ptext SLIT("Constraint is no smaller than the instance head")
1235 undecidableMsg = ptext SLIT("Use -fallow-undecidable-instances to permit this")
1239 %************************************************************************
1241 \subsection{Checking type instance well-formedness and termination}
1243 %************************************************************************
1246 -- Check that a "type instance" is well-formed (which includes decidability
1247 -- unless -fallow-undecidable-instances is given).
1249 checkValidTypeInst :: [Type] -> Type -> TcM ()
1250 checkValidTypeInst typats rhs
1251 = do { -- left-hand side contains no type family applications
1252 -- (vanilla synonyms are fine, though)
1253 ; mappM_ checkTyFamFreeness typats
1255 -- the right-hand side is a tau type
1256 ; checkTc (isTauTy rhs) $
1259 -- we have a decidable instance unless otherwise permitted
1260 ; undecidable_ok <- doptM Opt_UndecidableInstances
1261 ; unless undecidable_ok $
1262 mapM_ addErrTc (checkFamInst typats (tyFamInsts rhs))
1265 -- Make sure that each type family instance is
1266 -- (1) strictly smaller than the lhs,
1267 -- (2) mentions no type variable more often than the lhs, and
1268 -- (3) does not contain any further type family instances.
1270 checkFamInst :: [Type] -- lhs
1271 -> [(TyCon, [Type])] -- type family instances
1273 checkFamInst lhsTys famInsts
1274 = mapCatMaybes check famInsts
1276 size = sizeTypes lhsTys
1277 fvs = fvTypes lhsTys
1279 | not (all isTyFamFree tys)
1280 = Just (famInstUndecErr famInst nestedMsg $$ parens undecidableMsg)
1281 | not (null (fvTypes tys \\ fvs))
1282 = Just (famInstUndecErr famInst nomoreVarMsg $$ parens undecidableMsg)
1283 | size <= sizeTypes tys
1284 = Just (famInstUndecErr famInst smallerAppMsg $$ parens undecidableMsg)
1288 famInst = TyConApp tc tys
1290 -- Ensure that no type family instances occur in a type.
1292 checkTyFamFreeness :: Type -> TcM ()
1293 checkTyFamFreeness ty
1294 = checkTc (isTyFamFree ty) $
1295 tyFamInstInIndexErr ty
1297 -- Check that a type does not contain any type family applications.
1299 isTyFamFree :: Type -> Bool
1300 isTyFamFree = null . tyFamInsts
1304 tyFamInstInIndexErr ty
1305 = hang (ptext SLIT("Illegal type family application in type instance") <>
1310 = hang (ptext SLIT("Illegal polymorphic type in type instance") <> colon) 4 $
1313 famInstUndecErr ty msg
1315 nest 2 (ptext SLIT("in the type family application:") <+>
1318 nestedMsg = ptext SLIT("Nested type family application")
1319 nomoreVarMsg = ptext SLIT("Variable occurs more often than in instance head")
1320 smallerAppMsg = ptext SLIT("Application is no smaller than the instance head")
1324 %************************************************************************
1326 \subsection{Auxiliary functions}
1328 %************************************************************************
1331 -- Free variables of a type, retaining repetitions, and expanding synonyms
1332 fvType :: Type -> [TyVar]
1333 fvType ty | Just exp_ty <- tcView ty = fvType exp_ty
1334 fvType (TyVarTy tv) = [tv]
1335 fvType (TyConApp _ tys) = fvTypes tys
1336 fvType (NoteTy _ ty) = fvType ty
1337 fvType (PredTy pred) = fvPred pred
1338 fvType (FunTy arg res) = fvType arg ++ fvType res
1339 fvType (AppTy fun arg) = fvType fun ++ fvType arg
1340 fvType (ForAllTy tyvar ty) = filter (/= tyvar) (fvType ty)
1342 fvTypes :: [Type] -> [TyVar]
1343 fvTypes tys = concat (map fvType tys)
1345 fvPred :: PredType -> [TyVar]
1346 fvPred (ClassP _ tys') = fvTypes tys'
1347 fvPred (IParam _ ty) = fvType ty
1348 fvPred (EqPred ty1 ty2) = fvType ty1 ++ fvType ty2
1350 -- Size of a type: the number of variables and constructors
1351 sizeType :: Type -> Int
1352 sizeType ty | Just exp_ty <- tcView ty = sizeType exp_ty
1353 sizeType (TyVarTy _) = 1
1354 sizeType (TyConApp _ tys) = sizeTypes tys + 1
1355 sizeType (NoteTy _ ty) = sizeType ty
1356 sizeType (PredTy pred) = sizePred pred
1357 sizeType (FunTy arg res) = sizeType arg + sizeType res + 1
1358 sizeType (AppTy fun arg) = sizeType fun + sizeType arg
1359 sizeType (ForAllTy _ ty) = sizeType ty
1361 sizeTypes :: [Type] -> Int
1362 sizeTypes xs = sum (map sizeType xs)
1364 sizePred :: PredType -> Int
1365 sizePred (ClassP _ tys') = sizeTypes tys'
1366 sizePred (IParam _ ty) = sizeType ty
1367 sizePred (EqPred ty1 ty2) = sizeType ty1 + sizeType ty2
1369 -- Type family instances occuring in a type after expanding synonyms
1370 tyFamInsts :: Type -> [(TyCon, [Type])]
1372 | Just exp_ty <- tcView ty = tyFamInsts exp_ty
1373 tyFamInsts (TyVarTy _) = []
1374 tyFamInsts (TyConApp tc tys)
1375 | isOpenSynTyCon tc = [(tc, tys)]
1376 | otherwise = concat (map tyFamInsts tys)
1377 tyFamInsts (FunTy ty1 ty2) = tyFamInsts ty1 ++ tyFamInsts ty2
1378 tyFamInsts (AppTy ty1 ty2) = tyFamInsts ty1 ++ tyFamInsts ty2
1379 tyFamInsts (ForAllTy _ ty) = tyFamInsts ty