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,
36 tcInstType, tcInstSigType,
37 tcInstSkolTyVars, tcInstSkolType,
38 tcSkolSigType, tcSkolSigTyVars, occurCheckErr, execTcTyVarBinds,
40 --------------------------------
41 -- Checking type validity
42 Rank, UserTypeCtxt(..), checkValidType, checkValidMonoType,
43 SourceTyCtxt(..), checkValidTheta,
44 checkValidInstHead, checkValidInstance,
45 checkInstTermination, checkValidTypeInst, checkTyFamFreeness, checkKinds,
46 checkUpdateMeta, updateMeta, checkTauTvUpdate, fillBoxWithTau, unifyKindCtxt,
47 unifyKindMisMatch, validDerivPred, arityErr, notMonoType, notMonoArgs,
48 growPredTyVars, growTyVars, growThetaTyVars,
50 --------------------------------
52 zonkType, zonkTcPredType,
53 zonkTcTyVar, zonkTcTyVars, zonkTcTyVarsAndFV, zonkSigTyVar,
54 zonkQuantifiedTyVar, zonkQuantifiedTyVars,
55 zonkTcType, zonkTcTypes, zonkTcThetaType,
56 zonkTcKindToKind, zonkTcKind, zonkTopTyVar,
58 readKindVar, writeKindVar
61 #include "HsVersions.h"
73 import HsSyn -- HsType
74 import TcRnMonad -- TcType, amongst others
91 import Data.List ( (\\) )
95 %************************************************************************
97 Instantiation in general
99 %************************************************************************
102 tcInstType :: ([TyVar] -> TcM [TcTyVar]) -- How to instantiate the type variables
103 -> TcType -- Type to instantiate
104 -> TcM ([TcTyVar], TcThetaType, TcType) -- Result
105 -- (type vars (excl coercion vars), preds (incl equalities), rho)
106 tcInstType inst_tyvars ty
107 = case tcSplitForAllTys ty of
108 ([], rho) -> let -- There may be overloading despite no type variables;
109 -- (?x :: Int) => Int -> Int
110 (theta, tau) = tcSplitPhiTy rho
112 return ([], theta, tau)
114 (tyvars, rho) -> do { tyvars' <- inst_tyvars tyvars
116 ; let tenv = zipTopTvSubst tyvars (mkTyVarTys tyvars')
117 -- Either the tyvars are freshly made, by inst_tyvars,
118 -- or (in the call from tcSkolSigType) any nested foralls
119 -- have different binders. Either way, zipTopTvSubst is ok
121 ; let (theta, tau) = tcSplitPhiTy (substTy tenv rho)
122 ; return (tyvars', theta, tau) }
126 %************************************************************************
130 %************************************************************************
132 Can't be in TcUnify, as we also need it in TcTyFuns.
136 -- False <=> the two args are (actual, expected) respectively
137 -- True <=> the two args are (expected, actual) respectively
139 checkUpdateMeta :: SwapFlag
140 -> TcTyVar -> IORef MetaDetails -> TcType -> TcM ()
141 -- Update tv1, which is flexi; occurs check is alrady done
142 -- The 'check' version does a kind check too
143 -- We do a sub-kind check here: we might unify (a b) with (c d)
144 -- where b::*->* and d::*; this should fail
146 checkUpdateMeta swapped tv1 ref1 ty2
147 = do { checkKinds swapped tv1 ty2
148 ; updateMeta tv1 ref1 ty2 }
150 updateMeta :: TcTyVar -> IORef MetaDetails -> TcType -> TcM ()
151 updateMeta tv1 ref1 ty2
152 = ASSERT( isMetaTyVar tv1 )
153 ASSERT( isBoxyTyVar tv1 || isTauTy ty2 )
154 do { ASSERTM2( do { details <- readMetaTyVar tv1; return (isFlexi details) }, ppr tv1 )
155 ; traceTc (text "updateMeta" <+> ppr tv1 <+> text ":=" <+> ppr ty2)
156 ; writeMutVar ref1 (Indirect ty2)
160 checkKinds :: Bool -> TyVar -> Type -> TcM ()
161 checkKinds swapped tv1 ty2
162 -- We're about to unify a type variable tv1 with a non-tyvar-type ty2.
163 -- ty2 has been zonked at this stage, which ensures that
164 -- its kind has as much boxity information visible as possible.
165 | tk2 `isSubKind` tk1 = return ()
168 -- Either the kinds aren't compatible
169 -- (can happen if we unify (a b) with (c d))
170 -- or we are unifying a lifted type variable with an
171 -- unlifted type: e.g. (id 3#) is illegal
172 = addErrCtxtM (unifyKindCtxt swapped tv1 ty2) $
173 unifyKindMisMatch k1 k2
175 (k1,k2) | swapped = (tk2,tk1)
176 | otherwise = (tk1,tk2)
181 checkTauTvUpdate :: TcTyVar -> TcType -> TcM (Maybe TcType)
182 -- (checkTauTvUpdate tv ty)
183 -- We are about to update the TauTv tv with ty.
184 -- Check (a) that tv doesn't occur in ty (occurs check)
185 -- (b) that ty is a monotype
186 -- Furthermore, in the interest of (b), if you find an
187 -- empty box (BoxTv that is Flexi), fill it in with a TauTv
189 -- We have three possible outcomes:
190 -- (1) Return the (non-boxy) type to update the type variable with,
191 -- [we know the update is ok!]
192 -- (2) return Nothing, or
193 -- [we cannot tell whether the update is ok right now]
195 -- [the update is definitely invalid]
196 -- We return Nothing in case the tv occurs in ty *under* a type family
197 -- application. In this case, we must not update tv (to avoid a cyclic type
198 -- term), but we also cannot fail claiming an infinite type. Given
200 -- type instance F Int = Int
203 -- This is perfectly reasonable, if we later get a ~ Int.
205 checkTauTvUpdate orig_tv orig_ty
206 = do { result <- go orig_ty
208 Right ty -> return $ Just ty
209 Left True -> return $ Nothing
210 Left False -> occurCheckErr (mkTyVarTy orig_tv) orig_ty
213 go :: TcType -> TcM (Either Bool TcType)
215 -- Right ty if everything is fine
216 -- Left True if orig_tv occurs in orig_ty, but under a type family app
217 -- Left False if orig_tv occurs in orig_ty (with no type family app)
218 -- It fails if it encounters a forall type, except as an argument for a
219 -- closed type synonym that expands to a tau type.
221 | isSynTyCon tc = go_syn tc tys
222 | otherwise = do { tys' <- mapM go tys
223 ; return $ occurs (TyConApp tc) tys' }
224 go (PredTy p) = do { p' <- go_pred p
225 ; return $ occurs1 PredTy p' }
226 go (FunTy arg res) = do { arg' <- go arg
228 ; return $ occurs2 FunTy arg' res' }
229 go (AppTy fun arg) = do { fun' <- go fun
231 ; return $ occurs2 mkAppTy fun' arg' }
232 -- NB the mkAppTy; we might have instantiated a
233 -- type variable to a type constructor, so we need
234 -- to pull the TyConApp to the top.
235 go (ForAllTy _ _) = notMonoType orig_ty -- (b)
238 | orig_tv == tv = return $ Left False -- (a)
239 | isTcTyVar tv = go_tyvar tv (tcTyVarDetails tv)
240 | otherwise = return $ Right (TyVarTy tv)
241 -- Ordinary (non Tc) tyvars
242 -- occur inside quantified types
244 go_pred (ClassP c tys) = do { tys' <- mapM go tys
245 ; return $ occurs (ClassP c) tys' }
246 go_pred (IParam n ty) = do { ty' <- go ty
247 ; return $ occurs1 (IParam n) ty' }
248 go_pred (EqPred t1 t2) = do { t1' <- go t1
250 ; return $ occurs2 EqPred t1' t2' }
252 go_tyvar tv (SkolemTv _) = return $ Right (TyVarTy tv)
253 go_tyvar tv (MetaTv box ref)
254 = do { cts <- readMutVar ref
258 BoxTv -> do { ty <- fillBoxWithTau tv ref
259 ; return $ Right ty }
260 _ -> return $ Right (TyVarTy tv)
263 -- go_syn is called for synonyms only
264 -- See Note [Type synonyms and the occur check]
266 | not (isTauTyCon tc)
267 = notMonoType orig_ty -- (b) again
269 = do { (_msgs, mb_tys') <- tryTc (mapM go tys)
272 -- we had a type error => forall in type parameters
274 | isOpenTyCon tc -> notMonoArgs (TyConApp tc tys)
275 -- Synonym families must have monotype args
276 | otherwise -> go (expectJust "checkTauTvUpdate(1)"
277 (tcView (TyConApp tc tys)))
278 -- Try again, expanding the synonym
280 -- no type error, but need to test whether occurs check happend
282 case occurs id tys' of
284 | isOpenTyCon tc -> return $ Left True
285 -- Variable occured under type family application
286 | otherwise -> go (expectJust "checkTauTvUpdate(2)"
287 (tcView (TyConApp tc tys)))
288 -- Try again, expanding the synonym
289 Right raw_tys' -> return $ Right (TyConApp tc raw_tys')
290 -- Retain the synonym (the common case)
293 -- Left results (= occurrence of orig_ty) dominate and
294 -- (Left False) (= fatal occurrence) dominates over (Left True)
295 occurs :: ([a] -> b) -> [Either Bool a] -> Either Bool b
296 occurs c = either Left (Right . c) . foldr combine (Right [])
298 combine (Left famInst1) (Left famInst2) = Left (famInst1 && famInst2)
299 combine (Right _ ) (Left famInst) = Left famInst
300 combine (Left famInst) (Right _) = Left famInst
301 combine (Right arg) (Right args) = Right (arg:args)
303 occurs1 c x = occurs (\[x'] -> c x') [x]
304 occurs2 c x y = occurs (\[x', y'] -> c x' y') [x, y]
306 fillBoxWithTau :: BoxyTyVar -> IORef MetaDetails -> TcM TcType
307 -- (fillBoxWithTau tv ref) fills ref with a freshly allocated
308 -- tau-type meta-variable, whose print-name is the same as tv
309 -- Choosing the same name is good: when we instantiate a function
310 -- we allocate boxy tyvars with the same print-name as the quantified
311 -- tyvar; and then we often fill the box with a tau-tyvar, and again
312 -- we want to choose the same name.
313 fillBoxWithTau tv ref
314 = do { tv' <- tcInstTyVar tv -- Do not gratuitously forget
315 ; let tau = mkTyVarTy tv' -- name of the type variable
316 ; writeMutVar ref (Indirect tau)
320 Note [Type synonyms and the occur check]
322 Basically we want to update tv1 := ps_ty2
323 because ps_ty2 has type-synonym info, which improves later error messages
328 f :: (A a -> a -> ()) -> ()
334 In the application (p x), we try to match "t" with "A t". If we go
335 ahead and bind t to A t (= ps_ty2), we'll lead the type checker into
336 an infinite loop later.
337 But we should not reject the program, because A t = ().
338 Rather, we should bind t to () (= non_var_ty2).
342 Execute a bag of type variable bindings.
345 execTcTyVarBinds :: TcTyVarBinds -> TcM ()
346 execTcTyVarBinds = mapM_ execTcTyVarBind . bagToList
348 execTcTyVarBind (TcTyVarBind tv ty)
349 = do { ASSERTM2( do { details <- readMetaTyVar tv
350 ; return (isFlexi details) }, ppr tv )
351 ; ty' <- if isCoVar tv
353 else do { maybe_ty <- checkTauTvUpdate tv ty
355 Nothing -> pprPanic "TcRnMonad.execTcTyBind"
356 (ppr tv <+> text ":=" <+> ppr ty)
357 Just ty' -> return ty'
359 ; writeMetaTyVar tv ty'
363 Error mesages in case of kind mismatch.
366 unifyKindMisMatch :: TcKind -> TcKind -> TcM ()
367 unifyKindMisMatch ty1 ty2 = do
368 ty1' <- zonkTcKind ty1
369 ty2' <- zonkTcKind ty2
371 msg = hang (ptext (sLit "Couldn't match kind"))
372 2 (sep [quotes (ppr ty1'),
373 ptext (sLit "against"),
377 unifyKindCtxt :: Bool -> TyVar -> Type -> TidyEnv -> TcM (TidyEnv, SDoc)
378 unifyKindCtxt swapped tv1 ty2 tidy_env -- not swapped => tv1 expected, ty2 inferred
379 -- tv1 and ty2 are zonked already
382 msg = (env2, ptext (sLit "When matching the kinds of") <+>
383 sep [quotes pp_expected <+> ptext (sLit "and"), quotes pp_actual])
385 (pp_expected, pp_actual) | swapped = (pp2, pp1)
386 | otherwise = (pp1, pp2)
387 (env1, tv1') = tidyOpenTyVar tidy_env tv1
388 (env2, ty2') = tidyOpenType env1 ty2
389 pp1 = ppr tv1' <+> dcolon <+> ppr (tyVarKind tv1)
390 pp2 = ppr ty2' <+> dcolon <+> ppr (typeKind ty2)
393 Error message for failure due to an occurs check.
396 occurCheckErr :: TcType -> TcType -> TcM a
397 occurCheckErr ty containingTy
398 = do { env0 <- tcInitTidyEnv
399 ; ty' <- zonkTcType ty
400 ; containingTy' <- zonkTcType containingTy
401 ; let (env1, tidy_ty1) = tidyOpenType env0 ty'
402 (env2, tidy_ty2) = tidyOpenType env1 containingTy'
403 extra = sep [ppr tidy_ty1, char '=', ppr tidy_ty2]
404 ; failWithTcM (env2, hang msg 2 extra) }
406 msg = ptext (sLit "Occurs check: cannot construct the infinite type:")
409 %************************************************************************
413 %************************************************************************
416 newCoVars :: [(TcType,TcType)] -> TcM [CoVar]
418 = do { us <- newUniqueSupply
419 ; return [ mkCoVar (mkSysTvName uniq (fsLit "co_kv"))
421 | ((ty1,ty2), uniq) <- spec `zip` uniqsFromSupply us] }
423 newMetaCoVar :: TcType -> TcType -> TcM TcTyVar
424 newMetaCoVar ty1 ty2 = newMetaTyVar TauTv (mkCoKind ty1 ty2)
426 newKindVar :: TcM TcKind
427 newKindVar = do { uniq <- newUnique
428 ; ref <- newMutVar Flexi
429 ; return (mkTyVarTy (mkKindVar uniq ref)) }
431 newKindVars :: Int -> TcM [TcKind]
432 newKindVars n = mapM (\ _ -> newKindVar) (nOfThem n ())
436 %************************************************************************
438 SkolemTvs (immutable)
440 %************************************************************************
443 mkSkolTyVar :: Name -> Kind -> SkolemInfo -> TcTyVar
444 mkSkolTyVar name kind info = mkTcTyVar name kind (SkolemTv info)
446 tcSkolSigType :: SkolemInfo -> Type -> TcM ([TcTyVar], TcThetaType, TcType)
447 -- Instantiate a type signature with skolem constants, but
448 -- do *not* give them fresh names, because we want the name to
449 -- be in the type environment -- it is lexically scoped.
450 tcSkolSigType info ty = tcInstType (\tvs -> return (tcSkolSigTyVars info tvs)) ty
452 tcSkolSigTyVars :: SkolemInfo -> [TyVar] -> [TcTyVar]
453 -- Make skolem constants, but do *not* give them new names, as above
454 tcSkolSigTyVars info tyvars = [ mkSkolTyVar (tyVarName tv) (tyVarKind tv) info
457 tcInstSkolTyVar :: SkolemInfo -> (Name -> SrcSpan) -> TyVar -> TcM TcTyVar
458 -- Instantiate the tyvar, using
459 -- * the occ-name and kind of the supplied tyvar,
460 -- * the unique from the monad,
461 -- * the location either from the tyvar (mb_loc = Nothing)
462 -- or from mb_loc (Just loc)
463 tcInstSkolTyVar info get_loc tyvar
464 = do { uniq <- newUnique
465 ; let old_name = tyVarName tyvar
466 kind = tyVarKind tyvar
467 loc = get_loc old_name
468 new_name = mkInternalName uniq (nameOccName old_name) loc
469 ; return (mkSkolTyVar new_name kind info) }
471 tcInstSkolTyVars :: SkolemInfo -> [TyVar] -> TcM [TcTyVar]
472 -- Get the location from the monad
473 tcInstSkolTyVars info tyvars
474 = do { span <- getSrcSpanM
475 ; mapM (tcInstSkolTyVar info (const span)) tyvars }
477 tcInstSkolType :: SkolemInfo -> TcType -> TcM ([TcTyVar], TcThetaType, TcType)
478 -- Instantiate a type with fresh skolem constants
479 -- Binding location comes from the monad
480 tcInstSkolType info ty = tcInstType (tcInstSkolTyVars info) ty
482 tcInstSigType :: Bool -> SkolemInfo -> TcType -> TcM ([TcTyVar], TcThetaType, TcRhoType)
483 -- Instantiate with skolems or meta SigTvs; depending on use_skols
484 -- Always take location info from the supplied tyvars
485 tcInstSigType use_skols skol_info ty
486 = tcInstType (mapM inst_tyvar) ty
488 inst_tyvar | use_skols = tcInstSkolTyVar skol_info getSrcSpan
489 | otherwise = instMetaTyVar (SigTv skol_info)
493 %************************************************************************
495 MetaTvs (meta type variables; mutable)
497 %************************************************************************
500 newMetaTyVar :: BoxInfo -> Kind -> TcM TcTyVar
501 -- Make a new meta tyvar out of thin air
502 newMetaTyVar box_info kind
503 = do { uniq <- newUnique
504 ; ref <- newMutVar Flexi
505 ; let name = mkSysTvName uniq fs
506 fs = case box_info of
510 -- We give BoxTv and TauTv the same string, because
511 -- otherwise we get user-visible differences in error
512 -- messages, which are confusing. If you want to see
513 -- the box_info of each tyvar, use -dppr-debug
514 ; return (mkTcTyVar name kind (MetaTv box_info ref)) }
516 instMetaTyVar :: BoxInfo -> TyVar -> TcM TcTyVar
517 -- Make a new meta tyvar whose Name and Kind
518 -- come from an existing TyVar
519 instMetaTyVar box_info tyvar
520 = do { uniq <- newUnique
521 ; ref <- newMutVar Flexi
522 ; let name = setNameUnique (tyVarName tyvar) uniq
523 kind = tyVarKind tyvar
524 ; return (mkTcTyVar name kind (MetaTv box_info ref)) }
526 readMetaTyVar :: TyVar -> TcM MetaDetails
527 readMetaTyVar tyvar = ASSERT2( isMetaTyVar tyvar, ppr tyvar )
528 readMutVar (metaTvRef tyvar)
530 isFilledMetaTyVar :: TyVar -> TcM Bool
531 -- True of a filled-in (Indirect) meta type variable
533 | not (isTcTyVar tv) = return False
534 | MetaTv _ ref <- tcTyVarDetails tv
535 = do { details <- readMutVar ref
536 ; return (isIndirect details) }
537 | otherwise = return False
539 writeMetaTyVar :: TcTyVar -> TcType -> TcM ()
540 writeMetaTyVar tyvar ty
541 | not debugIsOn = writeMutVar (metaTvRef tyvar) (Indirect ty)
542 writeMetaTyVar tyvar ty
543 | not (isMetaTyVar tyvar)
544 = pprTrace "writeMetaTyVar" (ppr tyvar) $
547 = ASSERT( isMetaTyVar tyvar )
548 ASSERT2( isCoVar tyvar || typeKind ty `isSubKind` tyVarKind tyvar,
549 (ppr tyvar <+> ppr (tyVarKind tyvar))
550 $$ (ppr ty <+> ppr (typeKind ty)) )
551 do { if debugIsOn then do { details <- readMetaTyVar tyvar;
552 -- FIXME ; ASSERT2( not (isFlexi details), ppr tyvar )
553 ; WARN( not (isFlexi details), ppr tyvar )
557 ; traceTc (text "writeMetaTyVar" <+> ppr tyvar <+> text ":=" <+> ppr ty)
558 ; writeMutVar (metaTvRef tyvar) (Indirect ty) }
562 %************************************************************************
566 %************************************************************************
569 newFlexiTyVar :: Kind -> TcM TcTyVar
570 newFlexiTyVar kind = newMetaTyVar TauTv kind
572 newFlexiTyVarTy :: Kind -> TcM TcType
573 newFlexiTyVarTy kind = do
574 tc_tyvar <- newFlexiTyVar kind
575 return (TyVarTy tc_tyvar)
577 newFlexiTyVarTys :: Int -> Kind -> TcM [TcType]
578 newFlexiTyVarTys n kind = mapM newFlexiTyVarTy (nOfThem n kind)
580 tcInstTyVar :: TyVar -> TcM TcTyVar
581 -- Instantiate with a META type variable
582 tcInstTyVar tyvar = instMetaTyVar TauTv tyvar
584 tcInstTyVars :: [TyVar] -> TcM ([TcTyVar], [TcType], TvSubst)
585 -- Instantiate with META type variables
587 = do { tc_tvs <- mapM tcInstTyVar tyvars
588 ; let tys = mkTyVarTys tc_tvs
589 ; return (tc_tvs, tys, zipTopTvSubst tyvars tys) }
590 -- Since the tyvars are freshly made,
591 -- they cannot possibly be captured by
592 -- any existing for-alls. Hence zipTopTvSubst
596 %************************************************************************
600 %************************************************************************
603 zonkSigTyVar :: TcTyVar -> TcM TcTyVar
605 | isSkolemTyVar sig_tv
606 = return sig_tv -- Happens in the call in TcBinds.checkDistinctTyVars
608 = ASSERT( isSigTyVar sig_tv )
609 do { ty <- zonkTcTyVar sig_tv
610 ; return (tcGetTyVar "zonkSigTyVar" ty) }
611 -- 'ty' is bound to be a type variable, because SigTvs
612 -- can only be unified with type variables
616 %************************************************************************
620 %************************************************************************
623 newBoxyTyVar :: Kind -> TcM BoxyTyVar
624 newBoxyTyVar kind = newMetaTyVar BoxTv kind
626 newBoxyTyVars :: [Kind] -> TcM [BoxyTyVar]
627 newBoxyTyVars kinds = mapM newBoxyTyVar kinds
629 newBoxyTyVarTys :: [Kind] -> TcM [BoxyType]
630 newBoxyTyVarTys kinds = do { tvs <- mapM newBoxyTyVar kinds; return (mkTyVarTys tvs) }
632 readFilledBox :: BoxyTyVar -> TcM TcType
633 -- Read the contents of the box, which should be filled in by now
634 readFilledBox box_tv = ASSERT( isBoxyTyVar box_tv )
635 do { cts <- readMetaTyVar box_tv
637 Flexi -> pprPanic "readFilledBox" (ppr box_tv)
638 Indirect ty -> return ty }
640 tcInstBoxyTyVar :: TyVar -> TcM BoxyTyVar
641 -- Instantiate with a BOXY type variable
642 tcInstBoxyTyVar tyvar = instMetaTyVar BoxTv tyvar
646 %************************************************************************
648 \subsection{Putting and getting mutable type variables}
650 %************************************************************************
652 But it's more fun to short out indirections on the way: If this
653 version returns a TyVar, then that TyVar is unbound. If it returns
654 any other type, then there might be bound TyVars embedded inside it.
656 We return Nothing iff the original box was unbound.
659 data LookupTyVarResult -- The result of a lookupTcTyVar call
660 = DoneTv TcTyVarDetails -- SkolemTv or virgin MetaTv
663 lookupTcTyVar :: TcTyVar -> TcM LookupTyVarResult
665 = ASSERT2( isTcTyVar tyvar, ppr tyvar )
667 SkolemTv _ -> return (DoneTv details)
668 MetaTv _ ref -> do { meta_details <- readMutVar ref
669 ; case meta_details of
670 Indirect ty -> return (IndirectTv ty)
671 Flexi -> return (DoneTv details) }
673 details = tcTyVarDetails tyvar
676 -- gaw 2004 We aren't shorting anything out anymore, at least for now
678 | not (isTcTyVar tyvar)
679 = pprTrace "getTcTyVar" (ppr tyvar) $
680 return (Just (mkTyVarTy tyvar))
683 = ASSERT2( isTcTyVar tyvar, ppr tyvar ) do
684 maybe_ty <- readMetaTyVar tyvar
686 Just ty -> do ty' <- short_out ty
687 writeMetaTyVar tyvar (Just ty')
690 Nothing -> return Nothing
692 short_out :: TcType -> TcM TcType
693 short_out ty@(TyVarTy tyvar)
694 | not (isTcTyVar tyvar)
698 maybe_ty <- readMetaTyVar tyvar
700 Just ty' -> do ty' <- short_out ty'
701 writeMetaTyVar tyvar (Just ty')
706 short_out other_ty = return other_ty
711 %************************************************************************
713 \subsection{Zonking -- the exernal interfaces}
715 %************************************************************************
717 ----------------- Type variables
720 zonkTcTyVars :: [TcTyVar] -> TcM [TcType]
721 zonkTcTyVars tyvars = mapM zonkTcTyVar tyvars
723 zonkTcTyVarsAndFV :: [TcTyVar] -> TcM TcTyVarSet
724 zonkTcTyVarsAndFV tyvars = tyVarsOfTypes <$> mapM zonkTcTyVar tyvars
726 zonkTcTyVar :: TcTyVar -> TcM TcType
727 zonkTcTyVar tyvar = ASSERT2( isTcTyVar tyvar, ppr tyvar)
728 zonk_tc_tyvar (\ tv -> return (TyVarTy tv)) tyvar
731 ----------------- Types
734 zonkTcType :: TcType -> TcM TcType
735 zonkTcType ty = zonkType (\ tv -> return (TyVarTy tv)) ty
737 zonkTcTypes :: [TcType] -> TcM [TcType]
738 zonkTcTypes tys = mapM zonkTcType tys
740 zonkTcThetaType :: TcThetaType -> TcM TcThetaType
741 zonkTcThetaType theta = mapM zonkTcPredType theta
743 zonkTcPredType :: TcPredType -> TcM TcPredType
744 zonkTcPredType (ClassP c ts) = ClassP c <$> zonkTcTypes ts
745 zonkTcPredType (IParam n t) = IParam n <$> zonkTcType t
746 zonkTcPredType (EqPred t1 t2) = EqPred <$> zonkTcType t1 <*> zonkTcType t2
749 ------------------- These ...ToType, ...ToKind versions
750 are used at the end of type checking
753 zonkTopTyVar :: TcTyVar -> TcM TcTyVar
754 -- zonkTopTyVar is used, at the top level, on any un-instantiated meta type variables
755 -- to default the kind of ? and ?? etc to *. This is important to ensure that
756 -- instance declarations match. For example consider
757 -- instance Show (a->b)
758 -- foo x = show (\_ -> True)
759 -- Then we'll get a constraint (Show (p ->q)) where p has argTypeKind (printed ??),
760 -- and that won't match the typeKind (*) in the instance decl.
762 -- Because we are at top level, no further constraints are going to affect these
763 -- type variables, so it's time to do it by hand. However we aren't ready
764 -- to default them fully to () or whatever, because the type-class defaulting
765 -- rules have yet to run.
768 | k `eqKind` default_k = return tv
770 = do { tv' <- newFlexiTyVar default_k
771 ; writeMetaTyVar tv (mkTyVarTy tv')
775 default_k = defaultKind k
777 zonkQuantifiedTyVars :: [TcTyVar] -> TcM [TcTyVar]
778 zonkQuantifiedTyVars = mapM zonkQuantifiedTyVar
780 zonkQuantifiedTyVar :: TcTyVar -> TcM TcTyVar
781 -- zonkQuantifiedTyVar is applied to the a TcTyVar when quantifying over it.
783 -- The quantified type variables often include meta type variables
784 -- we want to freeze them into ordinary type variables, and
785 -- default their kind (e.g. from OpenTypeKind to TypeKind)
786 -- -- see notes with Kind.defaultKind
787 -- The meta tyvar is updated to point to the new skolem TyVar. Now any
788 -- bound occurences of the original type variable will get zonked to
789 -- the immutable version.
791 -- We leave skolem TyVars alone; they are immutable.
792 zonkQuantifiedTyVar tv
793 | ASSERT2( isTcTyVar tv, ppr tv )
795 = do { kind <- zonkTcType (tyVarKind tv)
796 ; return $ setTyVarKind tv kind
798 -- It might be a skolem type variable,
799 -- for example from a user type signature
801 | otherwise -- It's a meta-type-variable
802 = do { details <- readMetaTyVar tv
804 -- Create the new, frozen, skolem type variable
805 -- We zonk to a skolem, not to a regular TcVar
806 -- See Note [Zonking to Skolem]
807 ; let final_kind = defaultKind (tyVarKind tv)
808 final_tv = mkSkolTyVar (tyVarName tv) final_kind UnkSkol
810 -- Bind the meta tyvar to the new tyvar
812 Indirect ty -> WARN( True, ppr tv $$ ppr ty )
814 -- [Sept 04] I don't think this should happen
815 -- See note [Silly Type Synonym]
817 Flexi -> writeMetaTyVar tv (mkTyVarTy final_tv)
819 -- Return the new tyvar
823 Note [Silly Type Synonyms]
824 ~~~~~~~~~~~~~~~~~~~~~~~~~~
826 type C u a = u -- Note 'a' unused
828 foo :: (forall a. C u a -> C u a) -> u
832 bar = foo (\t -> t + t)
834 * From the (\t -> t+t) we get type {Num d} => d -> d
837 * Now unify with type of foo's arg, and we get:
838 {Num (C d a)} => C d a -> C d a
841 * Now abstract over the 'a', but float out the Num (C d a) constraint
842 because it does not 'really' mention a. (see exactTyVarsOfType)
843 The arg to foo becomes
846 * So we get a dict binding for Num (C d a), which is zonked to give
848 [Note Sept 04: now that we are zonking quantified type variables
849 on construction, the 'a' will be frozen as a regular tyvar on
850 quantification, so the floated dict will still have type (C d a).
851 Which renders this whole note moot; happily!]
853 * Then the \/\a abstraction has a zonked 'a' in it.
855 All very silly. I think its harmless to ignore the problem. We'll end up with
856 a \/\a in the final result but all the occurrences of a will be zonked to ()
858 Note [Zonking to Skolem]
859 ~~~~~~~~~~~~~~~~~~~~~~~~
860 We used to zonk quantified type variables to regular TyVars. However, this
861 leads to problems. Consider this program from the regression test suite:
863 eval :: Int -> String -> String -> String
864 eval 0 root actual = evalRHS 0 root actual
867 evalRHS 0 root actual = eval 0 root actual
869 It leads to the deferral of an equality
871 (String -> String -> String) ~ a
873 which is propagated up to the toplevel (see TcSimplify.tcSimplifyInferCheck).
874 In the meantime `a' is zonked and quantified to form `evalRHS's signature.
875 This has the *side effect* of also zonking the `a' in the deferred equality
876 (which at this point is being handed around wrapped in an implication
879 Finally, the equality (with the zonked `a') will be handed back to the
880 simplifier by TcRnDriver.tcRnSrcDecls calling TcSimplify.tcSimplifyTop.
881 If we zonk `a' with a regular type variable, we will have this regular type
882 variable now floating around in the simplifier, which in many places assumes to
883 only see proper TcTyVars.
885 We can avoid this problem by zonking with a skolem. The skolem is rigid
886 (which we requirefor a quantified variable), but is still a TcTyVar that the
887 simplifier knows how to deal with.
890 %************************************************************************
892 \subsection{Zonking -- the main work-horses: zonkType, zonkTyVar}
894 %* For internal use only! *
896 %************************************************************************
899 -- For unbound, mutable tyvars, zonkType uses the function given to it
900 -- For tyvars bound at a for-all, zonkType zonks them to an immutable
901 -- type variable and zonks the kind too
903 zonkType :: (TcTyVar -> TcM Type) -- What to do with unbound mutable type variables
904 -- see zonkTcType, and zonkTcTypeToType
907 zonkType unbound_var_fn ty
910 go (TyConApp tc tys) = do tys' <- mapM go tys
911 return (TyConApp tc tys')
913 go (PredTy p) = do p' <- go_pred p
916 go (FunTy arg res) = do arg' <- go arg
918 return (FunTy arg' res')
920 go (AppTy fun arg) = do fun' <- go fun
922 return (mkAppTy fun' arg')
923 -- NB the mkAppTy; we might have instantiated a
924 -- type variable to a type constructor, so we need
925 -- to pull the TyConApp to the top.
927 -- The two interesting cases!
928 go (TyVarTy tyvar) | isTcTyVar tyvar = zonk_tc_tyvar unbound_var_fn tyvar
929 | otherwise = liftM TyVarTy $
930 zonkTyVar unbound_var_fn tyvar
931 -- Ordinary (non Tc) tyvars occur inside quantified types
933 go (ForAllTy tyvar ty) = ASSERT( isImmutableTyVar tyvar ) do
935 tyvar' <- zonkTyVar unbound_var_fn tyvar
936 return (ForAllTy tyvar' ty')
938 go_pred (ClassP c tys) = do tys' <- mapM go tys
939 return (ClassP c tys')
940 go_pred (IParam n ty) = do ty' <- go ty
941 return (IParam n ty')
942 go_pred (EqPred ty1 ty2) = do ty1' <- go ty1
944 return (EqPred ty1' ty2')
946 zonk_tc_tyvar :: (TcTyVar -> TcM Type) -- What to do for an unbound mutable var
947 -> TcTyVar -> TcM TcType
948 zonk_tc_tyvar unbound_var_fn tyvar
949 = ASSERT( isTcTyVar tyvar )
950 case tcTyVarDetails tyvar of
951 SkolemTv {} -> return (TyVarTy tyvar)
952 FlatSkol ty -> zonkType unbound_var_fn ty
953 MetaTv _ ref -> do { cts <- readMutVar ref
955 Flexi -> unbound_var_fn tyvar
956 Indirect ty -> zonkType unbound_var_fn ty }
958 -- Zonk the kind of a non-TC tyvar in case it is a coercion variable (their
959 -- kind contains types).
961 zonkTyVar :: (TcTyVar -> TcM Type) -- What to do for an unbound mutable var
962 -> TyVar -> TcM TyVar
963 zonkTyVar unbound_var_fn tv
965 = do { kind <- zonkType unbound_var_fn (tyVarKind tv)
966 ; return $ setTyVarKind tv kind
968 | otherwise = return tv
973 %************************************************************************
977 %************************************************************************
980 readKindVar :: KindVar -> TcM (MetaDetails)
981 writeKindVar :: KindVar -> TcKind -> TcM ()
982 readKindVar kv = readMutVar (kindVarRef kv)
983 writeKindVar kv val = writeMutVar (kindVarRef kv) (Indirect val)
986 zonkTcKind :: TcKind -> TcM TcKind
987 zonkTcKind k = zonkTcType k
990 zonkTcKindToKind :: TcKind -> TcM Kind
991 -- When zonking a TcKind to a kind, we need to instantiate kind variables,
992 -- Haskell specifies that * is to be used, so we follow that.
993 zonkTcKindToKind k = zonkType (\ _ -> return liftedTypeKind) k
996 %************************************************************************
998 \subsection{Checking a user type}
1000 %************************************************************************
1002 When dealing with a user-written type, we first translate it from an HsType
1003 to a Type, performing kind checking, and then check various things that should
1004 be true about it. We don't want to perform these checks at the same time
1005 as the initial translation because (a) they are unnecessary for interface-file
1006 types and (b) when checking a mutually recursive group of type and class decls,
1007 we can't "look" at the tycons/classes yet. Also, the checks are are rather
1008 diverse, and used to really mess up the other code.
1010 One thing we check for is 'rank'.
1012 Rank 0: monotypes (no foralls)
1013 Rank 1: foralls at the front only, Rank 0 inside
1014 Rank 2: foralls at the front, Rank 1 on left of fn arrow,
1016 basic ::= tyvar | T basic ... basic
1018 r2 ::= forall tvs. cxt => r2a
1019 r2a ::= r1 -> r2a | basic
1020 r1 ::= forall tvs. cxt => r0
1021 r0 ::= r0 -> r0 | basic
1023 Another thing is to check that type synonyms are saturated.
1024 This might not necessarily show up in kind checking.
1026 data T k = MkT (k Int)
1031 checkValidType :: UserTypeCtxt -> Type -> TcM ()
1032 -- Checks that the type is valid for the given context
1033 checkValidType ctxt ty = do
1034 traceTc (text "checkValidType" <+> ppr ty)
1035 unboxed <- doptM Opt_UnboxedTuples
1036 rank2 <- doptM Opt_Rank2Types
1037 rankn <- doptM Opt_RankNTypes
1038 polycomp <- doptM Opt_PolymorphicComponents
1040 gen_rank n | rankn = ArbitraryRank
1042 | otherwise = Rank n
1045 DefaultDeclCtxt-> MustBeMonoType
1046 ResSigCtxt -> MustBeMonoType
1047 LamPatSigCtxt -> gen_rank 0
1048 BindPatSigCtxt -> gen_rank 0
1049 TySynCtxt _ -> gen_rank 0
1050 GenPatCtxt -> gen_rank 1
1051 -- This one is a bit of a hack
1052 -- See the forall-wrapping in TcClassDcl.mkGenericInstance
1054 ExprSigCtxt -> gen_rank 1
1055 FunSigCtxt _ -> gen_rank 1
1056 ConArgCtxt _ | polycomp -> gen_rank 2
1057 -- We are given the type of the entire
1058 -- constructor, hence rank 1
1059 | otherwise -> gen_rank 1
1061 ForSigCtxt _ -> gen_rank 1
1062 SpecInstCtxt -> gen_rank 1
1063 ThBrackCtxt -> gen_rank 1
1065 actual_kind = typeKind ty
1067 kind_ok = case ctxt of
1068 TySynCtxt _ -> True -- Any kind will do
1069 ThBrackCtxt -> True -- Any kind will do
1070 ResSigCtxt -> isSubOpenTypeKind actual_kind
1071 ExprSigCtxt -> isSubOpenTypeKind actual_kind
1072 GenPatCtxt -> isLiftedTypeKind actual_kind
1073 ForSigCtxt _ -> isLiftedTypeKind actual_kind
1074 _ -> isSubArgTypeKind actual_kind
1076 ubx_tup = case ctxt of
1077 TySynCtxt _ | unboxed -> UT_Ok
1078 ExprSigCtxt | unboxed -> UT_Ok
1079 ThBrackCtxt | unboxed -> UT_Ok
1082 -- Check the internal validity of the type itself
1083 check_type rank ubx_tup ty
1085 -- Check that the thing has kind Type, and is lifted if necessary
1086 -- Do this second, becuase we can't usefully take the kind of an
1087 -- ill-formed type such as (a~Int)
1088 checkTc kind_ok (kindErr actual_kind)
1090 traceTc (text "checkValidType done" <+> ppr ty)
1092 checkValidMonoType :: Type -> TcM ()
1093 checkValidMonoType ty = check_mono_type MustBeMonoType ty
1098 data Rank = ArbitraryRank -- Any rank ok
1099 | MustBeMonoType -- Monotype regardless of flags
1100 | TyConArgMonoType -- Monotype but could be poly if -XImpredicativeTypes
1101 | SynArgMonoType -- Monotype but could be poly if -XLiberalTypeSynonyms
1102 | Rank Int -- Rank n, but could be more with -XRankNTypes
1104 decRank :: Rank -> Rank -- Function arguments
1105 decRank (Rank 0) = Rank 0
1106 decRank (Rank n) = Rank (n-1)
1107 decRank other_rank = other_rank
1109 nonZeroRank :: Rank -> Bool
1110 nonZeroRank ArbitraryRank = True
1111 nonZeroRank (Rank n) = n>0
1112 nonZeroRank _ = False
1114 ----------------------------------------
1115 data UbxTupFlag = UT_Ok | UT_NotOk
1116 -- The "Ok" version means "ok if UnboxedTuples is on"
1118 ----------------------------------------
1119 check_mono_type :: Rank -> Type -> TcM () -- No foralls anywhere
1120 -- No unlifted types of any kind
1121 check_mono_type rank ty
1122 = do { check_type rank UT_NotOk ty
1123 ; checkTc (not (isUnLiftedType ty)) (unliftedArgErr ty) }
1125 check_type :: Rank -> UbxTupFlag -> Type -> TcM ()
1126 -- The args say what the *type context* requires, independent
1127 -- of *flag* settings. You test the flag settings at usage sites.
1129 -- Rank is allowed rank for function args
1130 -- Rank 0 means no for-alls anywhere
1132 check_type rank ubx_tup ty
1133 | not (null tvs && null theta)
1134 = do { checkTc (nonZeroRank rank) (forAllTyErr rank ty)
1135 -- Reject e.g. (Maybe (?x::Int => Int)),
1136 -- with a decent error message
1137 ; check_valid_theta SigmaCtxt theta
1138 ; check_type rank ubx_tup tau -- Allow foralls to right of arrow
1139 ; checkAmbiguity tvs theta (tyVarsOfType tau) }
1141 (tvs, theta, tau) = tcSplitSigmaTy ty
1143 -- Naked PredTys should, I think, have been rejected before now
1144 check_type _ _ ty@(PredTy {})
1145 = failWithTc (text "Predicate used as a type:" <+> ppr ty)
1147 check_type _ _ (TyVarTy _) = return ()
1149 check_type rank _ (FunTy arg_ty res_ty)
1150 = do { check_type (decRank rank) UT_NotOk arg_ty
1151 ; check_type rank UT_Ok res_ty }
1153 check_type rank _ (AppTy ty1 ty2)
1154 = do { check_arg_type rank ty1
1155 ; check_arg_type rank ty2 }
1157 check_type rank ubx_tup ty@(TyConApp tc tys)
1159 = do { -- Check that the synonym has enough args
1160 -- This applies equally to open and closed synonyms
1161 -- It's OK to have an *over-applied* type synonym
1162 -- data Tree a b = ...
1163 -- type Foo a = Tree [a]
1164 -- f :: Foo a b -> ...
1165 checkTc (tyConArity tc <= length tys) arity_msg
1167 -- See Note [Liberal type synonyms]
1168 ; liberal <- doptM Opt_LiberalTypeSynonyms
1169 ; if not liberal || isOpenSynTyCon tc then
1170 -- For H98 and synonym families, do check the type args
1171 mapM_ (check_mono_type SynArgMonoType) tys
1173 else -- In the liberal case (only for closed syns), expand then check
1175 Just ty' -> check_type rank ubx_tup ty'
1176 Nothing -> pprPanic "check_tau_type" (ppr ty)
1179 | isUnboxedTupleTyCon tc
1180 = do { ub_tuples_allowed <- doptM Opt_UnboxedTuples
1181 ; checkTc (ubx_tup_ok ub_tuples_allowed) ubx_tup_msg
1183 ; impred <- doptM Opt_ImpredicativeTypes
1184 ; let rank' = if impred then ArbitraryRank else TyConArgMonoType
1185 -- c.f. check_arg_type
1186 -- However, args are allowed to be unlifted, or
1187 -- more unboxed tuples, so can't use check_arg_ty
1188 ; mapM_ (check_type rank' UT_Ok) tys }
1191 = mapM_ (check_arg_type rank) tys
1194 ubx_tup_ok ub_tuples_allowed = case ubx_tup of
1195 UT_Ok -> ub_tuples_allowed
1199 tc_arity = tyConArity tc
1201 arity_msg = arityErr "Type synonym" (tyConName tc) tc_arity n_args
1202 ubx_tup_msg = ubxArgTyErr ty
1204 check_type _ _ ty = pprPanic "check_type" (ppr ty)
1206 ----------------------------------------
1207 check_arg_type :: Rank -> Type -> TcM ()
1208 -- The sort of type that can instantiate a type variable,
1209 -- or be the argument of a type constructor.
1210 -- Not an unboxed tuple, but now *can* be a forall (since impredicativity)
1211 -- Other unboxed types are very occasionally allowed as type
1212 -- arguments depending on the kind of the type constructor
1214 -- For example, we want to reject things like:
1216 -- instance Ord a => Ord (forall s. T s a)
1218 -- g :: T s (forall b.b)
1220 -- NB: unboxed tuples can have polymorphic or unboxed args.
1221 -- This happens in the workers for functions returning
1222 -- product types with polymorphic components.
1223 -- But not in user code.
1224 -- Anyway, they are dealt with by a special case in check_tau_type
1226 check_arg_type rank ty
1227 = do { impred <- doptM Opt_ImpredicativeTypes
1228 ; let rank' = case rank of -- Predictive => must be monotype
1229 MustBeMonoType -> MustBeMonoType -- Monotype, regardless
1230 _other | impred -> ArbitraryRank
1231 | otherwise -> TyConArgMonoType
1232 -- Make sure that MustBeMonoType is propagated,
1233 -- so that we don't suggest -XImpredicativeTypes in
1234 -- (Ord (forall a.a)) => a -> a
1235 -- and so that if it Must be a monotype, we check that it is!
1237 ; check_type rank' UT_NotOk ty
1238 ; checkTc (not (isUnLiftedType ty)) (unliftedArgErr ty) }
1240 ----------------------------------------
1241 forAllTyErr :: Rank -> Type -> SDoc
1243 = vcat [ hang (ptext (sLit "Illegal polymorphic or qualified type:")) 2 (ppr ty)
1246 suggestion = case rank of
1247 Rank _ -> ptext (sLit "Perhaps you intended to use -XRankNTypes or -XRank2Types")
1248 TyConArgMonoType -> ptext (sLit "Perhaps you intended to use -XImpredicativeTypes")
1249 SynArgMonoType -> ptext (sLit "Perhaps you intended to use -XLiberalTypeSynonyms")
1250 _ -> empty -- Polytype is always illegal
1252 unliftedArgErr, ubxArgTyErr :: Type -> SDoc
1253 unliftedArgErr ty = sep [ptext (sLit "Illegal unlifted type:"), ppr ty]
1254 ubxArgTyErr ty = sep [ptext (sLit "Illegal unboxed tuple type as function argument:"), ppr ty]
1256 kindErr :: Kind -> SDoc
1257 kindErr kind = sep [ptext (sLit "Expecting an ordinary type, but found a type of kind"), ppr kind]
1260 Note [Liberal type synonyms]
1261 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1262 If -XLiberalTypeSynonyms is on, expand closed type synonyms *before*
1263 doing validity checking. This allows us to instantiate a synonym defn
1264 with a for-all type, or with a partially-applied type synonym.
1268 Here, T is partially applied, so it's illegal in H98. But if you
1269 expand S first, then T we get just
1273 IMPORTANT: suppose T is a type synonym. Then we must do validity
1274 checking on an appliation (T ty1 ty2)
1276 *either* before expansion (i.e. check ty1, ty2)
1277 *or* after expansion (i.e. expand T ty1 ty2, and then check)
1280 If we do both, we get exponential behaviour!!
1282 data TIACons1 i r c = c i ::: r c
1283 type TIACons2 t x = TIACons1 t (TIACons1 t x)
1284 type TIACons3 t x = TIACons2 t (TIACons1 t x)
1285 type TIACons4 t x = TIACons2 t (TIACons2 t x)
1286 type TIACons7 t x = TIACons4 t (TIACons3 t x)
1289 %************************************************************************
1291 \subsection{Checking a theta or source type}
1293 %************************************************************************
1296 -- Enumerate the contexts in which a "source type", <S>, can occur
1300 -- or (N a) where N is a newtype
1303 = ClassSCCtxt Name -- Superclasses of clas
1304 -- class <S> => C a where ...
1305 | SigmaCtxt -- Theta part of a normal for-all type
1306 -- f :: <S> => a -> a
1307 | DataTyCtxt Name -- Theta part of a data decl
1308 -- data <S> => T a = MkT a
1309 | TypeCtxt -- Source type in an ordinary type
1311 | InstThetaCtxt -- Context of an instance decl
1312 -- instance <S> => C [a] where ...
1314 pprSourceTyCtxt :: SourceTyCtxt -> SDoc
1315 pprSourceTyCtxt (ClassSCCtxt c) = ptext (sLit "the super-classes of class") <+> quotes (ppr c)
1316 pprSourceTyCtxt SigmaCtxt = ptext (sLit "the context of a polymorphic type")
1317 pprSourceTyCtxt (DataTyCtxt tc) = ptext (sLit "the context of the data type declaration for") <+> quotes (ppr tc)
1318 pprSourceTyCtxt InstThetaCtxt = ptext (sLit "the context of an instance declaration")
1319 pprSourceTyCtxt TypeCtxt = ptext (sLit "the context of a type")
1323 checkValidTheta :: SourceTyCtxt -> ThetaType -> TcM ()
1324 checkValidTheta ctxt theta
1325 = addErrCtxt (checkThetaCtxt ctxt theta) (check_valid_theta ctxt theta)
1327 -------------------------
1328 check_valid_theta :: SourceTyCtxt -> [PredType] -> TcM ()
1329 check_valid_theta _ []
1331 check_valid_theta ctxt theta = do
1333 warnTc (notNull dups) (dupPredWarn dups)
1334 mapM_ (check_pred_ty dflags ctxt) theta
1336 (_,dups) = removeDups tcCmpPred theta
1338 -------------------------
1339 check_pred_ty :: DynFlags -> SourceTyCtxt -> PredType -> TcM ()
1340 check_pred_ty dflags ctxt pred@(ClassP cls tys)
1341 = do { -- Class predicates are valid in all contexts
1342 ; checkTc (arity == n_tys) arity_err
1344 -- Check the form of the argument types
1345 ; mapM_ checkValidMonoType tys
1346 ; checkTc (check_class_pred_tys dflags ctxt tys)
1347 (predTyVarErr pred $$ how_to_allow)
1350 class_name = className cls
1351 arity = classArity cls
1353 arity_err = arityErr "Class" class_name arity n_tys
1354 how_to_allow = parens (ptext (sLit "Use -XFlexibleContexts to permit this"))
1356 check_pred_ty _ (ClassSCCtxt _) (EqPred _ _)
1357 = -- We do not yet support superclass equalities.
1359 sep [ ptext (sLit "The current implementation of type families does not")
1360 , ptext (sLit "support equality constraints in superclass contexts.")
1361 , ptext (sLit "They are planned for a future release.")
1364 check_pred_ty dflags _ pred@(EqPred ty1 ty2)
1365 = do { -- Equational constraints are valid in all contexts if type
1366 -- families are permitted
1367 ; checkTc (dopt Opt_TypeFamilies dflags) (eqPredTyErr pred)
1369 -- Check the form of the argument types
1370 ; checkValidMonoType ty1
1371 ; checkValidMonoType ty2
1374 check_pred_ty _ SigmaCtxt (IParam _ ty) = checkValidMonoType ty
1375 -- Implicit parameters only allowed in type
1376 -- signatures; not in instance decls, superclasses etc
1377 -- The reason for not allowing implicit params in instances is a bit
1379 -- If we allowed instance (?x::Int, Eq a) => Foo [a] where ...
1380 -- then when we saw (e :: (?x::Int) => t) it would be unclear how to
1381 -- discharge all the potential usas of the ?x in e. For example, a
1382 -- constraint Foo [Int] might come out of e,and applying the
1383 -- instance decl would show up two uses of ?x.
1386 check_pred_ty _ _ sty = failWithTc (badPredTyErr sty)
1388 -------------------------
1389 check_class_pred_tys :: DynFlags -> SourceTyCtxt -> [Type] -> Bool
1390 check_class_pred_tys dflags ctxt tys
1392 TypeCtxt -> True -- {-# SPECIALISE instance Eq (T Int) #-} is fine
1393 InstThetaCtxt -> flexible_contexts || undecidable_ok || all tcIsTyVarTy tys
1394 -- Further checks on head and theta in
1395 -- checkInstTermination
1396 _ -> flexible_contexts || all tyvar_head tys
1398 flexible_contexts = dopt Opt_FlexibleContexts dflags
1399 undecidable_ok = dopt Opt_UndecidableInstances dflags
1401 -------------------------
1402 tyvar_head :: Type -> Bool
1403 tyvar_head ty -- Haskell 98 allows predicates of form
1404 | tcIsTyVarTy ty = True -- C (a ty1 .. tyn)
1405 | otherwise -- where a is a type variable
1406 = case tcSplitAppTy_maybe ty of
1407 Just (ty, _) -> tyvar_head ty
1414 is ambiguous if P contains generic variables
1415 (i.e. one of the Vs) that are not mentioned in tau
1417 However, we need to take account of functional dependencies
1418 when we speak of 'mentioned in tau'. Example:
1419 class C a b | a -> b where ...
1421 forall x y. (C x y) => x
1422 is not ambiguous because x is mentioned and x determines y
1424 NB; the ambiguity check is only used for *user* types, not for types
1425 coming from inteface files. The latter can legitimately have
1426 ambiguous types. Example
1428 class S a where s :: a -> (Int,Int)
1429 instance S Char where s _ = (1,1)
1430 f:: S a => [a] -> Int -> (Int,Int)
1431 f (_::[a]) x = (a*x,b)
1432 where (a,b) = s (undefined::a)
1434 Here the worker for f gets the type
1435 fw :: forall a. S a => Int -> (# Int, Int #)
1437 If the list of tv_names is empty, we have a monotype, and then we
1438 don't need to check for ambiguity either, because the test can't fail
1443 checkAmbiguity :: [TyVar] -> ThetaType -> TyVarSet -> TcM ()
1444 checkAmbiguity forall_tyvars theta tau_tyvars
1445 = mapM_ complain (filter is_ambig theta)
1447 complain pred = addErrTc (ambigErr pred)
1448 extended_tau_vars = growThetaTyVars theta tau_tyvars
1450 -- See Note [Implicit parameters and ambiguity] in TcSimplify
1451 is_ambig pred = isClassPred pred &&
1452 any ambig_var (varSetElems (tyVarsOfPred pred))
1454 ambig_var ct_var = (ct_var `elem` forall_tyvars) &&
1455 not (ct_var `elemVarSet` extended_tau_vars)
1457 ambigErr :: PredType -> SDoc
1459 = sep [ptext (sLit "Ambiguous constraint") <+> quotes (pprPred pred),
1460 nest 4 (ptext (sLit "At least one of the forall'd type variables mentioned by the constraint") $$
1461 ptext (sLit "must be reachable from the type after the '=>'"))]
1463 --------------------------
1464 -- For this 'grow' stuff see Note [Growing the tau-tvs using constraints] in Inst
1466 growThetaTyVars :: TcThetaType -> TyVarSet -> TyVarSet
1468 growThetaTyVars theta tvs
1470 | otherwise = fixVarSet mk_next tvs
1472 mk_next tvs = foldr growPredTyVars tvs theta
1475 growPredTyVars :: TcPredType -> TyVarSet -> TyVarSet
1476 -- Here is where the special case for inplicit parameters happens
1477 growPredTyVars (IParam _ ty) tvs = tvs `unionVarSet` tyVarsOfType ty
1478 growPredTyVars pred tvs = growTyVars (tyVarsOfPred pred) tvs
1480 growTyVars :: TyVarSet -> TyVarSet -> TyVarSet
1481 growTyVars new_tvs tvs
1482 | new_tvs `intersectsVarSet` tvs = tvs `unionVarSet` new_tvs
1486 In addition, GHC insists that at least one type variable
1487 in each constraint is in V. So we disallow a type like
1488 forall a. Eq b => b -> b
1489 even in a scope where b is in scope.
1492 checkThetaCtxt :: SourceTyCtxt -> ThetaType -> SDoc
1493 checkThetaCtxt ctxt theta
1494 = vcat [ptext (sLit "In the context:") <+> pprTheta theta,
1495 ptext (sLit "While checking") <+> pprSourceTyCtxt ctxt ]
1497 badPredTyErr, eqPredTyErr, predTyVarErr :: PredType -> SDoc
1498 badPredTyErr sty = ptext (sLit "Illegal constraint") <+> pprPred sty
1499 eqPredTyErr sty = ptext (sLit "Illegal equational constraint") <+> pprPred sty
1501 parens (ptext (sLit "Use -XTypeFamilies to permit this"))
1502 predTyVarErr pred = sep [ptext (sLit "Non type-variable argument"),
1503 nest 2 (ptext (sLit "in the constraint:") <+> pprPred pred)]
1504 dupPredWarn :: [[PredType]] -> SDoc
1505 dupPredWarn dups = ptext (sLit "Duplicate constraint(s):") <+> pprWithCommas pprPred (map head dups)
1507 arityErr :: Outputable a => String -> a -> Int -> Int -> SDoc
1508 arityErr kind name n m
1509 = hsep [ text kind, quotes (ppr name), ptext (sLit "should have"),
1510 n_arguments <> comma, text "but has been given",
1511 if m==0 then text "none" else int m]
1513 n_arguments | n == 0 = ptext (sLit "no arguments")
1514 | n == 1 = ptext (sLit "1 argument")
1515 | True = hsep [int n, ptext (sLit "arguments")]
1518 notMonoType :: TcType -> TcM a
1520 = do { ty' <- zonkTcType ty
1521 ; env0 <- tcInitTidyEnv
1522 ; let (env1, tidy_ty) = tidyOpenType env0 ty'
1523 msg = ptext (sLit "Cannot match a monotype with") <+> quotes (ppr tidy_ty)
1524 ; failWithTcM (env1, msg) }
1526 notMonoArgs :: TcType -> TcM a
1528 = do { ty' <- zonkTcType ty
1529 ; env0 <- tcInitTidyEnv
1530 ; let (env1, tidy_ty) = tidyOpenType env0 ty'
1531 msg = ptext (sLit "Arguments of type synonym families must be monotypes") <+> quotes (ppr tidy_ty)
1532 ; failWithTcM (env1, msg) }
1536 %************************************************************************
1538 \subsection{Checking for a decent instance head type}
1540 %************************************************************************
1542 @checkValidInstHead@ checks the type {\em and} its syntactic constraints:
1543 it must normally look like: @instance Foo (Tycon a b c ...) ...@
1545 The exceptions to this syntactic checking: (1)~if the @GlasgowExts@
1546 flag is on, or (2)~the instance is imported (they must have been
1547 compiled elsewhere). In these cases, we let them go through anyway.
1549 We can also have instances for functions: @instance Foo (a -> b) ...@.
1552 checkValidInstHead :: Type -> TcM (Class, [TcType])
1554 checkValidInstHead ty -- Should be a source type
1555 = case tcSplitPredTy_maybe ty of {
1556 Nothing -> failWithTc (instTypeErr (ppr ty) empty) ;
1559 case getClassPredTys_maybe pred of {
1560 Nothing -> failWithTc (instTypeErr (pprPred pred) empty) ;
1561 Just (clas,tys) -> do
1564 check_inst_head dflags clas tys
1568 check_inst_head :: DynFlags -> Class -> [Type] -> TcM ()
1569 check_inst_head dflags clas tys
1570 = do { -- If GlasgowExts then check at least one isn't a type variable
1571 ; checkTc (dopt Opt_TypeSynonymInstances dflags ||
1572 all tcInstHeadTyNotSynonym tys)
1573 (instTypeErr (pprClassPred clas tys) head_type_synonym_msg)
1574 ; checkTc (dopt Opt_FlexibleInstances dflags ||
1575 all tcInstHeadTyAppAllTyVars tys)
1576 (instTypeErr (pprClassPred clas tys) head_type_args_tyvars_msg)
1577 ; checkTc (dopt Opt_MultiParamTypeClasses dflags ||
1579 (instTypeErr (pprClassPred clas tys) head_one_type_msg)
1580 -- May not contain type family applications
1581 ; mapM_ checkTyFamFreeness tys
1583 ; mapM_ checkValidMonoType tys
1584 -- For now, I only allow tau-types (not polytypes) in
1585 -- the head of an instance decl.
1586 -- E.g. instance C (forall a. a->a) is rejected
1587 -- One could imagine generalising that, but I'm not sure
1588 -- what all the consequences might be
1592 head_type_synonym_msg = parens (
1593 text "All instance types must be of the form (T t1 ... tn)" $$
1594 text "where T is not a synonym." $$
1595 text "Use -XTypeSynonymInstances if you want to disable this.")
1597 head_type_args_tyvars_msg = parens (vcat [
1598 text "All instance types must be of the form (T a1 ... an)",
1599 text "where a1 ... an are type *variables*,",
1600 text "and each type variable appears at most once in the instance head.",
1601 text "Use -XFlexibleInstances if you want to disable this."])
1603 head_one_type_msg = parens (
1604 text "Only one type can be given in an instance head." $$
1605 text "Use -XMultiParamTypeClasses if you want to allow more.")
1607 instTypeErr :: SDoc -> SDoc -> SDoc
1608 instTypeErr pp_ty msg
1609 = sep [ptext (sLit "Illegal instance declaration for") <+> quotes pp_ty,
1614 %************************************************************************
1616 \subsection{Checking instance for termination}
1618 %************************************************************************
1621 checkValidInstance :: LHsType Name -> [TyVar] -> ThetaType -> Type
1622 -> TcM (Class, [TcType])
1623 checkValidInstance hs_type tyvars theta tau
1624 = setSrcSpan (getLoc hs_type) $
1625 do { (clas, inst_tys) <- setSrcSpan head_loc $
1626 checkValidInstHead tau
1628 ; undecidable_ok <- doptM Opt_UndecidableInstances
1630 ; checkValidTheta InstThetaCtxt theta
1631 ; checkAmbiguity tyvars theta (tyVarsOfTypes inst_tys)
1633 -- Check that instance inference will terminate (if we care)
1634 -- For Haskell 98 this will already have been done by checkValidTheta,
1635 -- but as we may be using other extensions we need to check.
1636 ; unless undecidable_ok $
1637 mapM_ addErrTc (checkInstTermination inst_tys theta)
1639 -- The Coverage Condition
1640 ; checkTc (undecidable_ok || checkInstCoverage clas inst_tys)
1641 (instTypeErr (pprClassPred clas inst_tys) msg)
1643 ; return (clas, inst_tys)
1646 msg = parens (vcat [ptext (sLit "the Coverage Condition fails for one of the functional dependencies;"),
1649 -- The location of the "head" of the instance
1650 head_loc = case hs_type of
1651 L _ (HsForAllTy _ _ _ (L loc _)) -> loc
1655 Termination test: the so-called "Paterson conditions" (see Section 5 of
1656 "Understanding functionsl dependencies via Constraint Handling Rules,
1659 We check that each assertion in the context satisfies:
1660 (1) no variable has more occurrences in the assertion than in the head, and
1661 (2) the assertion has fewer constructors and variables (taken together
1662 and counting repetitions) than the head.
1663 This is only needed with -fglasgow-exts, as Haskell 98 restrictions
1664 (which have already been checked) guarantee termination.
1666 The underlying idea is that
1668 for any ground substitution, each assertion in the
1669 context has fewer type constructors than the head.
1673 checkInstTermination :: [TcType] -> ThetaType -> [Message]
1674 checkInstTermination tys theta
1675 = mapCatMaybes check theta
1678 size = sizeTypes tys
1680 | not (null (fvPred pred \\ fvs))
1681 = Just (predUndecErr pred nomoreMsg $$ parens undecidableMsg)
1682 | sizePred pred >= size
1683 = Just (predUndecErr pred smallerMsg $$ parens undecidableMsg)
1687 predUndecErr :: PredType -> SDoc -> SDoc
1688 predUndecErr pred msg = sep [msg,
1689 nest 2 (ptext (sLit "in the constraint:") <+> pprPred pred)]
1691 nomoreMsg, smallerMsg, undecidableMsg :: SDoc
1692 nomoreMsg = ptext (sLit "Variable occurs more often in a constraint than in the instance head")
1693 smallerMsg = ptext (sLit "Constraint is no smaller than the instance head")
1694 undecidableMsg = ptext (sLit "Use -XUndecidableInstances to permit this")
1698 %************************************************************************
1700 Checking the context of a derived instance declaration
1702 %************************************************************************
1704 Note [Exotic derived instance contexts]
1705 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1706 In a 'derived' instance declaration, we *infer* the context. It's a
1707 bit unclear what rules we should apply for this; the Haskell report is
1708 silent. Obviously, constraints like (Eq a) are fine, but what about
1709 data T f a = MkT (f a) deriving( Eq )
1710 where we'd get an Eq (f a) constraint. That's probably fine too.
1712 One could go further: consider
1713 data T a b c = MkT (Foo a b c) deriving( Eq )
1714 instance (C Int a, Eq b, Eq c) => Eq (Foo a b c)
1716 Notice that this instance (just) satisfies the Paterson termination
1717 conditions. Then we *could* derive an instance decl like this:
1719 instance (C Int a, Eq b, Eq c) => Eq (T a b c)
1720 even though there is no instance for (C Int a), because there just
1721 *might* be an instance for, say, (C Int Bool) at a site where we
1722 need the equality instance for T's.
1724 However, this seems pretty exotic, and it's quite tricky to allow
1725 this, and yet give sensible error messages in the (much more common)
1726 case where we really want that instance decl for C.
1728 So for now we simply require that the derived instance context
1729 should have only type-variable constraints.
1731 Here is another example:
1732 data Fix f = In (f (Fix f)) deriving( Eq )
1733 Here, if we are prepared to allow -XUndecidableInstances we
1734 could derive the instance
1735 instance Eq (f (Fix f)) => Eq (Fix f)
1736 but this is so delicate that I don't think it should happen inside
1737 'deriving'. If you want this, write it yourself!
1739 NB: if you want to lift this condition, make sure you still meet the
1740 termination conditions! If not, the deriving mechanism generates
1741 larger and larger constraints. Example:
1743 data Seq a = Cons a (Seq (Succ a)) | Nil deriving Show
1745 Note the lack of a Show instance for Succ. First we'll generate
1746 instance (Show (Succ a), Show a) => Show (Seq a)
1748 instance (Show (Succ (Succ a)), Show (Succ a), Show a) => Show (Seq a)
1749 and so on. Instead we want to complain of no instance for (Show (Succ a)).
1753 Allow constraints which consist only of type variables, with no repeats.
1756 validDerivPred :: PredType -> Bool
1757 validDerivPred (ClassP _ tys) = hasNoDups fvs && sizeTypes tys == length fvs
1758 where fvs = fvTypes tys
1759 validDerivPred _ = False
1762 %************************************************************************
1764 Checking type instance well-formedness and termination
1766 %************************************************************************
1769 -- Check that a "type instance" is well-formed (which includes decidability
1770 -- unless -XUndecidableInstances is given).
1772 checkValidTypeInst :: [Type] -> Type -> TcM ()
1773 checkValidTypeInst typats rhs
1774 = do { -- left-hand side contains no type family applications
1775 -- (vanilla synonyms are fine, though)
1776 ; mapM_ checkTyFamFreeness typats
1778 -- the right-hand side is a tau type
1779 ; checkValidMonoType rhs
1781 -- we have a decidable instance unless otherwise permitted
1782 ; undecidable_ok <- doptM Opt_UndecidableInstances
1783 ; unless undecidable_ok $
1784 mapM_ addErrTc (checkFamInst typats (tyFamInsts rhs))
1787 -- Make sure that each type family instance is
1788 -- (1) strictly smaller than the lhs,
1789 -- (2) mentions no type variable more often than the lhs, and
1790 -- (3) does not contain any further type family instances.
1792 checkFamInst :: [Type] -- lhs
1793 -> [(TyCon, [Type])] -- type family instances
1795 checkFamInst lhsTys famInsts
1796 = mapCatMaybes check famInsts
1798 size = sizeTypes lhsTys
1799 fvs = fvTypes lhsTys
1801 | not (all isTyFamFree tys)
1802 = Just (famInstUndecErr famInst nestedMsg $$ parens undecidableMsg)
1803 | not (null (fvTypes tys \\ fvs))
1804 = Just (famInstUndecErr famInst nomoreVarMsg $$ parens undecidableMsg)
1805 | size <= sizeTypes tys
1806 = Just (famInstUndecErr famInst smallerAppMsg $$ parens undecidableMsg)
1810 famInst = TyConApp tc tys
1812 -- Ensure that no type family instances occur in a type.
1814 checkTyFamFreeness :: Type -> TcM ()
1815 checkTyFamFreeness ty
1816 = checkTc (isTyFamFree ty) $
1817 tyFamInstIllegalErr ty
1819 -- Check that a type does not contain any type family applications.
1821 isTyFamFree :: Type -> Bool
1822 isTyFamFree = null . tyFamInsts
1826 tyFamInstIllegalErr :: Type -> SDoc
1827 tyFamInstIllegalErr ty
1828 = hang (ptext (sLit "Illegal type synonym family application in instance") <>
1832 famInstUndecErr :: Type -> SDoc -> SDoc
1833 famInstUndecErr ty msg
1835 nest 2 (ptext (sLit "in the type family application:") <+>
1838 nestedMsg, nomoreVarMsg, smallerAppMsg :: SDoc
1839 nestedMsg = ptext (sLit "Nested type family application")
1840 nomoreVarMsg = ptext (sLit "Variable occurs more often than in instance head")
1841 smallerAppMsg = ptext (sLit "Application is no smaller than the instance head")
1845 %************************************************************************
1847 \subsection{Auxiliary functions}
1849 %************************************************************************
1852 -- Free variables of a type, retaining repetitions, and expanding synonyms
1853 fvType :: Type -> [TyVar]
1854 fvType ty | Just exp_ty <- tcView ty = fvType exp_ty
1855 fvType (TyVarTy tv) = [tv]
1856 fvType (TyConApp _ tys) = fvTypes tys
1857 fvType (PredTy pred) = fvPred pred
1858 fvType (FunTy arg res) = fvType arg ++ fvType res
1859 fvType (AppTy fun arg) = fvType fun ++ fvType arg
1860 fvType (ForAllTy tyvar ty) = filter (/= tyvar) (fvType ty)
1862 fvTypes :: [Type] -> [TyVar]
1863 fvTypes tys = concat (map fvType tys)
1865 fvPred :: PredType -> [TyVar]
1866 fvPred (ClassP _ tys') = fvTypes tys'
1867 fvPred (IParam _ ty) = fvType ty
1868 fvPred (EqPred ty1 ty2) = fvType ty1 ++ fvType ty2
1870 -- Size of a type: the number of variables and constructors
1871 sizeType :: Type -> Int
1872 sizeType ty | Just exp_ty <- tcView ty = sizeType exp_ty
1873 sizeType (TyVarTy _) = 1
1874 sizeType (TyConApp _ tys) = sizeTypes tys + 1
1875 sizeType (PredTy pred) = sizePred pred
1876 sizeType (FunTy arg res) = sizeType arg + sizeType res + 1
1877 sizeType (AppTy fun arg) = sizeType fun + sizeType arg
1878 sizeType (ForAllTy _ ty) = sizeType ty
1880 sizeTypes :: [Type] -> Int
1881 sizeTypes xs = sum (map sizeType xs)
1883 -- Size of a predicate
1885 -- Equalities are a special case. The equality itself doesn't contribute to the
1886 -- size and as we do not count class predicates, we have to start with one less.
1887 -- This is easy to see considering that, given
1888 -- class C a b | a -> b
1890 -- constraints (C a b) and (F a ~ b) are equivalent in size.
1891 sizePred :: PredType -> Int
1892 sizePred (ClassP _ tys') = sizeTypes tys'
1893 sizePred (IParam _ ty) = sizeType ty
1894 sizePred (EqPred ty1 ty2) = sizeType ty1 + sizeType ty2 - 1