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(..),
23 newMetaTyVar, readMetaTyVar, writeMetaTyVar, isFilledMetaTyVar,
25 --------------------------------
26 -- Boxy type variables
27 newBoxyTyVar, newBoxyTyVars, newBoxyTyVarTys, readFilledBox,
29 --------------------------------
30 -- Creating new coercion variables
31 newCoVars, newMetaCoVar,
33 --------------------------------
35 tcInstTyVar, tcInstType, tcInstTyVars, tcInstBoxyTyVar,
37 tcInstSkolTyVar, tcInstSkolTyVars, tcInstSkolType,
38 tcSkolSigType, tcSkolSigTyVars, occurCheckErr,
40 --------------------------------
41 -- Checking type validity
42 Rank, UserTypeCtxt(..), checkValidType, checkValidMonoType,
43 SourceTyCtxt(..), checkValidTheta, checkFreeness,
44 checkValidInstHead, checkValidInstance,
45 checkInstTermination, checkValidTypeInst, checkTyFamFreeness,
46 checkUpdateMeta, updateMeta, checkTauTvUpdate, fillBoxWithTau, unifyKindCtxt,
47 unifyKindMisMatch, validDerivPred, arityErr, notMonoType, notMonoArgs,
49 --------------------------------
51 zonkType, zonkTcPredType,
52 zonkTcTyVar, zonkTcTyVars, zonkTcTyVarsAndFV, zonkSigTyVar,
53 zonkQuantifiedTyVar, zonkQuantifiedTyVars,
54 zonkTcType, zonkTcTypes, zonkTcThetaType,
55 zonkTcKindToKind, zonkTcKind, zonkTopTyVar,
57 readKindVar, writeKindVar
60 #include "HsVersions.h"
72 import TcRnMonad -- TcType, amongst others
88 import Data.List ( (\\) )
92 %************************************************************************
94 Instantiation in general
96 %************************************************************************
99 tcInstType :: ([TyVar] -> TcM [TcTyVar]) -- How to instantiate the type variables
100 -> TcType -- Type to instantiate
101 -> TcM ([TcTyVar], TcThetaType, TcType) -- Result
102 -- (type vars (excl coercion vars), preds (incl equalities), rho)
103 tcInstType inst_tyvars ty
104 = case tcSplitForAllTys ty of
105 ([], rho) -> let -- There may be overloading despite no type variables;
106 -- (?x :: Int) => Int -> Int
107 (theta, tau) = tcSplitPhiTy rho
109 return ([], theta, tau)
111 (tyvars, rho) -> do { tyvars' <- inst_tyvars tyvars
113 ; let tenv = zipTopTvSubst tyvars (mkTyVarTys tyvars')
114 -- Either the tyvars are freshly made, by inst_tyvars,
115 -- or (in the call from tcSkolSigType) any nested foralls
116 -- have different binders. Either way, zipTopTvSubst is ok
118 ; let (theta, tau) = tcSplitPhiTy (substTy tenv rho)
119 ; return (tyvars', theta, tau) }
123 %************************************************************************
127 %************************************************************************
129 Can't be in TcUnify, as we also need it in TcTyFuns.
133 -- False <=> the two args are (actual, expected) respectively
134 -- True <=> the two args are (expected, actual) respectively
136 checkUpdateMeta :: SwapFlag
137 -> TcTyVar -> IORef MetaDetails -> TcType -> TcM ()
138 -- Update tv1, which is flexi; occurs check is alrady done
139 -- The 'check' version does a kind check too
140 -- We do a sub-kind check here: we might unify (a b) with (c d)
141 -- where b::*->* and d::*; this should fail
143 checkUpdateMeta swapped tv1 ref1 ty2
144 = do { checkKinds swapped tv1 ty2
145 ; updateMeta tv1 ref1 ty2 }
147 updateMeta :: TcTyVar -> IORef MetaDetails -> TcType -> TcM ()
148 updateMeta tv1 ref1 ty2
149 = ASSERT( isMetaTyVar tv1 )
150 ASSERT( isBoxyTyVar tv1 || isTauTy ty2 )
151 do { ASSERTM2( do { details <- readMetaTyVar tv1; return (isFlexi details) }, ppr tv1 )
152 ; traceTc (text "updateMeta" <+> ppr tv1 <+> text ":=" <+> ppr ty2)
153 ; writeMutVar ref1 (Indirect ty2)
157 checkKinds :: Bool -> TyVar -> Type -> TcM ()
158 checkKinds swapped tv1 ty2
159 -- We're about to unify a type variable tv1 with a non-tyvar-type ty2.
160 -- ty2 has been zonked at this stage, which ensures that
161 -- its kind has as much boxity information visible as possible.
162 | tk2 `isSubKind` tk1 = return ()
165 -- Either the kinds aren't compatible
166 -- (can happen if we unify (a b) with (c d))
167 -- or we are unifying a lifted type variable with an
168 -- unlifted type: e.g. (id 3#) is illegal
169 = addErrCtxtM (unifyKindCtxt swapped tv1 ty2) $
170 unifyKindMisMatch k1 k2
172 (k1,k2) | swapped = (tk2,tk1)
173 | otherwise = (tk1,tk2)
178 checkTauTvUpdate :: TcTyVar -> TcType -> TcM (Maybe TcType)
179 -- (checkTauTvUpdate tv ty)
180 -- We are about to update the TauTv tv with ty.
181 -- Check (a) that tv doesn't occur in ty (occurs check)
182 -- (b) that ty is a monotype
183 -- Furthermore, in the interest of (b), if you find an
184 -- empty box (BoxTv that is Flexi), fill it in with a TauTv
186 -- We have three possible outcomes:
187 -- (1) Return the (non-boxy) type to update the type variable with,
188 -- [we know the update is ok!]
189 -- (2) return Nothing, or
190 -- [we cannot tell whether the update is ok right now]
192 -- [the update is definitely invalid]
193 -- We return Nothing in case the tv occurs in ty *under* a type family
194 -- application. In this case, we must not update tv (to avoid a cyclic type
195 -- term), but we also cannot fail claiming an infinite type. Given
197 -- type instance F Int = Int
200 -- This is perfectly reasonable, if we later get a ~ Int.
202 checkTauTvUpdate orig_tv orig_ty
203 = do { result <- go orig_ty
205 Right ty -> return $ Just ty
206 Left True -> return $ Nothing
207 Left False -> occurCheckErr (mkTyVarTy orig_tv) orig_ty
210 go :: TcType -> TcM (Either Bool TcType)
212 -- Right ty if everything is fine
213 -- Left True if orig_tv occurs in orig_ty, but under a type family app
214 -- Left False if orig_tv occurs in orig_ty (with no type family app)
215 -- It fails if it encounters a forall type, except as an argument for a
216 -- closed type synonym that expands to a tau type.
218 | isSynTyCon tc = go_syn tc tys
219 | otherwise = do { tys' <- mapM go tys
220 ; return $ occurs (TyConApp tc) tys' }
221 go (PredTy p) = do { p' <- go_pred p
222 ; return $ occurs1 PredTy p' }
223 go (FunTy arg res) = do { arg' <- go arg
225 ; return $ occurs2 FunTy arg' res' }
226 go (AppTy fun arg) = do { fun' <- go fun
228 ; return $ occurs2 mkAppTy fun' arg' }
229 -- NB the mkAppTy; we might have instantiated a
230 -- type variable to a type constructor, so we need
231 -- to pull the TyConApp to the top.
232 go (ForAllTy _ _) = notMonoType orig_ty -- (b)
235 | orig_tv == tv = return $ Left False -- (a)
236 | isTcTyVar tv = go_tyvar tv (tcTyVarDetails tv)
237 | otherwise = return $ Right (TyVarTy tv)
238 -- Ordinary (non Tc) tyvars
239 -- occur inside quantified types
241 go_pred (ClassP c tys) = do { tys' <- mapM go tys
242 ; return $ occurs (ClassP c) tys' }
243 go_pred (IParam n ty) = do { ty' <- go ty
244 ; return $ occurs1 (IParam n) ty' }
245 go_pred (EqPred t1 t2) = do { t1' <- go t1
247 ; return $ occurs2 EqPred t1' t2' }
249 go_tyvar tv (SkolemTv _) = return $ Right (TyVarTy tv)
250 go_tyvar tv (MetaTv box ref)
251 = do { cts <- readMutVar ref
255 BoxTv -> do { ty <- fillBoxWithTau tv ref
256 ; return $ Right ty }
257 _ -> return $ Right (TyVarTy tv)
260 -- go_syn is called for synonyms only
261 -- See Note [Type synonyms and the occur check]
263 | not (isTauTyCon tc)
264 = notMonoType orig_ty -- (b) again
266 = do { (_msgs, mb_tys') <- tryTc (mapM go tys)
269 -- we had a type error => forall in type parameters
271 | isOpenTyCon tc -> notMonoArgs (TyConApp tc tys)
272 -- Synonym families must have monotype args
273 | otherwise -> go (expectJust "checkTauTvUpdate(1)"
274 (tcView (TyConApp tc tys)))
275 -- Try again, expanding the synonym
277 -- no type error, but need to test whether occurs check happend
279 case occurs id tys' of
281 | isOpenTyCon tc -> return $ Left True
282 -- Variable occured under type family application
283 | otherwise -> go (expectJust "checkTauTvUpdate(2)"
284 (tcView (TyConApp tc tys)))
285 -- Try again, expanding the synonym
286 Right raw_tys' -> return $ Right (TyConApp tc raw_tys')
287 -- Retain the synonym (the common case)
290 -- Left results (= occurrence of orig_ty) dominate and
291 -- (Left False) (= fatal occurrence) dominates over (Left True)
292 occurs :: ([a] -> b) -> [Either Bool a] -> Either Bool b
293 occurs c = either Left (Right . c) . foldr combine (Right [])
295 combine (Left famInst1) (Left famInst2) = Left (famInst1 && famInst2)
296 combine (Right _ ) (Left famInst) = Left famInst
297 combine (Left famInst) (Right _) = Left famInst
298 combine (Right arg) (Right args) = Right (arg:args)
300 occurs1 c x = occurs (\[x'] -> c x') [x]
301 occurs2 c x y = occurs (\[x', y'] -> c x' y') [x, y]
303 fillBoxWithTau :: BoxyTyVar -> IORef MetaDetails -> TcM TcType
304 -- (fillBoxWithTau tv ref) fills ref with a freshly allocated
305 -- tau-type meta-variable, whose print-name is the same as tv
306 -- Choosing the same name is good: when we instantiate a function
307 -- we allocate boxy tyvars with the same print-name as the quantified
308 -- tyvar; and then we often fill the box with a tau-tyvar, and again
309 -- we want to choose the same name.
310 fillBoxWithTau tv ref
311 = do { tv' <- tcInstTyVar tv -- Do not gratuitously forget
312 ; let tau = mkTyVarTy tv' -- name of the type variable
313 ; writeMutVar ref (Indirect tau)
317 Note [Type synonyms and the occur check]
319 Basically we want to update tv1 := ps_ty2
320 because ps_ty2 has type-synonym info, which improves later error messages
325 f :: (A a -> a -> ()) -> ()
331 In the application (p x), we try to match "t" with "A t". If we go
332 ahead and bind t to A t (= ps_ty2), we'll lead the type checker into
333 an infinite loop later.
334 But we should not reject the program, because A t = ().
335 Rather, we should bind t to () (= non_var_ty2).
339 Error mesages in case of kind mismatch.
342 unifyKindMisMatch :: TcKind -> TcKind -> TcM ()
343 unifyKindMisMatch ty1 ty2 = do
344 ty1' <- zonkTcKind ty1
345 ty2' <- zonkTcKind ty2
347 msg = hang (ptext (sLit "Couldn't match kind"))
348 2 (sep [quotes (ppr ty1'),
349 ptext (sLit "against"),
353 unifyKindCtxt :: Bool -> TyVar -> Type -> TidyEnv -> TcM (TidyEnv, SDoc)
354 unifyKindCtxt swapped tv1 ty2 tidy_env -- not swapped => tv1 expected, ty2 inferred
355 -- tv1 and ty2 are zonked already
358 msg = (env2, ptext (sLit "When matching the kinds of") <+>
359 sep [quotes pp_expected <+> ptext (sLit "and"), quotes pp_actual])
361 (pp_expected, pp_actual) | swapped = (pp2, pp1)
362 | otherwise = (pp1, pp2)
363 (env1, tv1') = tidyOpenTyVar tidy_env tv1
364 (env2, ty2') = tidyOpenType env1 ty2
365 pp1 = ppr tv1' <+> dcolon <+> ppr (tyVarKind tv1)
366 pp2 = ppr ty2' <+> dcolon <+> ppr (typeKind ty2)
369 Error message for failure due to an occurs check.
372 occurCheckErr :: TcType -> TcType -> TcM a
373 occurCheckErr ty containingTy
374 = do { env0 <- tcInitTidyEnv
375 ; ty' <- zonkTcType ty
376 ; containingTy' <- zonkTcType containingTy
377 ; let (env1, tidy_ty1) = tidyOpenType env0 ty'
378 (env2, tidy_ty2) = tidyOpenType env1 containingTy'
379 extra = sep [ppr tidy_ty1, char '=', ppr tidy_ty2]
380 ; failWithTcM (env2, hang msg 2 extra) }
382 msg = ptext (sLit "Occurs check: cannot construct the infinite type:")
385 %************************************************************************
389 %************************************************************************
392 newCoVars :: [(TcType,TcType)] -> TcM [CoVar]
394 = do { us <- newUniqueSupply
395 ; return [ mkCoVar (mkSysTvName uniq (fsLit "co"))
397 | ((ty1,ty2), uniq) <- spec `zip` uniqsFromSupply us] }
399 newMetaCoVar :: TcType -> TcType -> TcM TcTyVar
400 newMetaCoVar ty1 ty2 = newMetaTyVar TauTv (mkCoKind ty1 ty2)
402 newKindVar :: TcM TcKind
403 newKindVar = do { uniq <- newUnique
404 ; ref <- newMutVar Flexi
405 ; return (mkTyVarTy (mkKindVar uniq ref)) }
407 newKindVars :: Int -> TcM [TcKind]
408 newKindVars n = mapM (\ _ -> newKindVar) (nOfThem n ())
412 %************************************************************************
414 SkolemTvs (immutable)
416 %************************************************************************
419 mkSkolTyVar :: Name -> Kind -> SkolemInfo -> TcTyVar
420 mkSkolTyVar name kind info = mkTcTyVar name kind (SkolemTv info)
422 tcSkolSigType :: SkolemInfo -> Type -> TcM ([TcTyVar], TcThetaType, TcType)
423 -- Instantiate a type signature with skolem constants, but
424 -- do *not* give them fresh names, because we want the name to
425 -- be in the type environment -- it is lexically scoped.
426 tcSkolSigType info ty = tcInstType (\tvs -> return (tcSkolSigTyVars info tvs)) ty
428 tcSkolSigTyVars :: SkolemInfo -> [TyVar] -> [TcTyVar]
429 -- Make skolem constants, but do *not* give them new names, as above
430 tcSkolSigTyVars info tyvars = [ mkSkolTyVar (tyVarName tv) (tyVarKind tv) info
433 tcInstSkolTyVar :: SkolemInfo -> Maybe SrcSpan -> TyVar -> TcM TcTyVar
434 -- Instantiate the tyvar, using
435 -- * the occ-name and kind of the supplied tyvar,
436 -- * the unique from the monad,
437 -- * the location either from the tyvar (mb_loc = Nothing)
438 -- or from mb_loc (Just loc)
439 tcInstSkolTyVar info mb_loc tyvar
440 = do { uniq <- newUnique
441 ; let old_name = tyVarName tyvar
442 kind = tyVarKind tyvar
443 loc = mb_loc `orElse` getSrcSpan old_name
444 new_name = mkInternalName uniq (nameOccName old_name) loc
445 ; return (mkSkolTyVar new_name kind info) }
447 tcInstSkolTyVars :: SkolemInfo -> [TyVar] -> TcM [TcTyVar]
448 -- Get the location from the monad
449 tcInstSkolTyVars info tyvars
450 = do { span <- getSrcSpanM
451 ; mapM (tcInstSkolTyVar info (Just span)) tyvars }
453 tcInstSkolType :: SkolemInfo -> TcType -> TcM ([TcTyVar], TcThetaType, TcType)
454 -- Instantiate a type with fresh skolem constants
455 -- Binding location comes from the monad
456 tcInstSkolType info ty = tcInstType (tcInstSkolTyVars info) ty
460 %************************************************************************
462 MetaTvs (meta type variables; mutable)
464 %************************************************************************
467 newMetaTyVar :: BoxInfo -> Kind -> TcM TcTyVar
468 -- Make a new meta tyvar out of thin air
469 newMetaTyVar box_info kind
470 = do { uniq <- newUnique
471 ; ref <- newMutVar Flexi
472 ; let name = mkSysTvName uniq fs
473 fs = case box_info of
477 -- We give BoxTv and TauTv the same string, because
478 -- otherwise we get user-visible differences in error
479 -- messages, which are confusing. If you want to see
480 -- the box_info of each tyvar, use -dppr-debug
481 ; return (mkTcTyVar name kind (MetaTv box_info ref)) }
483 instMetaTyVar :: BoxInfo -> TyVar -> TcM TcTyVar
484 -- Make a new meta tyvar whose Name and Kind
485 -- come from an existing TyVar
486 instMetaTyVar box_info tyvar
487 = do { uniq <- newUnique
488 ; ref <- newMutVar Flexi
489 ; let name = setNameUnique (tyVarName tyvar) uniq
490 kind = tyVarKind tyvar
491 ; return (mkTcTyVar name kind (MetaTv box_info ref)) }
493 readMetaTyVar :: TyVar -> TcM MetaDetails
494 readMetaTyVar tyvar = ASSERT2( isMetaTyVar tyvar, ppr tyvar )
495 readMutVar (metaTvRef tyvar)
497 isFilledMetaTyVar :: TyVar -> TcM Bool
498 -- True of a filled-in (Indirect) meta type variable
500 | not (isTcTyVar tv) = return False
501 | MetaTv _ ref <- tcTyVarDetails tv
502 = do { details <- readMutVar ref
503 ; return (isIndirect details) }
504 | otherwise = return False
506 writeMetaTyVar :: TcTyVar -> TcType -> TcM ()
507 writeMetaTyVar tyvar ty
508 | not debugIsOn = writeMutVar (metaTvRef tyvar) (Indirect ty)
509 writeMetaTyVar tyvar ty
510 | not (isMetaTyVar tyvar)
511 = pprTrace "writeMetaTyVar" (ppr tyvar) $
514 = ASSERT( isMetaTyVar tyvar )
515 -- TOM: It should also work for coercions
516 -- ASSERT2( k2 `isSubKind` k1, (ppr tyvar <+> ppr k1) $$ (ppr ty <+> ppr k2) )
517 do { ASSERTM2( do { details <- readMetaTyVar tyvar; return (isFlexi details) }, ppr tyvar )
518 ; writeMutVar (metaTvRef tyvar) (Indirect ty) }
520 _k1 = tyVarKind tyvar
525 %************************************************************************
529 %************************************************************************
532 newFlexiTyVar :: Kind -> TcM TcTyVar
533 newFlexiTyVar kind = newMetaTyVar TauTv kind
535 newFlexiTyVarTy :: Kind -> TcM TcType
536 newFlexiTyVarTy kind = do
537 tc_tyvar <- newFlexiTyVar kind
538 return (TyVarTy tc_tyvar)
540 newFlexiTyVarTys :: Int -> Kind -> TcM [TcType]
541 newFlexiTyVarTys n kind = mapM newFlexiTyVarTy (nOfThem n kind)
543 tcInstTyVar :: TyVar -> TcM TcTyVar
544 -- Instantiate with a META type variable
545 tcInstTyVar tyvar = instMetaTyVar TauTv tyvar
547 tcInstTyVars :: [TyVar] -> TcM ([TcTyVar], [TcType], TvSubst)
548 -- Instantiate with META type variables
550 = do { tc_tvs <- mapM tcInstTyVar tyvars
551 ; let tys = mkTyVarTys tc_tvs
552 ; return (tc_tvs, tys, zipTopTvSubst tyvars tys) }
553 -- Since the tyvars are freshly made,
554 -- they cannot possibly be captured by
555 -- any existing for-alls. Hence zipTopTvSubst
559 %************************************************************************
563 %************************************************************************
566 tcInstSigTyVars :: Bool -> SkolemInfo -> [TyVar] -> TcM [TcTyVar]
567 -- Instantiate with skolems or meta SigTvs; depending on use_skols
568 -- Always take location info from the supplied tyvars
569 tcInstSigTyVars use_skols skol_info tyvars
571 = mapM (tcInstSkolTyVar skol_info Nothing) tyvars
574 = mapM (instMetaTyVar (SigTv skol_info)) tyvars
576 zonkSigTyVar :: TcTyVar -> TcM TcTyVar
578 | isSkolemTyVar sig_tv
579 = return sig_tv -- Happens in the call in TcBinds.checkDistinctTyVars
581 = ASSERT( isSigTyVar sig_tv )
582 do { ty <- zonkTcTyVar sig_tv
583 ; return (tcGetTyVar "zonkSigTyVar" ty) }
584 -- 'ty' is bound to be a type variable, because SigTvs
585 -- can only be unified with type variables
589 %************************************************************************
593 %************************************************************************
596 newBoxyTyVar :: Kind -> TcM BoxyTyVar
597 newBoxyTyVar kind = newMetaTyVar BoxTv kind
599 newBoxyTyVars :: [Kind] -> TcM [BoxyTyVar]
600 newBoxyTyVars kinds = mapM newBoxyTyVar kinds
602 newBoxyTyVarTys :: [Kind] -> TcM [BoxyType]
603 newBoxyTyVarTys kinds = do { tvs <- mapM newBoxyTyVar kinds; return (mkTyVarTys tvs) }
605 readFilledBox :: BoxyTyVar -> TcM TcType
606 -- Read the contents of the box, which should be filled in by now
607 readFilledBox box_tv = ASSERT( isBoxyTyVar box_tv )
608 do { cts <- readMetaTyVar box_tv
610 Flexi -> pprPanic "readFilledBox" (ppr box_tv)
611 Indirect ty -> return ty }
613 tcInstBoxyTyVar :: TyVar -> TcM BoxyTyVar
614 -- Instantiate with a BOXY type variable
615 tcInstBoxyTyVar tyvar = instMetaTyVar BoxTv tyvar
619 %************************************************************************
621 \subsection{Putting and getting mutable type variables}
623 %************************************************************************
625 But it's more fun to short out indirections on the way: If this
626 version returns a TyVar, then that TyVar is unbound. If it returns
627 any other type, then there might be bound TyVars embedded inside it.
629 We return Nothing iff the original box was unbound.
632 data LookupTyVarResult -- The result of a lookupTcTyVar call
633 = DoneTv TcTyVarDetails -- SkolemTv or virgin MetaTv
636 lookupTcTyVar :: TcTyVar -> TcM LookupTyVarResult
638 = ASSERT2( isTcTyVar tyvar, ppr tyvar )
640 SkolemTv _ -> return (DoneTv details)
641 MetaTv _ ref -> do { meta_details <- readMutVar ref
642 ; case meta_details of
643 Indirect ty -> return (IndirectTv ty)
644 Flexi -> return (DoneTv details) }
646 details = tcTyVarDetails tyvar
649 -- gaw 2004 We aren't shorting anything out anymore, at least for now
651 | not (isTcTyVar tyvar)
652 = pprTrace "getTcTyVar" (ppr tyvar) $
653 return (Just (mkTyVarTy tyvar))
656 = ASSERT2( isTcTyVar tyvar, ppr tyvar ) do
657 maybe_ty <- readMetaTyVar tyvar
659 Just ty -> do ty' <- short_out ty
660 writeMetaTyVar tyvar (Just ty')
663 Nothing -> return Nothing
665 short_out :: TcType -> TcM TcType
666 short_out ty@(TyVarTy tyvar)
667 | not (isTcTyVar tyvar)
671 maybe_ty <- readMetaTyVar tyvar
673 Just ty' -> do ty' <- short_out ty'
674 writeMetaTyVar tyvar (Just ty')
679 short_out other_ty = return other_ty
684 %************************************************************************
686 \subsection{Zonking -- the exernal interfaces}
688 %************************************************************************
690 ----------------- Type variables
693 zonkTcTyVars :: [TcTyVar] -> TcM [TcType]
694 zonkTcTyVars tyvars = mapM zonkTcTyVar tyvars
696 zonkTcTyVarsAndFV :: [TcTyVar] -> TcM TcTyVarSet
697 zonkTcTyVarsAndFV tyvars = tyVarsOfTypes <$> mapM zonkTcTyVar tyvars
699 zonkTcTyVar :: TcTyVar -> TcM TcType
700 zonkTcTyVar tyvar = ASSERT2( isTcTyVar tyvar, ppr tyvar)
701 zonk_tc_tyvar (\ tv -> return (TyVarTy tv)) tyvar
704 ----------------- Types
707 zonkTcType :: TcType -> TcM TcType
708 zonkTcType ty = zonkType (\ tv -> return (TyVarTy tv)) ty
710 zonkTcTypes :: [TcType] -> TcM [TcType]
711 zonkTcTypes tys = mapM zonkTcType tys
713 zonkTcThetaType :: TcThetaType -> TcM TcThetaType
714 zonkTcThetaType theta = mapM zonkTcPredType theta
716 zonkTcPredType :: TcPredType -> TcM TcPredType
717 zonkTcPredType (ClassP c ts) = ClassP c <$> zonkTcTypes ts
718 zonkTcPredType (IParam n t) = IParam n <$> zonkTcType t
719 zonkTcPredType (EqPred t1 t2) = EqPred <$> zonkTcType t1 <*> zonkTcType t2
722 ------------------- These ...ToType, ...ToKind versions
723 are used at the end of type checking
726 zonkTopTyVar :: TcTyVar -> TcM TcTyVar
727 -- zonkTopTyVar is used, at the top level, on any un-instantiated meta type variables
728 -- to default the kind of ? and ?? etc to *. This is important to ensure that
729 -- instance declarations match. For example consider
730 -- instance Show (a->b)
731 -- foo x = show (\_ -> True)
732 -- Then we'll get a constraint (Show (p ->q)) where p has argTypeKind (printed ??),
733 -- and that won't match the typeKind (*) in the instance decl.
735 -- Because we are at top level, no further constraints are going to affect these
736 -- type variables, so it's time to do it by hand. However we aren't ready
737 -- to default them fully to () or whatever, because the type-class defaulting
738 -- rules have yet to run.
741 | k `eqKind` default_k = return tv
743 = do { tv' <- newFlexiTyVar default_k
744 ; writeMetaTyVar tv (mkTyVarTy tv')
748 default_k = defaultKind k
750 zonkQuantifiedTyVars :: [TcTyVar] -> TcM [TcTyVar]
751 zonkQuantifiedTyVars = mapM zonkQuantifiedTyVar
753 zonkQuantifiedTyVar :: TcTyVar -> TcM TcTyVar
754 -- zonkQuantifiedTyVar is applied to the a TcTyVar when quantifying over it.
756 -- The quantified type variables often include meta type variables
757 -- we want to freeze them into ordinary type variables, and
758 -- default their kind (e.g. from OpenTypeKind to TypeKind)
759 -- -- see notes with Kind.defaultKind
760 -- The meta tyvar is updated to point to the new skolem TyVar. Now any
761 -- bound occurences of the original type variable will get zonked to
762 -- the immutable version.
764 -- We leave skolem TyVars alone; they are immutable.
765 zonkQuantifiedTyVar tv
766 | ASSERT( isTcTyVar tv )
767 isSkolemTyVar tv = return tv
768 -- It might be a skolem type variable,
769 -- for example from a user type signature
771 | otherwise -- It's a meta-type-variable
772 = do { details <- readMetaTyVar tv
774 -- Create the new, frozen, skolem type variable
775 -- We zonk to a skolem, not to a regular TcVar
776 -- See Note [Zonking to Skolem]
777 ; let final_kind = defaultKind (tyVarKind tv)
778 final_tv = mkSkolTyVar (tyVarName tv) final_kind UnkSkol
780 -- Bind the meta tyvar to the new tyvar
782 Indirect ty -> WARN( True, ppr tv $$ ppr ty )
784 -- [Sept 04] I don't think this should happen
785 -- See note [Silly Type Synonym]
787 Flexi -> writeMetaTyVar tv (mkTyVarTy final_tv)
789 -- Return the new tyvar
793 Note [Silly Type Synonyms]
794 ~~~~~~~~~~~~~~~~~~~~~~~~~~
796 type C u a = u -- Note 'a' unused
798 foo :: (forall a. C u a -> C u a) -> u
802 bar = foo (\t -> t + t)
804 * From the (\t -> t+t) we get type {Num d} => d -> d
807 * Now unify with type of foo's arg, and we get:
808 {Num (C d a)} => C d a -> C d a
811 * Now abstract over the 'a', but float out the Num (C d a) constraint
812 because it does not 'really' mention a. (see exactTyVarsOfType)
813 The arg to foo becomes
816 * So we get a dict binding for Num (C d a), which is zonked to give
818 [Note Sept 04: now that we are zonking quantified type variables
819 on construction, the 'a' will be frozen as a regular tyvar on
820 quantification, so the floated dict will still have type (C d a).
821 Which renders this whole note moot; happily!]
823 * Then the /\a abstraction has a zonked 'a' in it.
825 All very silly. I think its harmless to ignore the problem. We'll end up with
826 a /\a in the final result but all the occurrences of a will be zonked to ()
828 Note [Zonking to Skolem]
829 ~~~~~~~~~~~~~~~~~~~~~~~~
830 We used to zonk quantified type variables to regular TyVars. However, this
831 leads to problems. Consider this program from the regression test suite:
833 eval :: Int -> String -> String -> String
834 eval 0 root actual = evalRHS 0 root actual
837 evalRHS 0 root actual = eval 0 root actual
839 It leads to the deferral of an equality
841 (String -> String -> String) ~ a
843 which is propagated up to the toplevel (see TcSimplify.tcSimplifyInferCheck).
844 In the meantime `a' is zonked and quantified to form `evalRHS's signature.
845 This has the *side effect* of also zonking the `a' in the deferred equality
846 (which at this point is being handed around wrapped in an implication
849 Finally, the equality (with the zonked `a') will be handed back to the
850 simplifier by TcRnDriver.tcRnSrcDecls calling TcSimplify.tcSimplifyTop.
851 If we zonk `a' with a regular type variable, we will have this regular type
852 variable now floating around in the simplifier, which in many places assumes to
853 only see proper TcTyVars.
855 We can avoid this problem by zonking with a skolem. The skolem is rigid
856 (which we requirefor a quantified variable), but is still a TcTyVar that the
857 simplifier knows how to deal with.
860 %************************************************************************
862 \subsection{Zonking -- the main work-horses: zonkType, zonkTyVar}
864 %* For internal use only! *
866 %************************************************************************
869 -- For unbound, mutable tyvars, zonkType uses the function given to it
870 -- For tyvars bound at a for-all, zonkType zonks them to an immutable
871 -- type variable and zonks the kind too
873 zonkType :: (TcTyVar -> TcM Type) -- What to do with unbound mutable type variables
874 -- see zonkTcType, and zonkTcTypeToType
877 zonkType unbound_var_fn ty
880 go (TyConApp tc tys) = do tys' <- mapM go tys
881 return (TyConApp tc tys')
883 go (PredTy p) = do p' <- go_pred p
886 go (FunTy arg res) = do arg' <- go arg
888 return (FunTy arg' res')
890 go (AppTy fun arg) = do fun' <- go fun
892 return (mkAppTy fun' arg')
893 -- NB the mkAppTy; we might have instantiated a
894 -- type variable to a type constructor, so we need
895 -- to pull the TyConApp to the top.
897 -- The two interesting cases!
898 go (TyVarTy tyvar) | isTcTyVar tyvar = zonk_tc_tyvar unbound_var_fn tyvar
899 | otherwise = return (TyVarTy tyvar)
900 -- Ordinary (non Tc) tyvars occur inside quantified types
902 go (ForAllTy tyvar ty) = ASSERT( isImmutableTyVar tyvar ) do
904 return (ForAllTy tyvar ty')
906 go_pred (ClassP c tys) = do tys' <- mapM go tys
907 return (ClassP c tys')
908 go_pred (IParam n ty) = do ty' <- go ty
909 return (IParam n ty')
910 go_pred (EqPred ty1 ty2) = do ty1' <- go ty1
912 return (EqPred ty1' ty2')
914 zonk_tc_tyvar :: (TcTyVar -> TcM Type) -- What to do for an unbound mutable variable
915 -> TcTyVar -> TcM TcType
916 zonk_tc_tyvar unbound_var_fn tyvar
917 | not (isMetaTyVar tyvar) -- Skolems
918 = return (TyVarTy tyvar)
920 | otherwise -- Mutables
921 = do { cts <- readMetaTyVar tyvar
923 Flexi -> unbound_var_fn tyvar -- Unbound meta type variable
924 Indirect ty -> zonkType unbound_var_fn ty }
929 %************************************************************************
933 %************************************************************************
936 readKindVar :: KindVar -> TcM (MetaDetails)
937 writeKindVar :: KindVar -> TcKind -> TcM ()
938 readKindVar kv = readMutVar (kindVarRef kv)
939 writeKindVar kv val = writeMutVar (kindVarRef kv) (Indirect val)
942 zonkTcKind :: TcKind -> TcM TcKind
943 zonkTcKind k = zonkTcType k
946 zonkTcKindToKind :: TcKind -> TcM Kind
947 -- When zonking a TcKind to a kind, we need to instantiate kind variables,
948 -- Haskell specifies that * is to be used, so we follow that.
949 zonkTcKindToKind k = zonkType (\ _ -> return liftedTypeKind) k
952 %************************************************************************
954 \subsection{Checking a user type}
956 %************************************************************************
958 When dealing with a user-written type, we first translate it from an HsType
959 to a Type, performing kind checking, and then check various things that should
960 be true about it. We don't want to perform these checks at the same time
961 as the initial translation because (a) they are unnecessary for interface-file
962 types and (b) when checking a mutually recursive group of type and class decls,
963 we can't "look" at the tycons/classes yet. Also, the checks are are rather
964 diverse, and used to really mess up the other code.
966 One thing we check for is 'rank'.
968 Rank 0: monotypes (no foralls)
969 Rank 1: foralls at the front only, Rank 0 inside
970 Rank 2: foralls at the front, Rank 1 on left of fn arrow,
972 basic ::= tyvar | T basic ... basic
974 r2 ::= forall tvs. cxt => r2a
975 r2a ::= r1 -> r2a | basic
976 r1 ::= forall tvs. cxt => r0
977 r0 ::= r0 -> r0 | basic
979 Another thing is to check that type synonyms are saturated.
980 This might not necessarily show up in kind checking.
982 data T k = MkT (k Int)
987 checkValidType :: UserTypeCtxt -> Type -> TcM ()
988 -- Checks that the type is valid for the given context
989 checkValidType ctxt ty = do
990 traceTc (text "checkValidType" <+> ppr ty)
991 unboxed <- doptM Opt_UnboxedTuples
992 rank2 <- doptM Opt_Rank2Types
993 rankn <- doptM Opt_RankNTypes
994 polycomp <- doptM Opt_PolymorphicComponents
996 rank | rankn = Arbitrary
999 = case ctxt of -- Haskell 98
1000 GenPatCtxt -> Rank 0
1001 LamPatSigCtxt -> Rank 0
1002 BindPatSigCtxt -> Rank 0
1003 DefaultDeclCtxt-> Rank 0
1004 ResSigCtxt -> Rank 0
1005 TySynCtxt _ -> Rank 0
1006 ExprSigCtxt -> Rank 1
1007 FunSigCtxt _ -> Rank 1
1008 ConArgCtxt _ -> if polycomp
1010 -- We are given the type of the entire
1011 -- constructor, hence rank 1
1013 ForSigCtxt _ -> Rank 1
1014 SpecInstCtxt -> Rank 1
1016 actual_kind = typeKind ty
1018 kind_ok = case ctxt of
1019 TySynCtxt _ -> True -- Any kind will do
1020 ResSigCtxt -> isSubOpenTypeKind actual_kind
1021 ExprSigCtxt -> isSubOpenTypeKind actual_kind
1022 GenPatCtxt -> isLiftedTypeKind actual_kind
1023 ForSigCtxt _ -> isLiftedTypeKind actual_kind
1024 _ -> isSubArgTypeKind actual_kind
1026 ubx_tup = case ctxt of
1027 TySynCtxt _ | unboxed -> UT_Ok
1028 ExprSigCtxt | unboxed -> UT_Ok
1031 -- Check that the thing has kind Type, and is lifted if necessary
1032 checkTc kind_ok (kindErr actual_kind)
1034 -- Check the internal validity of the type itself
1035 check_type rank ubx_tup ty
1037 traceTc (text "checkValidType done" <+> ppr ty)
1039 checkValidMonoType :: Type -> TcM ()
1040 checkValidMonoType ty = check_mono_type ty
1045 data Rank = Rank Int | Arbitrary
1047 decRank :: Rank -> Rank
1048 decRank Arbitrary = Arbitrary
1049 decRank (Rank n) = Rank (n-1)
1051 nonZeroRank :: Rank -> Bool
1052 nonZeroRank (Rank 0) = False
1053 nonZeroRank _ = True
1055 ----------------------------------------
1056 data UbxTupFlag = UT_Ok | UT_NotOk
1057 -- The "Ok" version means "ok if -fglasgow-exts is on"
1059 ----------------------------------------
1060 check_mono_type :: Type -> TcM () -- No foralls anywhere
1061 -- No unlifted types of any kind
1063 = do { check_type (Rank 0) UT_NotOk ty
1064 ; checkTc (not (isUnLiftedType ty)) (unliftedArgErr ty) }
1066 check_type :: Rank -> UbxTupFlag -> Type -> TcM ()
1067 -- The args say what the *type* context requires, independent
1068 -- of *flag* settings. You test the flag settings at usage sites.
1070 -- Rank is allowed rank for function args
1071 -- Rank 0 means no for-alls anywhere
1073 check_type rank ubx_tup ty
1074 | not (null tvs && null theta)
1075 = do { checkTc (nonZeroRank rank) (forAllTyErr ty)
1076 -- Reject e.g. (Maybe (?x::Int => Int)),
1077 -- with a decent error message
1078 ; check_valid_theta SigmaCtxt theta
1079 ; check_type rank ubx_tup tau -- Allow foralls to right of arrow
1080 ; checkFreeness tvs theta
1081 ; checkAmbiguity tvs theta (tyVarsOfType tau) }
1083 (tvs, theta, tau) = tcSplitSigmaTy ty
1085 -- Naked PredTys don't usually show up, but they can as a result of
1086 -- {-# SPECIALISE instance Ord Char #-}
1087 -- The Right Thing would be to fix the way that SPECIALISE instance pragmas
1088 -- are handled, but the quick thing is just to permit PredTys here.
1089 check_type _ _ (PredTy sty)
1090 = do { dflags <- getDOpts
1091 ; check_pred_ty dflags TypeCtxt sty }
1093 check_type _ _ (TyVarTy _) = return ()
1094 check_type rank _ (FunTy arg_ty res_ty)
1095 = do { check_type (decRank rank) UT_NotOk arg_ty
1096 ; check_type rank UT_Ok res_ty }
1098 check_type rank _ (AppTy ty1 ty2)
1099 = do { check_arg_type rank ty1
1100 ; check_arg_type rank ty2 }
1102 check_type rank ubx_tup ty@(TyConApp tc tys)
1104 = do { -- Check that the synonym has enough args
1105 -- This applies equally to open and closed synonyms
1106 -- It's OK to have an *over-applied* type synonym
1107 -- data Tree a b = ...
1108 -- type Foo a = Tree [a]
1109 -- f :: Foo a b -> ...
1110 checkTc (tyConArity tc <= length tys) arity_msg
1112 -- See Note [Liberal type synonyms]
1113 ; liberal <- doptM Opt_LiberalTypeSynonyms
1114 ; if not liberal || isOpenSynTyCon tc then
1115 -- For H98 and synonym families, do check the type args
1116 mapM_ check_mono_type tys
1118 else -- In the liberal case (only for closed syns), expand then check
1120 Just ty' -> check_type rank ubx_tup ty'
1121 Nothing -> pprPanic "check_tau_type" (ppr ty)
1124 | isUnboxedTupleTyCon tc
1125 = do { ub_tuples_allowed <- doptM Opt_UnboxedTuples
1126 ; checkTc (ubx_tup_ok ub_tuples_allowed) ubx_tup_msg
1128 ; impred <- doptM Opt_ImpredicativeTypes
1129 ; let rank' = if impred then rank else Rank 0
1130 -- c.f. check_arg_type
1131 -- However, args are allowed to be unlifted, or
1132 -- more unboxed tuples, so can't use check_arg_ty
1133 ; mapM_ (check_type rank' UT_Ok) tys }
1136 = mapM_ (check_arg_type rank) tys
1139 ubx_tup_ok ub_tuples_allowed = case ubx_tup of
1140 UT_Ok -> ub_tuples_allowed
1144 tc_arity = tyConArity tc
1146 arity_msg = arityErr "Type synonym" (tyConName tc) tc_arity n_args
1147 ubx_tup_msg = ubxArgTyErr ty
1149 check_type _ _ ty = pprPanic "check_type" (ppr ty)
1151 ----------------------------------------
1152 check_arg_type :: Rank -> Type -> TcM ()
1153 -- The sort of type that can instantiate a type variable,
1154 -- or be the argument of a type constructor.
1155 -- Not an unboxed tuple, but now *can* be a forall (since impredicativity)
1156 -- Other unboxed types are very occasionally allowed as type
1157 -- arguments depending on the kind of the type constructor
1159 -- For example, we want to reject things like:
1161 -- instance Ord a => Ord (forall s. T s a)
1163 -- g :: T s (forall b.b)
1165 -- NB: unboxed tuples can have polymorphic or unboxed args.
1166 -- This happens in the workers for functions returning
1167 -- product types with polymorphic components.
1168 -- But not in user code.
1169 -- Anyway, they are dealt with by a special case in check_tau_type
1171 check_arg_type rank ty
1172 = do { impred <- doptM Opt_ImpredicativeTypes
1173 ; let rank' = if impred then rank else Rank 0 -- Monotype unless impredicative
1174 ; check_type rank' UT_NotOk ty
1175 ; checkTc (not (isUnLiftedType ty)) (unliftedArgErr ty) }
1177 ----------------------------------------
1178 forAllTyErr, unliftedArgErr, ubxArgTyErr :: Type -> SDoc
1179 forAllTyErr ty = sep [ptext (sLit "Illegal polymorphic or qualified type:"), ppr ty]
1180 unliftedArgErr ty = sep [ptext (sLit "Illegal unlifted type:"), ppr ty]
1181 ubxArgTyErr ty = sep [ptext (sLit "Illegal unboxed tuple type as function argument:"), ppr ty]
1183 kindErr :: Kind -> SDoc
1184 kindErr kind = sep [ptext (sLit "Expecting an ordinary type, but found a type of kind"), ppr kind]
1187 Note [Liberal type synonyms]
1188 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1189 If -XLiberalTypeSynonyms is on, expand closed type synonyms *before*
1190 doing validity checking. This allows us to instantiate a synonym defn
1191 with a for-all type, or with a partially-applied type synonym.
1195 Here, T is partially applied, so it's illegal in H98. But if you
1196 expand S first, then T we get just
1200 IMPORTANT: suppose T is a type synonym. Then we must do validity
1201 checking on an appliation (T ty1 ty2)
1203 *either* before expansion (i.e. check ty1, ty2)
1204 *or* after expansion (i.e. expand T ty1 ty2, and then check)
1207 If we do both, we get exponential behaviour!!
1209 data TIACons1 i r c = c i ::: r c
1210 type TIACons2 t x = TIACons1 t (TIACons1 t x)
1211 type TIACons3 t x = TIACons2 t (TIACons1 t x)
1212 type TIACons4 t x = TIACons2 t (TIACons2 t x)
1213 type TIACons7 t x = TIACons4 t (TIACons3 t x)
1216 %************************************************************************
1218 \subsection{Checking a theta or source type}
1220 %************************************************************************
1223 -- Enumerate the contexts in which a "source type", <S>, can occur
1227 -- or (N a) where N is a newtype
1230 = ClassSCCtxt Name -- Superclasses of clas
1231 -- class <S> => C a where ...
1232 | SigmaCtxt -- Theta part of a normal for-all type
1233 -- f :: <S> => a -> a
1234 | DataTyCtxt Name -- Theta part of a data decl
1235 -- data <S> => T a = MkT a
1236 | TypeCtxt -- Source type in an ordinary type
1238 | InstThetaCtxt -- Context of an instance decl
1239 -- instance <S> => C [a] where ...
1241 pprSourceTyCtxt :: SourceTyCtxt -> SDoc
1242 pprSourceTyCtxt (ClassSCCtxt c) = ptext (sLit "the super-classes of class") <+> quotes (ppr c)
1243 pprSourceTyCtxt SigmaCtxt = ptext (sLit "the context of a polymorphic type")
1244 pprSourceTyCtxt (DataTyCtxt tc) = ptext (sLit "the context of the data type declaration for") <+> quotes (ppr tc)
1245 pprSourceTyCtxt InstThetaCtxt = ptext (sLit "the context of an instance declaration")
1246 pprSourceTyCtxt TypeCtxt = ptext (sLit "the context of a type")
1250 checkValidTheta :: SourceTyCtxt -> ThetaType -> TcM ()
1251 checkValidTheta ctxt theta
1252 = addErrCtxt (checkThetaCtxt ctxt theta) (check_valid_theta ctxt theta)
1254 -------------------------
1255 check_valid_theta :: SourceTyCtxt -> [PredType] -> TcM ()
1256 check_valid_theta _ []
1258 check_valid_theta ctxt theta = do
1260 warnTc (notNull dups) (dupPredWarn dups)
1261 mapM_ (check_pred_ty dflags ctxt) theta
1263 (_,dups) = removeDups tcCmpPred theta
1265 -------------------------
1266 check_pred_ty :: DynFlags -> SourceTyCtxt -> PredType -> TcM ()
1267 check_pred_ty dflags ctxt pred@(ClassP cls tys)
1268 = do { -- Class predicates are valid in all contexts
1269 ; checkTc (arity == n_tys) arity_err
1271 -- Check the form of the argument types
1272 ; mapM_ check_mono_type tys
1273 ; checkTc (check_class_pred_tys dflags ctxt tys)
1274 (predTyVarErr pred $$ how_to_allow)
1277 class_name = className cls
1278 arity = classArity cls
1280 arity_err = arityErr "Class" class_name arity n_tys
1281 how_to_allow = parens (ptext (sLit "Use -XFlexibleContexts to permit this"))
1283 check_pred_ty dflags _ pred@(EqPred ty1 ty2)
1284 = do { -- Equational constraints are valid in all contexts if type
1285 -- families are permitted
1286 ; checkTc (dopt Opt_TypeFamilies dflags) (eqPredTyErr pred)
1288 -- Check the form of the argument types
1289 ; check_mono_type ty1
1290 ; check_mono_type ty2
1293 check_pred_ty _ SigmaCtxt (IParam _ ty) = check_mono_type ty
1294 -- Implicit parameters only allowed in type
1295 -- signatures; not in instance decls, superclasses etc
1296 -- The reason for not allowing implicit params in instances is a bit
1298 -- If we allowed instance (?x::Int, Eq a) => Foo [a] where ...
1299 -- then when we saw (e :: (?x::Int) => t) it would be unclear how to
1300 -- discharge all the potential usas of the ?x in e. For example, a
1301 -- constraint Foo [Int] might come out of e,and applying the
1302 -- instance decl would show up two uses of ?x.
1305 check_pred_ty _ _ sty = failWithTc (badPredTyErr sty)
1307 -------------------------
1308 check_class_pred_tys :: DynFlags -> SourceTyCtxt -> [Type] -> Bool
1309 check_class_pred_tys dflags ctxt tys
1311 TypeCtxt -> True -- {-# SPECIALISE instance Eq (T Int) #-} is fine
1312 InstThetaCtxt -> flexible_contexts || undecidable_ok || all tcIsTyVarTy tys
1313 -- Further checks on head and theta in
1314 -- checkInstTermination
1315 _ -> flexible_contexts || all tyvar_head tys
1317 flexible_contexts = dopt Opt_FlexibleContexts dflags
1318 undecidable_ok = dopt Opt_UndecidableInstances dflags
1320 -------------------------
1321 tyvar_head :: Type -> Bool
1322 tyvar_head ty -- Haskell 98 allows predicates of form
1323 | tcIsTyVarTy ty = True -- C (a ty1 .. tyn)
1324 | otherwise -- where a is a type variable
1325 = case tcSplitAppTy_maybe ty of
1326 Just (ty, _) -> tyvar_head ty
1333 is ambiguous if P contains generic variables
1334 (i.e. one of the Vs) that are not mentioned in tau
1336 However, we need to take account of functional dependencies
1337 when we speak of 'mentioned in tau'. Example:
1338 class C a b | a -> b where ...
1340 forall x y. (C x y) => x
1341 is not ambiguous because x is mentioned and x determines y
1343 NB; the ambiguity check is only used for *user* types, not for types
1344 coming from inteface files. The latter can legitimately have
1345 ambiguous types. Example
1347 class S a where s :: a -> (Int,Int)
1348 instance S Char where s _ = (1,1)
1349 f:: S a => [a] -> Int -> (Int,Int)
1350 f (_::[a]) x = (a*x,b)
1351 where (a,b) = s (undefined::a)
1353 Here the worker for f gets the type
1354 fw :: forall a. S a => Int -> (# Int, Int #)
1356 If the list of tv_names is empty, we have a monotype, and then we
1357 don't need to check for ambiguity either, because the test can't fail
1362 checkAmbiguity :: [TyVar] -> ThetaType -> TyVarSet -> TcM ()
1363 checkAmbiguity forall_tyvars theta tau_tyvars
1364 = mapM_ complain (filter is_ambig theta)
1366 complain pred = addErrTc (ambigErr pred)
1367 extended_tau_vars = grow theta tau_tyvars
1369 -- See Note [Implicit parameters and ambiguity] in TcSimplify
1370 is_ambig pred = isClassPred pred &&
1371 any ambig_var (varSetElems (tyVarsOfPred pred))
1373 ambig_var ct_var = (ct_var `elem` forall_tyvars) &&
1374 not (ct_var `elemVarSet` extended_tau_vars)
1376 ambigErr :: PredType -> SDoc
1378 = sep [ptext (sLit "Ambiguous constraint") <+> quotes (pprPred pred),
1379 nest 4 (ptext (sLit "At least one of the forall'd type variables mentioned by the constraint") $$
1380 ptext (sLit "must be reachable from the type after the '=>'"))]
1383 In addition, GHC insists that at least one type variable
1384 in each constraint is in V. So we disallow a type like
1385 forall a. Eq b => b -> b
1386 even in a scope where b is in scope.
1389 checkFreeness :: [Var] -> [PredType] -> TcM ()
1390 checkFreeness forall_tyvars theta
1391 = do { flexible_contexts <- doptM Opt_FlexibleContexts
1392 ; unless flexible_contexts $ mapM_ complain (filter is_free theta) }
1394 is_free pred = not (isIPPred pred)
1395 && not (any bound_var (varSetElems (tyVarsOfPred pred)))
1396 bound_var ct_var = ct_var `elem` forall_tyvars
1397 complain pred = addErrTc (freeErr pred)
1399 freeErr :: PredType -> SDoc
1401 = sep [ ptext (sLit "All of the type variables in the constraint") <+>
1402 quotes (pprPred pred)
1403 , ptext (sLit "are already in scope") <+>
1404 ptext (sLit "(at least one must be universally quantified here)")
1406 ptext (sLit "(Use -XFlexibleContexts to lift this restriction)")
1411 checkThetaCtxt :: SourceTyCtxt -> ThetaType -> SDoc
1412 checkThetaCtxt ctxt theta
1413 = vcat [ptext (sLit "In the context:") <+> pprTheta theta,
1414 ptext (sLit "While checking") <+> pprSourceTyCtxt ctxt ]
1416 badPredTyErr, eqPredTyErr, predTyVarErr :: PredType -> SDoc
1417 badPredTyErr sty = ptext (sLit "Illegal constraint") <+> pprPred sty
1418 eqPredTyErr sty = ptext (sLit "Illegal equational constraint") <+> pprPred sty
1420 parens (ptext (sLit "Use -XTypeFamilies to permit this"))
1421 predTyVarErr pred = sep [ptext (sLit "Non type-variable argument"),
1422 nest 2 (ptext (sLit "in the constraint:") <+> pprPred pred)]
1423 dupPredWarn :: [[PredType]] -> SDoc
1424 dupPredWarn dups = ptext (sLit "Duplicate constraint(s):") <+> pprWithCommas pprPred (map head dups)
1426 arityErr :: Outputable a => String -> a -> Int -> Int -> SDoc
1427 arityErr kind name n m
1428 = hsep [ text kind, quotes (ppr name), ptext (sLit "should have"),
1429 n_arguments <> comma, text "but has been given", int m]
1431 n_arguments | n == 0 = ptext (sLit "no arguments")
1432 | n == 1 = ptext (sLit "1 argument")
1433 | True = hsep [int n, ptext (sLit "arguments")]
1436 notMonoType :: TcType -> TcM a
1438 = do { ty' <- zonkTcType ty
1439 ; env0 <- tcInitTidyEnv
1440 ; let (env1, tidy_ty) = tidyOpenType env0 ty'
1441 msg = ptext (sLit "Cannot match a monotype with") <+> quotes (ppr tidy_ty)
1442 ; failWithTcM (env1, msg) }
1444 notMonoArgs :: TcType -> TcM a
1446 = do { ty' <- zonkTcType ty
1447 ; env0 <- tcInitTidyEnv
1448 ; let (env1, tidy_ty) = tidyOpenType env0 ty'
1449 msg = ptext (sLit "Arguments of type synonym families must be monotypes") <+> quotes (ppr tidy_ty)
1450 ; failWithTcM (env1, msg) }
1454 %************************************************************************
1456 \subsection{Checking for a decent instance head type}
1458 %************************************************************************
1460 @checkValidInstHead@ checks the type {\em and} its syntactic constraints:
1461 it must normally look like: @instance Foo (Tycon a b c ...) ...@
1463 The exceptions to this syntactic checking: (1)~if the @GlasgowExts@
1464 flag is on, or (2)~the instance is imported (they must have been
1465 compiled elsewhere). In these cases, we let them go through anyway.
1467 We can also have instances for functions: @instance Foo (a -> b) ...@.
1470 checkValidInstHead :: Type -> TcM (Class, [TcType])
1472 checkValidInstHead ty -- Should be a source type
1473 = case tcSplitPredTy_maybe ty of {
1474 Nothing -> failWithTc (instTypeErr (ppr ty) empty) ;
1477 case getClassPredTys_maybe pred of {
1478 Nothing -> failWithTc (instTypeErr (pprPred pred) empty) ;
1479 Just (clas,tys) -> do
1482 mapM_ check_mono_type tys
1483 check_inst_head dflags clas tys
1487 check_inst_head :: DynFlags -> Class -> [Type] -> TcM ()
1488 check_inst_head dflags clas tys
1489 -- If GlasgowExts then check at least one isn't a type variable
1490 = do checkTc (dopt Opt_TypeSynonymInstances dflags ||
1491 all tcInstHeadTyNotSynonym tys)
1492 (instTypeErr (pprClassPred clas tys) head_type_synonym_msg)
1493 checkTc (dopt Opt_FlexibleInstances dflags ||
1494 all tcInstHeadTyAppAllTyVars tys)
1495 (instTypeErr (pprClassPred clas tys) head_type_args_tyvars_msg)
1496 checkTc (dopt Opt_MultiParamTypeClasses dflags ||
1498 (instTypeErr (pprClassPred clas tys) head_one_type_msg)
1499 mapM_ check_mono_type tys
1500 -- For now, I only allow tau-types (not polytypes) in
1501 -- the head of an instance decl.
1502 -- E.g. instance C (forall a. a->a) is rejected
1503 -- One could imagine generalising that, but I'm not sure
1504 -- what all the consequences might be
1507 head_type_synonym_msg = parens (
1508 text "All instance types must be of the form (T t1 ... tn)" $$
1509 text "where T is not a synonym." $$
1510 text "Use -XTypeSynonymInstances if you want to disable this.")
1512 head_type_args_tyvars_msg = parens (vcat [
1513 text "All instance types must be of the form (T a1 ... an)",
1514 text "where a1 ... an are type *variables*,",
1515 text "and each type variable appears at most once in the instance head.",
1516 text "Use -XFlexibleInstances if you want to disable this."])
1518 head_one_type_msg = parens (
1519 text "Only one type can be given in an instance head." $$
1520 text "Use -XMultiParamTypeClasses if you want to allow more.")
1522 instTypeErr :: SDoc -> SDoc -> SDoc
1523 instTypeErr pp_ty msg
1524 = sep [ptext (sLit "Illegal instance declaration for") <+> quotes pp_ty,
1529 %************************************************************************
1531 \subsection{Checking instance for termination}
1533 %************************************************************************
1537 checkValidInstance :: [TyVar] -> ThetaType -> Class -> [TcType] -> TcM ()
1538 checkValidInstance tyvars theta clas inst_tys
1539 = do { undecidable_ok <- doptM Opt_UndecidableInstances
1541 ; checkValidTheta InstThetaCtxt theta
1542 ; checkAmbiguity tyvars theta (tyVarsOfTypes inst_tys)
1544 -- Check that instance inference will terminate (if we care)
1545 -- For Haskell 98 this will already have been done by checkValidTheta,
1546 -- but as we may be using other extensions we need to check.
1547 ; unless undecidable_ok $
1548 mapM_ addErrTc (checkInstTermination inst_tys theta)
1550 -- The Coverage Condition
1551 ; checkTc (undecidable_ok || checkInstCoverage clas inst_tys)
1552 (instTypeErr (pprClassPred clas inst_tys) msg)
1555 msg = parens (vcat [ptext (sLit "the Coverage Condition fails for one of the functional dependencies;"),
1559 Termination test: the so-called "Paterson conditions" (see Section 5 of
1560 "Understanding functionsl dependencies via Constraint Handling Rules,
1563 We check that each assertion in the context satisfies:
1564 (1) no variable has more occurrences in the assertion than in the head, and
1565 (2) the assertion has fewer constructors and variables (taken together
1566 and counting repetitions) than the head.
1567 This is only needed with -fglasgow-exts, as Haskell 98 restrictions
1568 (which have already been checked) guarantee termination.
1570 The underlying idea is that
1572 for any ground substitution, each assertion in the
1573 context has fewer type constructors than the head.
1577 checkInstTermination :: [TcType] -> ThetaType -> [Message]
1578 checkInstTermination tys theta
1579 = mapCatMaybes check theta
1582 size = sizeTypes tys
1584 | not (null (fvPred pred \\ fvs))
1585 = Just (predUndecErr pred nomoreMsg $$ parens undecidableMsg)
1586 | sizePred pred >= size
1587 = Just (predUndecErr pred smallerMsg $$ parens undecidableMsg)
1591 predUndecErr :: PredType -> SDoc -> SDoc
1592 predUndecErr pred msg = sep [msg,
1593 nest 2 (ptext (sLit "in the constraint:") <+> pprPred pred)]
1595 nomoreMsg, smallerMsg, undecidableMsg :: SDoc
1596 nomoreMsg = ptext (sLit "Variable occurs more often in a constraint than in the instance head")
1597 smallerMsg = ptext (sLit "Constraint is no smaller than the instance head")
1598 undecidableMsg = ptext (sLit "Use -fallow-undecidable-instances to permit this")
1602 %************************************************************************
1604 Checking the context of a derived instance declaration
1606 %************************************************************************
1608 Note [Exotic derived instance contexts]
1609 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1610 In a 'derived' instance declaration, we *infer* the context. It's a
1611 bit unclear what rules we should apply for this; the Haskell report is
1612 silent. Obviously, constraints like (Eq a) are fine, but what about
1613 data T f a = MkT (f a) deriving( Eq )
1614 where we'd get an Eq (f a) constraint. That's probably fine too.
1616 One could go further: consider
1617 data T a b c = MkT (Foo a b c) deriving( Eq )
1618 instance (C Int a, Eq b, Eq c) => Eq (Foo a b c)
1620 Notice that this instance (just) satisfies the Paterson termination
1621 conditions. Then we *could* derive an instance decl like this:
1623 instance (C Int a, Eq b, Eq c) => Eq (T a b c)
1625 even though there is no instance for (C Int a), because there just
1626 *might* be an instance for, say, (C Int Bool) at a site where we
1627 need the equality instance for T's.
1629 However, this seems pretty exotic, and it's quite tricky to allow
1630 this, and yet give sensible error messages in the (much more common)
1631 case where we really want that instance decl for C.
1633 So for now we simply require that the derived instance context
1634 should have only type-variable constraints.
1636 Here is another example:
1637 data Fix f = In (f (Fix f)) deriving( Eq )
1638 Here, if we are prepared to allow -fallow-undecidable-instances we
1639 could derive the instance
1640 instance Eq (f (Fix f)) => Eq (Fix f)
1641 but this is so delicate that I don't think it should happen inside
1642 'deriving'. If you want this, write it yourself!
1644 NB: if you want to lift this condition, make sure you still meet the
1645 termination conditions! If not, the deriving mechanism generates
1646 larger and larger constraints. Example:
1648 data Seq a = Cons a (Seq (Succ a)) | Nil deriving Show
1650 Note the lack of a Show instance for Succ. First we'll generate
1651 instance (Show (Succ a), Show a) => Show (Seq a)
1653 instance (Show (Succ (Succ a)), Show (Succ a), Show a) => Show (Seq a)
1654 and so on. Instead we want to complain of no instance for (Show (Succ a)).
1658 Allow constraints which consist only of type variables, with no repeats.
1661 validDerivPred :: PredType -> Bool
1662 validDerivPred (ClassP _ tys) = hasNoDups fvs && sizeTypes tys == length fvs
1663 where fvs = fvTypes tys
1664 validDerivPred _ = False
1667 %************************************************************************
1669 Checking type instance well-formedness and termination
1671 %************************************************************************
1674 -- Check that a "type instance" is well-formed (which includes decidability
1675 -- unless -fallow-undecidable-instances is given).
1677 checkValidTypeInst :: [Type] -> Type -> TcM ()
1678 checkValidTypeInst typats rhs
1679 = do { -- left-hand side contains no type family applications
1680 -- (vanilla synonyms are fine, though)
1681 ; mapM_ checkTyFamFreeness typats
1683 -- the right-hand side is a tau type
1684 ; checkTc (isTauTy rhs) $
1687 -- we have a decidable instance unless otherwise permitted
1688 ; undecidable_ok <- doptM Opt_UndecidableInstances
1689 ; unless undecidable_ok $
1690 mapM_ addErrTc (checkFamInst typats (tyFamInsts rhs))
1693 -- Make sure that each type family instance is
1694 -- (1) strictly smaller than the lhs,
1695 -- (2) mentions no type variable more often than the lhs, and
1696 -- (3) does not contain any further type family instances.
1698 checkFamInst :: [Type] -- lhs
1699 -> [(TyCon, [Type])] -- type family instances
1701 checkFamInst lhsTys famInsts
1702 = mapCatMaybes check famInsts
1704 size = sizeTypes lhsTys
1705 fvs = fvTypes lhsTys
1707 | not (all isTyFamFree tys)
1708 = Just (famInstUndecErr famInst nestedMsg $$ parens undecidableMsg)
1709 | not (null (fvTypes tys \\ fvs))
1710 = Just (famInstUndecErr famInst nomoreVarMsg $$ parens undecidableMsg)
1711 | size <= sizeTypes tys
1712 = Just (famInstUndecErr famInst smallerAppMsg $$ parens undecidableMsg)
1716 famInst = TyConApp tc tys
1718 -- Ensure that no type family instances occur in a type.
1720 checkTyFamFreeness :: Type -> TcM ()
1721 checkTyFamFreeness ty
1722 = checkTc (isTyFamFree ty) $
1723 tyFamInstInIndexErr ty
1725 -- Check that a type does not contain any type family applications.
1727 isTyFamFree :: Type -> Bool
1728 isTyFamFree = null . tyFamInsts
1732 tyFamInstInIndexErr :: Type -> SDoc
1733 tyFamInstInIndexErr ty
1734 = hang (ptext (sLit "Illegal type family application in type instance") <>
1738 polyTyErr :: Type -> SDoc
1740 = hang (ptext (sLit "Illegal polymorphic type in type instance") <> colon) 4 $
1743 famInstUndecErr :: Type -> SDoc -> SDoc
1744 famInstUndecErr ty msg
1746 nest 2 (ptext (sLit "in the type family application:") <+>
1749 nestedMsg, nomoreVarMsg, smallerAppMsg :: SDoc
1750 nestedMsg = ptext (sLit "Nested type family application")
1751 nomoreVarMsg = ptext (sLit "Variable occurs more often than in instance head")
1752 smallerAppMsg = ptext (sLit "Application is no smaller than the instance head")
1756 %************************************************************************
1758 \subsection{Auxiliary functions}
1760 %************************************************************************
1763 -- Free variables of a type, retaining repetitions, and expanding synonyms
1764 fvType :: Type -> [TyVar]
1765 fvType ty | Just exp_ty <- tcView ty = fvType exp_ty
1766 fvType (TyVarTy tv) = [tv]
1767 fvType (TyConApp _ tys) = fvTypes tys
1768 fvType (PredTy pred) = fvPred pred
1769 fvType (FunTy arg res) = fvType arg ++ fvType res
1770 fvType (AppTy fun arg) = fvType fun ++ fvType arg
1771 fvType (ForAllTy tyvar ty) = filter (/= tyvar) (fvType ty)
1773 fvTypes :: [Type] -> [TyVar]
1774 fvTypes tys = concat (map fvType tys)
1776 fvPred :: PredType -> [TyVar]
1777 fvPred (ClassP _ tys') = fvTypes tys'
1778 fvPred (IParam _ ty) = fvType ty
1779 fvPred (EqPred ty1 ty2) = fvType ty1 ++ fvType ty2
1781 -- Size of a type: the number of variables and constructors
1782 sizeType :: Type -> Int
1783 sizeType ty | Just exp_ty <- tcView ty = sizeType exp_ty
1784 sizeType (TyVarTy _) = 1
1785 sizeType (TyConApp _ tys) = sizeTypes tys + 1
1786 sizeType (PredTy pred) = sizePred pred
1787 sizeType (FunTy arg res) = sizeType arg + sizeType res + 1
1788 sizeType (AppTy fun arg) = sizeType fun + sizeType arg
1789 sizeType (ForAllTy _ ty) = sizeType ty
1791 sizeTypes :: [Type] -> Int
1792 sizeTypes xs = sum (map sizeType xs)
1794 sizePred :: PredType -> Int
1795 sizePred (ClassP _ tys') = sizeTypes tys'
1796 sizePred (IParam _ ty) = sizeType ty
1797 sizePred (EqPred ty1 ty2) = sizeType ty1 + sizeType ty2