2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[Unify]{Unifier}
6 The unifier is now squarely in the typechecker monad (because of the
7 updatable substitution).
10 module TcUnify ( unifyTauTy, unifyTauTyList, unifyTauTyLists,
11 unifyFunTy, unifyListTy, unifyTupleTy,
12 unifyKind, unifyKinds, unifyTypeKind
15 #include "HsVersions.h"
19 import TypeRep ( Type(..), funTyCon,
20 Kind, boxedTypeKind, typeCon, anyBoxCon, anyBoxKind,
22 import Type ( tyVarsOfType,
23 mkFunTy, splitFunTy_maybe, splitTyConApp_maybe,
26 tidyOpenType, tidyOpenTypes, tidyTyVar
28 import TyCon ( TyCon, isTupleTyCon, tupleTyConBoxity, tyConArity )
29 import Name ( hasBetterProv )
30 import Var ( TyVar, tyVarKind, varName, isSigTyVar )
31 import VarSet ( varSetElems )
32 import TcType ( TcType, TcTauType, TcTyVar, TcKind,
33 newTyVarTy, newOpenTypeKind, newTyVarTy_OpenKind,
34 tcGetTyVar, tcPutTyVar, zonkTcType, tcTypeKind
38 import BasicTypes ( Arity, Boxity, isBoxed )
39 import TysWiredIn ( listTyCon, mkListTy, mkTupleTy )
44 %************************************************************************
46 \subsection{The Kind variants}
48 %************************************************************************
51 unifyKind :: TcKind -- Expected
55 = tcAddErrCtxtM (unifyCtxt "kind" k1 k2) $
58 unifyKinds :: [TcKind] -> [TcKind] -> TcM s ()
59 unifyKinds [] [] = returnTc ()
60 unifyKinds (k1:ks1) (k2:ks2) = unifyKind k1 k2 `thenTc_`
62 unifyKinds _ _ = panic "unifyKinds: length mis-match"
66 %************************************************************************
68 \subsection[Unify-exported]{Exported unification functions}
70 %************************************************************************
72 The exported functions are all defined as versions of some
73 non-exported generic functions.
75 Unify two @TauType@s. Dead straightforward.
78 unifyTauTy :: TcTauType -> TcTauType -> TcM s ()
79 unifyTauTy ty1 ty2 -- ty1 expected, ty2 inferred
80 = tcAddErrCtxtM (unifyCtxt "type" ty1 ty2) $
84 @unifyTauTyList@ unifies corresponding elements of two lists of
85 @TauType@s. It uses @uTys@ to do the real work. The lists should be
86 of equal length. We charge down the list explicitly so that we can
87 complain if their lengths differ.
90 unifyTauTyLists :: [TcTauType] -> [TcTauType] -> TcM s ()
91 unifyTauTyLists [] [] = returnTc ()
92 unifyTauTyLists (ty1:tys1) (ty2:tys2) = uTys ty1 ty1 ty2 ty2 `thenTc_`
93 unifyTauTyLists tys1 tys2
94 unifyTauTyLists ty1s ty2s = panic "Unify.unifyTauTyLists: mismatched type lists!"
97 @unifyTauTyList@ takes a single list of @TauType@s and unifies them
98 all together. It is used, for example, when typechecking explicit
99 lists, when all the elts should be of the same type.
102 unifyTauTyList :: [TcTauType] -> TcM s ()
103 unifyTauTyList [] = returnTc ()
104 unifyTauTyList [ty] = returnTc ()
105 unifyTauTyList (ty1:tys@(ty2:_)) = unifyTauTy ty1 ty2 `thenTc_`
109 %************************************************************************
111 \subsection[Unify-uTys]{@uTys@: getting down to business}
113 %************************************************************************
115 @uTys@ is the heart of the unifier. Each arg happens twice, because
116 we want to report errors in terms of synomyms if poss. The first of
117 the pair is used in error messages only; it is always the same as the
118 second, except that if the first is a synonym then the second may be a
119 de-synonym'd version. This way we get better error messages.
121 We call the first one \tr{ps_ty1}, \tr{ps_ty2} for ``possible synomym''.
124 uTys :: TcTauType -> TcTauType -- Error reporting ty1 and real ty1
125 -> TcTauType -> TcTauType -- Error reporting ty2 and real ty2
128 -- Always expand synonyms (see notes at end)
129 -- (this also throws away FTVs and usage annots)
130 uTys ps_ty1 (NoteTy _ ty1) ps_ty2 ty2 = uTys ps_ty1 ty1 ps_ty2 ty2
131 uTys ps_ty1 ty1 ps_ty2 (NoteTy _ ty2) = uTys ps_ty1 ty1 ps_ty2 ty2
133 -- Variables; go for uVar
134 uTys ps_ty1 (TyVarTy tyvar1) ps_ty2 ty2 = uVar False tyvar1 ps_ty2 ty2
135 uTys ps_ty1 ty1 ps_ty2 (TyVarTy tyvar2) = uVar True tyvar2 ps_ty1 ty1
136 -- "True" means args swapped
138 -- Functions; just check the two parts
139 uTys _ (FunTy fun1 arg1) _ (FunTy fun2 arg2)
140 = uTys fun1 fun1 fun2 fun2 `thenTc_` uTys arg1 arg1 arg2 arg2
142 -- Type constructors must match
143 uTys ps_ty1 (TyConApp con1 tys1) ps_ty2 (TyConApp con2 tys2)
144 = checkTcM (cons_match && length tys1 == length tys2)
145 (unifyMisMatch ps_ty1 ps_ty2) `thenTc_`
146 unifyTauTyLists tys1 tys2
148 -- The AnyBox wild card matches anything
149 cons_match = con1 == con2
153 -- Applications need a bit of care!
154 -- They can match FunTy and TyConApp, so use splitAppTy_maybe
155 -- NB: we've already dealt with type variables and Notes,
156 -- so if one type is an App the other one jolly well better be too
157 uTys ps_ty1 (AppTy s1 t1) ps_ty2 ty2
158 = case splitAppTy_maybe ty2 of
159 Just (s2,t2) -> uTys s1 s1 s2 s2 `thenTc_` uTys t1 t1 t2 t2
160 Nothing -> unifyMisMatch ps_ty1 ps_ty2
162 -- Now the same, but the other way round
163 -- Don't swap the types, because the error messages get worse
164 uTys ps_ty1 ty1 ps_ty2 (AppTy s2 t2)
165 = case splitAppTy_maybe ty1 of
166 Just (s1,t1) -> uTys s1 s1 s2 s2 `thenTc_` uTys t1 t1 t2 t2
167 Nothing -> unifyMisMatch ps_ty1 ps_ty2
169 -- Not expecting for-alls in unification
170 -- ... but the error message from the unifyMisMatch more informative
171 -- than a panic message!
173 -- Anything else fails
174 uTys ps_ty1 ty1 ps_ty2 ty2 = unifyMisMatch ps_ty1 ps_ty2
179 If you are tempted to make a short cut on synonyms, as in this
183 uTys (SynTy con1 args1 ty1) (SynTy con2 args2 ty2)
184 = if (con1 == con2) then
185 -- Good news! Same synonym constructors, so we can shortcut
186 -- by unifying their arguments and ignoring their expansions.
187 unifyTauTypeLists args1 args2
189 -- Never mind. Just expand them and try again
193 then THINK AGAIN. Here is the whole story, as detected and reported
194 by Chris Okasaki \tr{<Chris_Okasaki@loch.mess.cs.cmu.edu>}:
196 Here's a test program that should detect the problem:
200 x = (1 :: Bogus Char) :: Bogus Bool
203 The problem with [the attempted shortcut code] is that
207 is not a sufficient condition to be able to use the shortcut!
208 You also need to know that the type synonym actually USES all
209 its arguments. For example, consider the following type synonym
210 which does not use all its arguments.
215 If you ever tried unifying, say, \tr{Bogus Char} with \tr{Bogus Bool},
216 the unifier would blithely try to unify \tr{Char} with \tr{Bool} and
217 would fail, even though the expanded forms (both \tr{Int}) should
220 Similarly, unifying \tr{Bogus Char} with \tr{Bogus t} would
221 unnecessarily bind \tr{t} to \tr{Char}.
223 ... You could explicitly test for the problem synonyms and mark them
224 somehow as needing expansion, perhaps also issuing a warning to the
229 %************************************************************************
231 \subsection[Unify-uVar]{@uVar@: unifying with a type variable}
233 %************************************************************************
235 @uVar@ is called when at least one of the types being unified is a
236 variable. It does {\em not} assume that the variable is a fixed point
237 of the substitution; rather, notice that @uVar@ (defined below) nips
238 back into @uTys@ if it turns out that the variable is already bound.
241 uVar :: Bool -- False => tyvar is the "expected"
242 -- True => ty is the "expected" thing
244 -> TcTauType -> TcTauType -- printing and real versions
247 uVar swapped tv1 ps_ty2 ty2
248 = tcGetTyVar tv1 `thenNF_Tc` \ maybe_ty1 ->
250 Just ty1 | swapped -> uTys ps_ty2 ty2 ty1 ty1 -- Swap back
251 | otherwise -> uTys ty1 ty1 ps_ty2 ty2 -- Same order
252 other -> uUnboundVar swapped tv1 maybe_ty1 ps_ty2 ty2
254 -- Expand synonyms; ignore FTVs; ignore usage annots
255 uUnboundVar swapped tv1 maybe_ty1 ps_ty2 (NoteTy _ ty2)
256 = uUnboundVar swapped tv1 maybe_ty1 ps_ty2 ty2
259 -- The both-type-variable case
260 uUnboundVar swapped tv1 maybe_ty1 ps_ty2 ty2@(TyVarTy tv2)
262 -- Same type variable => no-op
266 -- Distinct type variables
267 -- ASSERT maybe_ty1 /= Just
269 = tcGetTyVar tv2 `thenNF_Tc` \ maybe_ty2 ->
271 Just ty2' -> uUnboundVar swapped tv1 maybe_ty1 ty2' ty2'
273 Nothing -> checkKinds swapped tv1 ty2 `thenTc_`
275 if tv1 `dominates` tv2 then
276 tcPutTyVar tv2 (TyVarTy tv1) `thenNF_Tc_`
279 ASSERT( isNotUsgTy ps_ty2 )
280 tcPutTyVar tv1 ps_ty2 `thenNF_Tc_`
283 tv1 `dominates` tv2 = isSigTyVar tv1
284 -- Don't unify a signature type variable if poss
285 || varName tv1 `hasBetterProv` varName tv2
286 -- Try to update sys-y type variables in preference to sig-y ones
288 -- Second one isn't a type variable
289 uUnboundVar swapped tv1 maybe_ty1 ps_ty2 non_var_ty2
290 | non_var_ty2 == anyBoxKind
295 = checkKinds swapped tv1 non_var_ty2 `thenTc_`
296 occur_check non_var_ty2 `thenTc_`
297 ASSERT( isNotUsgTy ps_ty2 )
298 checkTcM (not (isSigTyVar tv1))
299 (failWithTcM (unifyWithSigErr tv1 ps_ty2)) `thenTc_`
301 tcPutTyVar tv1 non_var_ty2 `thenNF_Tc_`
302 -- This used to say "ps_ty2" instead of "non_var_ty2"
304 -- But that led to an infinite loop in the type checker!
308 -- f :: (A a -> a -> ()) -> ()
312 -- x = f (\ x p -> p x)
314 -- Here, we try to match "t" with "A t", and succeed
315 -- because the unifier looks through synonyms. The occurs
316 -- check doesn't kick in because we are "really" binding "t" to "()",
317 -- but we *actually* bind "t" to "A t" if we store ps_ty2.
318 -- That leads the typechecker into an infinite loop later.
322 occur_check ty = mapTc occur_check_tv (varSetElems (tyVarsOfType ty)) `thenTc_`
326 | tv1 == tv2 -- Same tyvar; fail
327 = zonkTcType ps_ty2 `thenNF_Tc` \ zonked_ty2 ->
328 failWithTcM (unifyOccurCheck tv1 zonked_ty2)
330 | otherwise -- A different tyvar
331 = tcGetTyVar tv2 `thenNF_Tc` \ maybe_ty2 ->
333 Just ty2' -> occur_check ty2'
336 checkKinds swapped tv1 ty2
337 = tcAddErrCtxtM (unifyKindCtxt swapped tv1 ty2) $
339 -- We have to use tcTypeKind not just typeKind to get the
340 -- kind of ty2, because there might be mutable kind variables
341 -- in the way. For example, suppose that ty2 :: (a b), and
342 -- the kind of 'a' is a kind variable 'k' that has (presumably)
343 -- been unified with 'k1 -> k2'.
344 tcTypeKind ty2 `thenNF_Tc` \ k2 ->
347 unifyKind k2 (tyVarKind tv1)
349 unifyKind (tyVarKind tv1) k2
352 %************************************************************************
354 \subsection[Unify-fun]{@unifyFunTy@}
356 %************************************************************************
358 @unifyFunTy@ is used to avoid the fruitless creation of type variables.
361 unifyFunTy :: TcType -- Fail if ty isn't a function type
362 -> TcM s (TcType, TcType) -- otherwise return arg and result types
364 unifyFunTy ty@(TyVarTy tyvar)
365 = tcGetTyVar tyvar `thenNF_Tc` \ maybe_ty ->
367 Just ty' -> unifyFunTy ty'
368 other -> unify_fun_ty_help ty
371 = case splitFunTy_maybe ty of
372 Just arg_and_res -> returnTc arg_and_res
373 Nothing -> unify_fun_ty_help ty
375 unify_fun_ty_help ty -- Special cases failed, so revert to ordinary unification
376 = newTyVarTy_OpenKind `thenNF_Tc` \ arg ->
377 newTyVarTy_OpenKind `thenNF_Tc` \ res ->
378 unifyTauTy ty (mkFunTy arg res) `thenTc_`
383 unifyListTy :: TcType -- expected list type
384 -> TcM s TcType -- list element type
386 unifyListTy ty@(TyVarTy tyvar)
387 = tcGetTyVar tyvar `thenNF_Tc` \ maybe_ty ->
389 Just ty' -> unifyListTy ty'
390 other -> unify_list_ty_help ty
393 = case splitTyConApp_maybe ty of
394 Just (tycon, [arg_ty]) | tycon == listTyCon -> returnTc arg_ty
395 other -> unify_list_ty_help ty
397 unify_list_ty_help ty -- Revert to ordinary unification
398 = newTyVarTy boxedTypeKind `thenNF_Tc` \ elt_ty ->
399 unifyTauTy ty (mkListTy elt_ty) `thenTc_`
404 unifyTupleTy :: Boxity -> Arity -> TcType -> TcM s [TcType]
405 unifyTupleTy boxity arity ty@(TyVarTy tyvar)
406 = tcGetTyVar tyvar `thenNF_Tc` \ maybe_ty ->
408 Just ty' -> unifyTupleTy boxity arity ty'
409 other -> unify_tuple_ty_help boxity arity ty
411 unifyTupleTy boxity arity ty
412 = case splitTyConApp_maybe ty of
413 Just (tycon, arg_tys)
415 && tyConArity tycon == arity
416 && tupleTyConBoxity tycon == boxity
418 other -> unify_tuple_ty_help boxity arity ty
420 unify_tuple_ty_help boxity arity ty
421 = mapNF_Tc new_tyvar [1..arity] `thenNF_Tc` \ arg_tys ->
422 unifyTauTy ty (mkTupleTy boxity arity arg_tys) `thenTc_`
425 new_tyvar _ | isBoxed boxity = newTyVarTy boxedTypeKind
426 | otherwise = newTyVarTy_OpenKind
429 Make sure a kind is of the form (Type b) for some boxity b.
432 unifyTypeKind :: TcKind -> TcM s ()
433 unifyTypeKind kind@(TyVarTy kv)
434 = tcGetTyVar kv `thenNF_Tc` \ maybe_kind ->
436 Just kind' -> unifyTypeKind kind'
437 Nothing -> unify_type_kind_help kind
440 = case splitTyConApp_maybe kind of
441 Just (tycon, [_]) | tycon == typeCon -> returnTc ()
442 other -> unify_type_kind_help kind
444 unify_type_kind_help kind
445 = newOpenTypeKind `thenNF_Tc` \ expected_kind ->
446 unifyKind expected_kind kind
450 %************************************************************************
452 \subsection[Unify-context]{Errors and contexts}
454 %************************************************************************
460 unifyCtxt s ty1 ty2 tidy_env -- ty1 expected, ty2 inferred
461 = zonkTcType ty1 `thenNF_Tc` \ ty1' ->
462 zonkTcType ty2 `thenNF_Tc` \ ty2' ->
463 returnNF_Tc (err ty1' ty2')
468 text "Expected" <+> text s <> colon <+> ppr tidy_ty1,
469 text "Inferred" <+> text s <> colon <+> ppr tidy_ty2
472 (env1, [tidy_ty1,tidy_ty2]) = tidyOpenTypes tidy_env [ty1,ty2]
474 unifyKindCtxt swapped tv1 ty2 tidy_env -- not swapped => tv1 expected, ty2 inferred
475 = returnNF_Tc (env2, ptext SLIT("When matching types") <+>
476 sep [quotes pp_expected, ptext SLIT("and"), quotes pp_actual])
478 (pp_expected, pp_actual) | swapped = (pp2, pp1)
479 | otherwise = (pp1, pp2)
480 (env1, tv1') = tidyTyVar tidy_env tv1
481 (env2, ty2') = tidyOpenType env1 ty2
485 unifyMisMatch ty1 ty2
486 = zonkTcType ty1 `thenNF_Tc` \ ty1' ->
487 zonkTcType ty2 `thenNF_Tc` \ ty2' ->
489 (env, [tidy_ty1, tidy_ty2]) = tidyOpenTypes emptyTidyEnv [ty1',ty2']
490 msg = hang (ptext SLIT("Couldn't match"))
491 4 (sep [quotes (ppr tidy_ty1),
492 ptext SLIT("against"),
493 quotes (ppr tidy_ty2)])
495 failWithTcM (env, msg)
497 unifyWithSigErr tyvar ty
498 = (env2, hang (ptext SLIT("Cannot unify the type-signature variable") <+> quotes (ppr tidy_tyvar))
499 4 (ptext SLIT("with the type") <+> quotes (ppr tidy_ty)))
501 (env1, tidy_tyvar) = tidyTyVar emptyTidyEnv tyvar
502 (env2, tidy_ty) = tidyOpenType env1 ty
504 unifyOccurCheck tyvar ty
505 = (env2, hang (ptext SLIT("Occurs check: cannot construct the infinite type:"))
506 4 (sep [ppr tidy_tyvar, char '=', ppr tidy_ty]))
508 (env1, tidy_tyvar) = tidyTyVar emptyTidyEnv tyvar
509 (env2, tidy_ty) = tidyOpenType env1 ty