2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section{Monadic type operations}
6 This module contains monadic operations over types that contain mutable type variables
10 TcTyVar, TcKind, TcType, TcTauType, TcThetaType, TcRhoType, TcTyVarSet,
12 --------------------------------
13 -- Find the type to which a type variable is bound
14 tcPutTyVar, -- :: TcTyVar -> TcType -> NF_TcM TcType
15 tcGetTyVar, -- :: TcTyVar -> NF_TcM (Maybe TcType) does shorting out
17 --------------------------------
18 -- Creating new mutable type variables
20 newTyVarTy, -- Kind -> NF_TcM TcType
21 newTyVarTys, -- Int -> Kind -> NF_TcM [TcType]
22 newKindVar, newKindVars, newBoxityVar,
24 --------------------------------
26 tcInstTyVar, tcInstTyVars,
27 tcInstSigVars, tcInstType,
30 --------------------------------
32 unifyTauTy, unifyTauTyList, unifyTauTyLists,
33 unifyFunTy, unifyListTy, unifyTupleTy,
34 unifyKind, unifyKinds, unifyOpenTypeKind,
36 --------------------------------
38 zonkTcTyVar, zonkTcTyVars, zonkTcTyVarsAndFV, zonkTcSigTyVars,
39 zonkTcType, zonkTcTypes, zonkTcClassConstraints, zonkTcThetaType,
40 zonkTcPredType, zonkTcTypeToType, zonkTcTyVarToTyVar, zonkKindEnv,
44 #include "HsVersions.h"
48 import TypeRep ( Type(..), Kind, TyNote(..) ) -- friend
49 import Type -- Lots and lots
50 import TcType ( tcEqType,
51 tcSplitRhoTy, tcSplitPredTy_maybe, tcSplitAppTy_maybe,
52 tcSplitTyConApp_maybe, tcSplitFunTy_maybe
54 import Subst ( Subst, mkTopTyVarSubst, substTy )
55 import TyCon ( TyCon, mkPrimTyCon, isTupleTyCon, tyConArity, tupleTyConBoxity )
56 import PrimRep ( PrimRep(VoidRep) )
57 import Var ( TyVar, varName, tyVarKind, tyVarName, isTyVar, mkTyVar,
58 isMutTyVar, isSigTyVar )
61 import TcMonad -- TcType, amongst others
62 import TysWiredIn ( voidTy, listTyCon, mkListTy, mkTupleTy )
64 import Name ( Name, NamedThing(..), setNameUnique, mkSysLocalName,
65 mkLocalName, mkDerivedTyConOcc, isSystemName
68 import BasicTypes ( Boxity, Arity, isBoxed )
69 import Unique ( Uniquable(..) )
70 import SrcLoc ( noSrcLoc )
71 import Util ( nOfThem )
76 %************************************************************************
78 \subsection{New type variables}
80 %************************************************************************
83 newTyVar :: Kind -> NF_TcM TcTyVar
85 = tcGetUnique `thenNF_Tc` \ uniq ->
86 tcNewMutTyVar (mkSysLocalName uniq SLIT("t")) kind
88 newTyVarTy :: Kind -> NF_TcM TcType
90 = newTyVar kind `thenNF_Tc` \ tc_tyvar ->
91 returnNF_Tc (TyVarTy tc_tyvar)
93 newTyVarTys :: Int -> Kind -> NF_TcM [TcType]
94 newTyVarTys n kind = mapNF_Tc newTyVarTy (nOfThem n kind)
96 newKindVar :: NF_TcM TcKind
98 = tcGetUnique `thenNF_Tc` \ uniq ->
99 tcNewMutTyVar (mkSysLocalName uniq SLIT("k")) superKind `thenNF_Tc` \ kv ->
100 returnNF_Tc (TyVarTy kv)
102 newKindVars :: Int -> NF_TcM [TcKind]
103 newKindVars n = mapNF_Tc (\ _ -> newKindVar) (nOfThem n ())
105 newBoxityVar :: NF_TcM TcKind
107 = tcGetUnique `thenNF_Tc` \ uniq ->
108 tcNewMutTyVar (mkSysLocalName uniq SLIT("bx")) superBoxity `thenNF_Tc` \ kv ->
109 returnNF_Tc (TyVarTy kv)
113 %************************************************************************
115 \subsection{Type instantiation}
117 %************************************************************************
119 I don't understand why this is needed
120 An old comments says "No need for tcSplitForAllTyM because a type
121 variable can't be instantiated to a for-all type"
122 But the same is true of rho types!
125 tcSplitRhoTyM :: TcType -> NF_TcM (TcThetaType, TcType)
129 -- A type variable is never instantiated to a dictionary type,
130 -- so we don't need to do a tcReadVar on the "arg".
131 go syn_t (FunTy arg res) ts = case tcSplitPredTy_maybe arg of
132 Just pair -> go res res (pair:ts)
133 Nothing -> returnNF_Tc (reverse ts, syn_t)
134 go syn_t (NoteTy n t) ts = go syn_t t ts
135 go syn_t (TyVarTy tv) ts = tcGetTyVar tv `thenNF_Tc` \ maybe_ty ->
137 Just ty | not (isTyVarTy ty) -> go syn_t ty ts
138 other -> returnNF_Tc (reverse ts, syn_t)
139 go syn_t (UsageTy _ t) ts = go syn_t t ts
140 go syn_t t ts = returnNF_Tc (reverse ts, syn_t)
144 %************************************************************************
146 \subsection{Type instantiation}
148 %************************************************************************
150 Instantiating a bunch of type variables
153 tcInstTyVars :: [TyVar]
154 -> NF_TcM ([TcTyVar], [TcType], Subst)
157 = mapNF_Tc tcInstTyVar tyvars `thenNF_Tc` \ tc_tyvars ->
159 tys = mkTyVarTys tc_tyvars
161 returnNF_Tc (tc_tyvars, tys, mkTopTyVarSubst tyvars tys)
162 -- Since the tyvars are freshly made,
163 -- they cannot possibly be captured by
164 -- any existing for-alls. Hence mkTopTyVarSubst
167 = tcGetUnique `thenNF_Tc` \ uniq ->
169 name = setNameUnique (tyVarName tyvar) uniq
170 -- Note that we don't change the print-name
171 -- This won't confuse the type checker but there's a chance
172 -- that two different tyvars will print the same way
173 -- in an error message. -dppr-debug will show up the difference
174 -- Better watch out for this. If worst comes to worst, just
175 -- use mkSysLocalName.
177 tcNewMutTyVar name (tyVarKind tyvar)
179 tcInstSigVars tyvars -- Very similar to tcInstTyVar
180 = tcGetUniques `thenNF_Tc` \ uniqs ->
181 listTc [ ASSERT( not (kind `eqKind` openTypeKind) ) -- Shouldn't happen
182 tcNewSigTyVar name kind
183 | (tyvar, uniq) <- tyvars `zip` uniqs,
184 let name = setNameUnique (tyVarName tyvar) uniq,
185 let kind = tyVarKind tyvar
189 @tcInstType@ instantiates the outer-level for-alls of a TcType with
190 fresh type variables, splits off the dictionary part, and returns the results.
193 tcInstType :: TcType -> NF_TcM ([TcTyVar], TcThetaType, TcType)
195 = case splitForAllTys ty of
196 ([], rho) -> -- There may be overloading but no type variables;
197 -- (?x :: Int) => Int -> Int
199 (theta, tau) = tcSplitRhoTy rho -- Used to be tcSplitRhoTyM
201 returnNF_Tc ([], theta, tau)
203 (tyvars, rho) -> tcInstTyVars tyvars `thenNF_Tc` \ (tyvars', _, tenv) ->
205 (theta, tau) = tcSplitRhoTy (substTy tenv rho) -- Used to be tcSplitRhoTyM
207 returnNF_Tc (tyvars', theta, tau)
212 %************************************************************************
214 \subsection{Putting and getting mutable type variables}
216 %************************************************************************
219 tcPutTyVar :: TcTyVar -> TcType -> NF_TcM TcType
220 tcGetTyVar :: TcTyVar -> NF_TcM (Maybe TcType)
227 | not (isMutTyVar tyvar)
228 = pprTrace "tcPutTyVar" (ppr tyvar) $
232 = ASSERT( isMutTyVar tyvar )
233 UASSERT2( not (isUTy ty), ppr tyvar <+> ppr ty )
234 tcWriteMutTyVar tyvar (Just ty) `thenNF_Tc_`
238 Getting is more interesting. The easy thing to do is just to read, thus:
241 tcGetTyVar tyvar = tcReadMutTyVar tyvar
244 But it's more fun to short out indirections on the way: If this
245 version returns a TyVar, then that TyVar is unbound. If it returns
246 any other type, then there might be bound TyVars embedded inside it.
248 We return Nothing iff the original box was unbound.
252 | not (isMutTyVar tyvar)
253 = pprTrace "tcGetTyVar" (ppr tyvar) $
254 returnNF_Tc (Just (mkTyVarTy tyvar))
257 = ASSERT2( isMutTyVar tyvar, ppr tyvar )
258 tcReadMutTyVar tyvar `thenNF_Tc` \ maybe_ty ->
260 Just ty -> short_out ty `thenNF_Tc` \ ty' ->
261 tcWriteMutTyVar tyvar (Just ty') `thenNF_Tc_`
262 returnNF_Tc (Just ty')
264 Nothing -> returnNF_Tc Nothing
266 short_out :: TcType -> NF_TcM TcType
267 short_out ty@(TyVarTy tyvar)
268 | not (isMutTyVar tyvar)
272 = tcReadMutTyVar tyvar `thenNF_Tc` \ maybe_ty ->
274 Just ty' -> short_out ty' `thenNF_Tc` \ ty' ->
275 tcWriteMutTyVar tyvar (Just ty') `thenNF_Tc_`
278 other -> returnNF_Tc ty
280 short_out other_ty = returnNF_Tc other_ty
284 %************************************************************************
286 \subsection{Zonking -- the exernal interfaces}
288 %************************************************************************
290 ----------------- Type variables
293 zonkTcTyVars :: [TcTyVar] -> NF_TcM [TcType]
294 zonkTcTyVars tyvars = mapNF_Tc zonkTcTyVar tyvars
296 zonkTcTyVarsAndFV :: [TcTyVar] -> NF_TcM TcTyVarSet
297 zonkTcTyVarsAndFV tyvars = mapNF_Tc zonkTcTyVar tyvars `thenNF_Tc` \ tys ->
298 returnNF_Tc (tyVarsOfTypes tys)
300 zonkTcTyVar :: TcTyVar -> NF_TcM TcType
301 zonkTcTyVar tyvar = zonkTyVar (\ tv -> returnNF_Tc (TyVarTy tv)) tyvar
303 zonkTcSigTyVars :: [TcTyVar] -> NF_TcM [TcTyVar]
304 -- This guy is to zonk the tyvars we're about to feed into tcSimplify
305 -- Usually this job is done by checkSigTyVars, but in a couple of places
306 -- that is overkill, so we use this simpler chap
307 zonkTcSigTyVars tyvars
308 = zonkTcTyVars tyvars `thenNF_Tc` \ tys ->
309 returnNF_Tc (map (getTyVar "zonkTcSigTyVars") tys)
312 ----------------- Types
315 zonkTcType :: TcType -> NF_TcM TcType
316 zonkTcType ty = zonkType (\ tv -> returnNF_Tc (TyVarTy tv)) ty
318 zonkTcTypes :: [TcType] -> NF_TcM [TcType]
319 zonkTcTypes tys = mapNF_Tc zonkTcType tys
321 zonkTcClassConstraints cts = mapNF_Tc zonk cts
322 where zonk (clas, tys)
323 = zonkTcTypes tys `thenNF_Tc` \ new_tys ->
324 returnNF_Tc (clas, new_tys)
326 zonkTcThetaType :: TcThetaType -> NF_TcM TcThetaType
327 zonkTcThetaType theta = mapNF_Tc zonkTcPredType theta
329 zonkTcPredType :: TcPredType -> NF_TcM TcPredType
330 zonkTcPredType (ClassP c ts) =
331 zonkTcTypes ts `thenNF_Tc` \ new_ts ->
332 returnNF_Tc (ClassP c new_ts)
333 zonkTcPredType (IParam n t) =
334 zonkTcType t `thenNF_Tc` \ new_t ->
335 returnNF_Tc (IParam n new_t)
338 ------------------- These ...ToType, ...ToKind versions
339 are used at the end of type checking
342 zonkKindEnv :: [(Name, TcKind)] -> NF_TcM [(Name, Kind)]
344 = mapNF_Tc zonk_it pairs
346 zonk_it (name, tc_kind) = zonkType zonk_unbound_kind_var tc_kind `thenNF_Tc` \ kind ->
347 returnNF_Tc (name, kind)
349 -- When zonking a kind, we want to
350 -- zonk a *kind* variable to (Type *)
351 -- zonk a *boxity* variable to *
352 zonk_unbound_kind_var kv | tyVarKind kv `eqKind` superKind = tcPutTyVar kv liftedTypeKind
353 | tyVarKind kv `eqKind` superBoxity = tcPutTyVar kv liftedBoxity
354 | otherwise = pprPanic "zonkKindEnv" (ppr kv)
356 zonkTcTypeToType :: TcType -> NF_TcM Type
357 zonkTcTypeToType ty = zonkType zonk_unbound_tyvar ty
359 -- Zonk a mutable but unbound type variable to
360 -- Void if it has kind Lifted
362 zonk_unbound_tyvar tv
363 | kind `eqKind` liftedTypeKind || kind `eqKind` openTypeKind
364 = tcPutTyVar tv voidTy -- Just to avoid creating a new tycon in
365 -- this vastly common case
367 = tcPutTyVar tv (TyConApp (mk_void_tycon tv kind) [])
371 mk_void_tycon tv kind -- Make a new TyCon with the same kind as the
372 -- type variable tv. Same name too, apart from
373 -- making it start with a colon (sigh)
374 -- I dread to think what will happen if this gets out into an
375 -- interface file. Catastrophe likely. Major sigh.
376 = pprTrace "Urk! Inventing strangely-kinded void TyCon" (ppr tc_name) $
377 mkPrimTyCon tc_name kind 0 [] VoidRep
379 tc_name = mkLocalName (getUnique tv) (mkDerivedTyConOcc (getOccName tv)) noSrcLoc
381 -- zonkTcTyVarToTyVar is applied to the *binding* occurrence
382 -- of a type variable, at the *end* of type checking. It changes
383 -- the *mutable* type variable into an *immutable* one.
385 -- It does this by making an immutable version of tv and binds tv to it.
386 -- Now any bound occurences of the original type variable will get
387 -- zonked to the immutable version.
389 zonkTcTyVarToTyVar :: TcTyVar -> NF_TcM TyVar
390 zonkTcTyVarToTyVar tv
392 -- Make an immutable version, defaulting
393 -- the kind to lifted if necessary
394 immut_tv = mkTyVar (tyVarName tv) (defaultKind (tyVarKind tv))
395 immut_tv_ty = mkTyVarTy immut_tv
397 zap tv = tcPutTyVar tv immut_tv_ty
398 -- Bind the mutable version to the immutable one
400 -- If the type variable is mutable, then bind it to immut_tv_ty
401 -- so that all other occurrences of the tyvar will get zapped too
402 zonkTyVar zap tv `thenNF_Tc` \ ty2 ->
404 WARN( not (immut_tv_ty `tcEqType` ty2), ppr tv $$ ppr immut_tv $$ ppr ty2 )
410 %************************************************************************
412 \subsection{Zonking -- the main work-horses: zonkType, zonkTyVar}
414 %* For internal use only! *
416 %************************************************************************
419 -- zonkType is used for Kinds as well
421 -- For unbound, mutable tyvars, zonkType uses the function given to it
422 -- For tyvars bound at a for-all, zonkType zonks them to an immutable
423 -- type variable and zonks the kind too
425 zonkType :: (TcTyVar -> NF_TcM Type) -- What to do with unbound mutable type variables
426 -- see zonkTcType, and zonkTcTypeToType
429 zonkType unbound_var_fn ty
432 go (TyConApp tycon tys) = mapNF_Tc go tys `thenNF_Tc` \ tys' ->
433 returnNF_Tc (TyConApp tycon tys')
435 go (NoteTy (SynNote ty1) ty2) = go ty1 `thenNF_Tc` \ ty1' ->
436 go ty2 `thenNF_Tc` \ ty2' ->
437 returnNF_Tc (NoteTy (SynNote ty1') ty2')
439 go (NoteTy (FTVNote _) ty2) = go ty2 -- Discard free-tyvar annotations
441 go (SourceTy p) = go_pred p `thenNF_Tc` \ p' ->
442 returnNF_Tc (SourceTy p')
444 go (FunTy arg res) = go arg `thenNF_Tc` \ arg' ->
445 go res `thenNF_Tc` \ res' ->
446 returnNF_Tc (FunTy arg' res')
448 go (AppTy fun arg) = go fun `thenNF_Tc` \ fun' ->
449 go arg `thenNF_Tc` \ arg' ->
450 returnNF_Tc (mkAppTy fun' arg')
452 go (UsageTy u ty) = go u `thenNF_Tc` \ u' ->
453 go ty `thenNF_Tc` \ ty' ->
454 returnNF_Tc (mkUTy u' ty')
456 -- The two interesting cases!
457 go (TyVarTy tyvar) = zonkTyVar unbound_var_fn tyvar
459 go (ForAllTy tyvar ty) = zonkTcTyVarToTyVar tyvar `thenNF_Tc` \ tyvar' ->
460 go ty `thenNF_Tc` \ ty' ->
461 returnNF_Tc (ForAllTy tyvar' ty')
463 go_pred (ClassP c tys) = mapNF_Tc go tys `thenNF_Tc` \ tys' ->
464 returnNF_Tc (ClassP c tys')
465 go_pred (NType tc tys) = mapNF_Tc go tys `thenNF_Tc` \ tys' ->
466 returnNF_Tc (NType tc tys')
467 go_pred (IParam n ty) = go ty `thenNF_Tc` \ ty' ->
468 returnNF_Tc (IParam n ty')
470 zonkTyVar :: (TcTyVar -> NF_TcM Type) -- What to do for an unbound mutable variable
471 -> TcTyVar -> NF_TcM TcType
472 zonkTyVar unbound_var_fn tyvar
473 | not (isMutTyVar tyvar) -- Not a mutable tyvar. This can happen when
474 -- zonking a forall type, when the bound type variable
475 -- needn't be mutable
476 = ASSERT( isTyVar tyvar ) -- Should not be any immutable kind vars
477 returnNF_Tc (TyVarTy tyvar)
480 = tcGetTyVar tyvar `thenNF_Tc` \ maybe_ty ->
482 Nothing -> unbound_var_fn tyvar -- Mutable and unbound
483 Just other_ty -> zonkType unbound_var_fn other_ty -- Bound
488 %************************************************************************
490 \subsection{The Kind variants}
492 %************************************************************************
495 unifyKind :: TcKind -- Expected
499 = tcAddErrCtxtM (unifyCtxt "kind" k1 k2) $
502 unifyKinds :: [TcKind] -> [TcKind] -> TcM ()
503 unifyKinds [] [] = returnTc ()
504 unifyKinds (k1:ks1) (k2:ks2) = unifyKind k1 k2 `thenTc_`
506 unifyKinds _ _ = panic "unifyKinds: length mis-match"
510 unifyOpenTypeKind :: TcKind -> TcM ()
511 -- Ensures that the argument kind is of the form (Type bx)
512 -- for some boxity bx
514 unifyOpenTypeKind ty@(TyVarTy tyvar)
515 = tcGetTyVar tyvar `thenNF_Tc` \ maybe_ty ->
517 Just ty' -> unifyOpenTypeKind ty'
518 other -> unify_open_kind_help ty
521 = case tcSplitTyConApp_maybe ty of
522 Just (tycon, [_]) | tycon == typeCon -> returnTc ()
523 other -> unify_open_kind_help ty
525 unify_open_kind_help ty -- Revert to ordinary unification
526 = newBoxityVar `thenNF_Tc` \ boxity ->
527 unifyKind ty (mkTyConApp typeCon [boxity])
531 %************************************************************************
533 \subsection[Unify-exported]{Exported unification functions}
535 %************************************************************************
537 The exported functions are all defined as versions of some
538 non-exported generic functions.
540 Unify two @TauType@s. Dead straightforward.
543 unifyTauTy :: TcTauType -> TcTauType -> TcM ()
544 unifyTauTy ty1 ty2 -- ty1 expected, ty2 inferred
545 = tcAddErrCtxtM (unifyCtxt "type" ty1 ty2) $
549 @unifyTauTyList@ unifies corresponding elements of two lists of
550 @TauType@s. It uses @uTys@ to do the real work. The lists should be
551 of equal length. We charge down the list explicitly so that we can
552 complain if their lengths differ.
555 unifyTauTyLists :: [TcTauType] -> [TcTauType] -> TcM ()
556 unifyTauTyLists [] [] = returnTc ()
557 unifyTauTyLists (ty1:tys1) (ty2:tys2) = uTys ty1 ty1 ty2 ty2 `thenTc_`
558 unifyTauTyLists tys1 tys2
559 unifyTauTyLists ty1s ty2s = panic "Unify.unifyTauTyLists: mismatched type lists!"
562 @unifyTauTyList@ takes a single list of @TauType@s and unifies them
563 all together. It is used, for example, when typechecking explicit
564 lists, when all the elts should be of the same type.
567 unifyTauTyList :: [TcTauType] -> TcM ()
568 unifyTauTyList [] = returnTc ()
569 unifyTauTyList [ty] = returnTc ()
570 unifyTauTyList (ty1:tys@(ty2:_)) = unifyTauTy ty1 ty2 `thenTc_`
574 %************************************************************************
576 \subsection[Unify-uTys]{@uTys@: getting down to business}
578 %************************************************************************
580 @uTys@ is the heart of the unifier. Each arg happens twice, because
581 we want to report errors in terms of synomyms if poss. The first of
582 the pair is used in error messages only; it is always the same as the
583 second, except that if the first is a synonym then the second may be a
584 de-synonym'd version. This way we get better error messages.
586 We call the first one \tr{ps_ty1}, \tr{ps_ty2} for ``possible synomym''.
589 uTys :: TcTauType -> TcTauType -- Error reporting ty1 and real ty1
590 -- ty1 is the *expected* type
592 -> TcTauType -> TcTauType -- Error reporting ty2 and real ty2
593 -- ty2 is the *actual* type
596 -- Always expand synonyms (see notes at end)
597 -- (this also throws away FTVs)
598 uTys ps_ty1 (NoteTy n1 ty1) ps_ty2 ty2 = uTys ps_ty1 ty1 ps_ty2 ty2
599 uTys ps_ty1 ty1 ps_ty2 (NoteTy n2 ty2) = uTys ps_ty1 ty1 ps_ty2 ty2
601 -- Ignore usage annotations inside typechecker
602 uTys ps_ty1 (UsageTy _ ty1) ps_ty2 ty2 = uTys ps_ty1 ty1 ps_ty2 ty2
603 uTys ps_ty1 ty1 ps_ty2 (UsageTy _ ty2) = uTys ps_ty1 ty1 ps_ty2 ty2
605 -- Variables; go for uVar
606 uTys ps_ty1 (TyVarTy tyvar1) ps_ty2 ty2 = uVar False tyvar1 ps_ty2 ty2
607 uTys ps_ty1 ty1 ps_ty2 (TyVarTy tyvar2) = uVar True tyvar2 ps_ty1 ty1
608 -- "True" means args swapped
611 uTys _ (SourceTy (IParam n1 t1)) _ (SourceTy (IParam n2 t2))
612 | n1 == n2 = uTys t1 t1 t2 t2
613 uTys _ (SourceTy (ClassP c1 tys1)) _ (SourceTy (ClassP c2 tys2))
614 | c1 == c2 = unifyTauTyLists tys1 tys2
615 uTys _ (SourceTy (NType tc1 tys1)) _ (SourceTy (NType tc2 tys2))
616 | tc1 == tc2 = unifyTauTyLists tys1 tys2
618 -- Functions; just check the two parts
619 uTys _ (FunTy fun1 arg1) _ (FunTy fun2 arg2)
620 = uTys fun1 fun1 fun2 fun2 `thenTc_` uTys arg1 arg1 arg2 arg2
622 -- Type constructors must match
623 uTys ps_ty1 (TyConApp con1 tys1) ps_ty2 (TyConApp con2 tys2)
624 | con1 == con2 && length tys1 == length tys2
625 = unifyTauTyLists tys1 tys2
627 | con1 == openKindCon
628 -- When we are doing kind checking, we might match a kind '?'
629 -- against a kind '*' or '#'. Notably, CCallable :: ? -> *, and
630 -- (CCallable Int) and (CCallable Int#) are both OK
631 = unifyOpenTypeKind ps_ty2
633 -- Applications need a bit of care!
634 -- They can match FunTy and TyConApp, so use splitAppTy_maybe
635 -- NB: we've already dealt with type variables and Notes,
636 -- so if one type is an App the other one jolly well better be too
637 uTys ps_ty1 (AppTy s1 t1) ps_ty2 ty2
638 = case tcSplitAppTy_maybe ty2 of
639 Just (s2,t2) -> uTys s1 s1 s2 s2 `thenTc_` uTys t1 t1 t2 t2
640 Nothing -> unifyMisMatch ps_ty1 ps_ty2
642 -- Now the same, but the other way round
643 -- Don't swap the types, because the error messages get worse
644 uTys ps_ty1 ty1 ps_ty2 (AppTy s2 t2)
645 = case tcSplitAppTy_maybe ty1 of
646 Just (s1,t1) -> uTys s1 s1 s2 s2 `thenTc_` uTys t1 t1 t2 t2
647 Nothing -> unifyMisMatch ps_ty1 ps_ty2
649 -- Not expecting for-alls in unification
650 -- ... but the error message from the unifyMisMatch more informative
651 -- than a panic message!
653 -- Anything else fails
654 uTys ps_ty1 ty1 ps_ty2 ty2 = unifyMisMatch ps_ty1 ps_ty2
660 If you are tempted to make a short cut on synonyms, as in this
664 -- NO uTys (SynTy con1 args1 ty1) (SynTy con2 args2 ty2)
665 -- NO = if (con1 == con2) then
666 -- NO -- Good news! Same synonym constructors, so we can shortcut
667 -- NO -- by unifying their arguments and ignoring their expansions.
668 -- NO unifyTauTypeLists args1 args2
670 -- NO -- Never mind. Just expand them and try again
674 then THINK AGAIN. Here is the whole story, as detected and reported
675 by Chris Okasaki \tr{<Chris_Okasaki@loch.mess.cs.cmu.edu>}:
677 Here's a test program that should detect the problem:
681 x = (1 :: Bogus Char) :: Bogus Bool
684 The problem with [the attempted shortcut code] is that
688 is not a sufficient condition to be able to use the shortcut!
689 You also need to know that the type synonym actually USES all
690 its arguments. For example, consider the following type synonym
691 which does not use all its arguments.
696 If you ever tried unifying, say, \tr{Bogus Char} with \tr{Bogus Bool},
697 the unifier would blithely try to unify \tr{Char} with \tr{Bool} and
698 would fail, even though the expanded forms (both \tr{Int}) should
701 Similarly, unifying \tr{Bogus Char} with \tr{Bogus t} would
702 unnecessarily bind \tr{t} to \tr{Char}.
704 ... You could explicitly test for the problem synonyms and mark them
705 somehow as needing expansion, perhaps also issuing a warning to the
710 %************************************************************************
712 \subsection[Unify-uVar]{@uVar@: unifying with a type variable}
714 %************************************************************************
716 @uVar@ is called when at least one of the types being unified is a
717 variable. It does {\em not} assume that the variable is a fixed point
718 of the substitution; rather, notice that @uVar@ (defined below) nips
719 back into @uTys@ if it turns out that the variable is already bound.
722 uVar :: Bool -- False => tyvar is the "expected"
723 -- True => ty is the "expected" thing
725 -> TcTauType -> TcTauType -- printing and real versions
728 uVar swapped tv1 ps_ty2 ty2
729 = tcGetTyVar tv1 `thenNF_Tc` \ maybe_ty1 ->
731 Just ty1 | swapped -> uTys ps_ty2 ty2 ty1 ty1 -- Swap back
732 | otherwise -> uTys ty1 ty1 ps_ty2 ty2 -- Same order
733 other -> uUnboundVar swapped tv1 maybe_ty1 ps_ty2 ty2
735 -- Expand synonyms; ignore FTVs
736 uUnboundVar swapped tv1 maybe_ty1 ps_ty2 (NoteTy n2 ty2)
737 = uUnboundVar swapped tv1 maybe_ty1 ps_ty2 ty2
740 -- The both-type-variable case
741 uUnboundVar swapped tv1 maybe_ty1 ps_ty2 ty2@(TyVarTy tv2)
743 -- Same type variable => no-op
747 -- Distinct type variables
748 -- ASSERT maybe_ty1 /= Just
750 = tcGetTyVar tv2 `thenNF_Tc` \ maybe_ty2 ->
752 Just ty2' -> uUnboundVar swapped tv1 maybe_ty1 ty2' ty2'
756 -> WARN( not (k1 `hasMoreBoxityInfo` k2), (ppr tv1 <+> ppr k1) $$ (ppr tv2 <+> ppr k2) )
757 tcPutTyVar tv2 (TyVarTy tv1) `thenNF_Tc_`
761 -> WARN( not (k2 `hasMoreBoxityInfo` k1), (ppr tv2 <+> ppr k2) $$ (ppr tv1 <+> ppr k1) )
762 (tcPutTyVar tv1 ps_ty2 `thenNF_Tc_`
767 update_tv2 = (k2 `eqKind` openTypeKind) || (not (k1 `eqKind` openTypeKind) && nicer_to_update_tv2)
768 -- Try to get rid of open type variables as soon as poss
770 nicer_to_update_tv2 = isSigTyVar tv1
771 -- Don't unify a signature type variable if poss
772 || isSystemName (varName tv2)
773 -- Try to update sys-y type variables in preference to sig-y ones
775 -- Second one isn't a type variable
776 uUnboundVar swapped tv1 maybe_ty1 ps_ty2 non_var_ty2
777 = -- Check that the kinds match
778 checkKinds swapped tv1 non_var_ty2 `thenTc_`
780 -- Check that tv1 isn't a type-signature type variable
781 checkTcM (not (isSigTyVar tv1))
782 (failWithTcM (unifyWithSigErr tv1 ps_ty2)) `thenTc_`
784 -- Check that we aren't losing boxity info (shouldn't happen)
785 warnTc (not (typeKind non_var_ty2 `hasMoreBoxityInfo` tyVarKind tv1))
786 ((ppr tv1 <+> ppr (tyVarKind tv1)) $$
787 (ppr non_var_ty2 <+> ppr (typeKind non_var_ty2))) `thenNF_Tc_`
790 -- Basically we want to update tv1 := ps_ty2
791 -- because ps_ty2 has type-synonym info, which improves later error messages
796 -- f :: (A a -> a -> ()) -> ()
800 -- x = f (\ x p -> p x)
802 -- In the application (p x), we try to match "t" with "A t". If we go
803 -- ahead and bind t to A t (= ps_ty2), we'll lead the type checker into
804 -- an infinite loop later.
805 -- But we should not reject the program, because A t = ().
806 -- Rather, we should bind t to () (= non_var_ty2).
808 -- That's why we have this two-state occurs-check
809 zonkTcType ps_ty2 `thenNF_Tc` \ ps_ty2' ->
810 if not (tv1 `elemVarSet` tyVarsOfType ps_ty2') then
811 tcPutTyVar tv1 ps_ty2' `thenNF_Tc_`
814 zonkTcType non_var_ty2 `thenNF_Tc` \ non_var_ty2' ->
815 if not (tv1 `elemVarSet` tyVarsOfType non_var_ty2') then
816 -- This branch rarely succeeds, except in strange cases
817 -- like that in the example above
818 tcPutTyVar tv1 non_var_ty2' `thenNF_Tc_`
821 failWithTcM (unifyOccurCheck tv1 ps_ty2')
824 checkKinds swapped tv1 ty2
825 -- We're about to unify a type variable tv1 with a non-tyvar-type ty2.
826 -- We need to check that we don't unify a lifted type variable with an
827 -- unlifted type: e.g. (id 3#) is illegal
828 | tk1 `eqKind` liftedTypeKind && tk2 `eqKind` unliftedTypeKind
829 = tcAddErrCtxtM (unifyKindCtxt swapped tv1 ty2) $
834 (k1,k2) | swapped = (tk2,tk1)
835 | otherwise = (tk1,tk2)
841 %************************************************************************
843 \subsection[Unify-fun]{@unifyFunTy@}
845 %************************************************************************
847 @unifyFunTy@ is used to avoid the fruitless creation of type variables.
850 unifyFunTy :: TcType -- Fail if ty isn't a function type
851 -> TcM (TcType, TcType) -- otherwise return arg and result types
853 unifyFunTy ty@(TyVarTy tyvar)
854 = tcGetTyVar tyvar `thenNF_Tc` \ maybe_ty ->
856 Just ty' -> unifyFunTy ty'
857 other -> unify_fun_ty_help ty
860 = case tcSplitFunTy_maybe ty of
861 Just arg_and_res -> returnTc arg_and_res
862 Nothing -> unify_fun_ty_help ty
864 unify_fun_ty_help ty -- Special cases failed, so revert to ordinary unification
865 = newTyVarTy openTypeKind `thenNF_Tc` \ arg ->
866 newTyVarTy openTypeKind `thenNF_Tc` \ res ->
867 unifyTauTy ty (mkFunTy arg res) `thenTc_`
872 unifyListTy :: TcType -- expected list type
873 -> TcM TcType -- list element type
875 unifyListTy ty@(TyVarTy tyvar)
876 = tcGetTyVar tyvar `thenNF_Tc` \ maybe_ty ->
878 Just ty' -> unifyListTy ty'
879 other -> unify_list_ty_help ty
882 = case tcSplitTyConApp_maybe ty of
883 Just (tycon, [arg_ty]) | tycon == listTyCon -> returnTc arg_ty
884 other -> unify_list_ty_help ty
886 unify_list_ty_help ty -- Revert to ordinary unification
887 = newTyVarTy liftedTypeKind `thenNF_Tc` \ elt_ty ->
888 unifyTauTy ty (mkListTy elt_ty) `thenTc_`
893 unifyTupleTy :: Boxity -> Arity -> TcType -> TcM [TcType]
894 unifyTupleTy boxity arity ty@(TyVarTy tyvar)
895 = tcGetTyVar tyvar `thenNF_Tc` \ maybe_ty ->
897 Just ty' -> unifyTupleTy boxity arity ty'
898 other -> unify_tuple_ty_help boxity arity ty
900 unifyTupleTy boxity arity ty
901 = case tcSplitTyConApp_maybe ty of
902 Just (tycon, arg_tys)
904 && tyConArity tycon == arity
905 && tupleTyConBoxity tycon == boxity
907 other -> unify_tuple_ty_help boxity arity ty
909 unify_tuple_ty_help boxity arity ty
910 = newTyVarTys arity kind `thenNF_Tc` \ arg_tys ->
911 unifyTauTy ty (mkTupleTy boxity arity arg_tys) `thenTc_`
914 kind | isBoxed boxity = liftedTypeKind
915 | otherwise = openTypeKind
919 %************************************************************************
921 \subsection[Unify-context]{Errors and contexts}
923 %************************************************************************
929 unifyCtxt s ty1 ty2 tidy_env -- ty1 expected, ty2 inferred
930 = zonkTcType ty1 `thenNF_Tc` \ ty1' ->
931 zonkTcType ty2 `thenNF_Tc` \ ty2' ->
932 returnNF_Tc (err ty1' ty2')
937 text "Expected" <+> text s <> colon <+> ppr tidy_ty1,
938 text "Inferred" <+> text s <> colon <+> ppr tidy_ty2
941 (env1, [tidy_ty1,tidy_ty2]) = tidyOpenTypes tidy_env [ty1,ty2]
943 unifyKindCtxt swapped tv1 ty2 tidy_env -- not swapped => tv1 expected, ty2 inferred
944 -- tv1 is zonked already
945 = zonkTcType ty2 `thenNF_Tc` \ ty2' ->
946 returnNF_Tc (err ty2')
948 err ty2 = (env2, ptext SLIT("When matching types") <+>
949 sep [quotes pp_expected, ptext SLIT("and"), quotes pp_actual])
951 (pp_expected, pp_actual) | swapped = (pp2, pp1)
952 | otherwise = (pp1, pp2)
953 (env1, tv1') = tidyTyVar tidy_env tv1
954 (env2, ty2') = tidyOpenType env1 ty2
958 unifyMisMatch ty1 ty2
959 = zonkTcType ty1 `thenNF_Tc` \ ty1' ->
960 zonkTcType ty2 `thenNF_Tc` \ ty2' ->
962 (env, [tidy_ty1, tidy_ty2]) = tidyOpenTypes emptyTidyEnv [ty1',ty2']
963 msg = hang (ptext SLIT("Couldn't match"))
964 4 (sep [quotes (ppr tidy_ty1),
965 ptext SLIT("against"),
966 quotes (ppr tidy_ty2)])
968 failWithTcM (env, msg)
970 unifyWithSigErr tyvar ty
971 = (env2, hang (ptext SLIT("Cannot unify the type-signature variable") <+> quotes (ppr tidy_tyvar))
972 4 (ptext SLIT("with the type") <+> quotes (ppr tidy_ty)))
974 (env1, tidy_tyvar) = tidyTyVar emptyTidyEnv tyvar
975 (env2, tidy_ty) = tidyOpenType env1 ty
977 unifyOccurCheck tyvar ty
978 = (env2, hang (ptext SLIT("Occurs check: cannot construct the infinite type:"))
979 4 (sep [ppr tidy_tyvar, char '=', ppr tidy_ty]))
981 (env1, tidy_tyvar) = tidyTyVar emptyTidyEnv tyvar
982 (env2, tidy_ty) = tidyOpenType env1 ty