3 -- Matching and unification
4 tcMatchTys, tcMatchTyX, tcMatchPreds, MatchEnv(..),
8 gadtRefineTys, BindFlag(..),
16 #include "HsVersions.h"
18 import Var ( Var, TyVar, tyVarKind )
21 import Kind ( isSubKind )
22 import Type ( typeKind, tyVarsOfType, tyVarsOfTypes, tyVarsOfTheta,
23 TvSubstEnv, emptyTvSubstEnv, TvSubst(..), substTy, tcEqTypeX )
24 import TypeRep ( Type(..), PredType(..), funTyCon )
25 import Util ( snocView )
26 import ErrUtils ( Message )
32 %************************************************************************
36 %************************************************************************
39 Matching is much tricker than you might think.
41 1. The substitution we generate binds the *template type variables*
42 which are given to us explicitly.
44 2. We want to match in the presence of foralls;
45 e.g (forall a. t1) ~ (forall b. t2)
47 That is what the RnEnv2 is for; it does the alpha-renaming
48 that makes it as if a and b were the same variable.
49 Initialising the RnEnv2, so that it can generate a fresh
50 binder when necessary, entails knowing the free variables of
53 3. We must be careful not to bind a template type variable to a
54 locally bound variable. E.g.
55 (forall a. x) ~ (forall b. b)
56 where x is the template type variable. Then we do not want to
57 bind x to a/b! This is a kind of occurs check.
58 The necessary locals accumulate in the RnEnv2.
63 = ME { me_tmpls :: VarSet -- Template tyvars
64 , me_env :: RnEnv2 -- Renaming envt for nested foralls
65 } -- In-scope set includes template tyvars
67 tcMatchTys :: TyVarSet -- Template tyvars
70 -> Maybe TvSubst -- One-shot; in principle the template
71 -- variables could be free in the target
73 tcMatchTys tmpls tys1 tys2
74 = case match_tys menv emptyTvSubstEnv tys1 tys2 of
75 Just subst_env -> Just (TvSubst in_scope subst_env)
78 menv = ME { me_tmpls = tmpls, me_env = mkRnEnv2 in_scope }
79 in_scope = mkInScopeSet (tmpls `unionVarSet` tyVarsOfTypes tys2)
80 -- We're assuming that all the interesting
81 -- tyvars in tys1 are in tmpls
84 :: [TyVar] -- Bind these
85 -> [PredType] -> [PredType]
87 tcMatchPreds tmpls ps1 ps2
88 = match_list (match_pred menv) emptyTvSubstEnv ps1 ps2
90 menv = ME { me_tmpls = mkVarSet tmpls, me_env = mkRnEnv2 in_scope_tyvars }
91 in_scope_tyvars = mkInScopeSet (tyVarsOfTheta ps1 `unionVarSet` tyVarsOfTheta ps2)
93 -- This one is called from the expression matcher, which already has a MatchEnv in hand
94 tcMatchTyX :: MatchEnv
95 -> TvSubstEnv -- Substitution to extend
100 tcMatchTyX menv subst ty1 ty2 = match menv subst ty1 ty2 -- Rename for export
103 Now the internals of matching
106 match :: MatchEnv -- For the most part this is pushed downwards
107 -> TvSubstEnv -- Substitution so far:
108 -- Domain is subset of template tyvars
109 -- Free vars of range is subset of
110 -- in-scope set of the RnEnv2
111 -> Type -> Type -- Template and target respectively
113 -- This matcher works on source types; that is,
114 -- it respects NewTypes and PredType
116 match menv subst (NoteTy _ ty1) ty2 = match menv subst ty1 ty2
117 match menv subst ty1 (NoteTy _ ty2) = match menv subst ty1 ty2
119 match menv subst (TyVarTy tv1) ty2
120 | tv1 `elemVarSet` me_tmpls menv
121 = case lookupVarEnv subst tv1' of
122 Nothing | any (inRnEnvR rn_env) (varSetElems (tyVarsOfType ty2))
123 -> Nothing -- Occurs check
124 | not (typeKind ty2 `isSubKind` tyVarKind tv1)
125 -> Nothing -- Kind mis-match
127 -> Just (extendVarEnv subst tv1 ty2)
129 Just ty1' | tcEqTypeX (nukeRnEnvL rn_env) ty1' ty2
130 -- ty1 has no locally-bound variables, hence nukeRnEnvL
131 -- Note tcEqType...we are doing source-type matching here
136 | otherwise -- tv1 is not a template tyvar
138 TyVarTy tv2 | tv1' == rnOccR rn_env tv2 -> Just subst
142 tv1' = rnOccL rn_env tv1
144 match menv subst (ForAllTy tv1 ty1) (ForAllTy tv2 ty2)
145 = match menv' subst ty1 ty2
146 where -- Use the magic of rnBndr2 to go under the binders
147 menv' = menv { me_env = rnBndr2 (me_env menv) tv1 tv2 }
149 match menv subst (PredTy p1) (PredTy p2)
150 = match_pred menv subst p1 p2
151 match menv subst (TyConApp tc1 tys1) (TyConApp tc2 tys2)
152 | tc1 == tc2 = match_tys menv subst tys1 tys2
153 match menv subst (FunTy ty1a ty1b) (FunTy ty2a ty2b)
154 = do { subst' <- match menv subst ty1a ty2a
155 ; match menv subst' ty1b ty2b }
156 match menv subst (AppTy ty1a ty1b) ty2
157 | Just (ty2a, ty2b) <- repSplitAppTy_maybe ty2
158 = do { subst' <- match menv subst ty1a ty2a
159 ; match menv subst' ty1b ty2b }
161 match menv subst ty1 ty2
165 match_tys menv subst tys1 tys2 = match_list (match menv) subst tys1 tys2
168 match_list :: (TvSubstEnv -> a -> a -> Maybe TvSubstEnv)
169 -> TvSubstEnv -> [a] -> [a] -> Maybe TvSubstEnv
170 match_list fn subst [] [] = Just subst
171 match_list fn subst (ty1:tys1) (ty2:tys2) = do { subst' <- fn subst ty1 ty2
172 ; match_list fn subst' tys1 tys2 }
173 match_list fn subst tys1 tys2 = Nothing
176 match_pred menv subst (ClassP c1 tys1) (ClassP c2 tys2)
177 | c1 == c2 = match_tys menv subst tys1 tys2
178 match_pred menv subst (IParam n1 t1) (IParam n2 t2)
179 | n1 == n2 = match menv subst t1 t2
180 match_pred menv subst p1 p2 = Nothing
184 %************************************************************************
188 %************************************************************************
191 tcUnifyTys :: (TyVar -> BindFlag)
193 -> Maybe TvSubst -- A regular one-shot substitution
194 -- The two types may have common type variables, and indeed do so in the
195 -- second call to tcUnifyTys in FunDeps.checkClsFD
196 tcUnifyTys bind_fn tys1 tys2
197 = maybeErrToMaybe $ initUM bind_fn $
198 do { subst_env <- unify_tys emptyTvSubstEnv tys1 tys2
200 -- Find the fixed point of the resulting non-idempotent substitution
201 ; let in_scope = mkInScopeSet (tvs1 `unionVarSet` tvs2)
202 subst = TvSubst in_scope subst_env_fixpt
203 subst_env_fixpt = mapVarEnv (substTy subst) subst_env
206 tvs1 = tyVarsOfTypes tys1
207 tvs2 = tyVarsOfTypes tys2
209 ----------------------------
210 coreRefineTys :: InScopeSet -- Superset of free vars of either type
211 -> [TyVar] -- Try to unify these
212 -> Type -- Both types should be a fixed point
213 -> Type -- of the incoming substitution
214 -> Maybe TvSubstEnv -- In-scope set is unaffected
215 -- Used by Core Lint and the simplifier. Takes a full apply-once substitution.
216 -- The incoming substitution's in-scope set should mention all the variables free
217 -- in the incoming types
218 coreRefineTys in_scope ex_tvs ty1 ty2
219 = maybeErrToMaybe $ initUM (tryToBind (mkVarSet ex_tvs)) $
220 do { -- Run the unifier, starting with an empty env
221 ; subst_env <- unify emptyTvSubstEnv ty1 ty2
223 -- Find the fixed point of the resulting non-idempotent substitution
224 ; let subst = TvSubst in_scope subst_env_fixpt
225 subst_env_fixpt = mapVarEnv (substTy subst) subst_env
226 ; return subst_env_fixpt }
228 ----------------------------
230 :: (TyVar -> BindFlag) -- Try to unify these
231 -> TvSubstEnv -- Not idempotent
233 -> MaybeErr Message TvSubstEnv -- Not idempotent
234 -- This one is used by the type checker. Neither the input nor result
235 -- substitition is idempotent
236 gadtRefineTys bind_fn subst tys1 tys2
237 = initUM bind_fn (unify_tys subst tys1 tys2)
239 ----------------------------
240 tryToBind :: TyVarSet -> TyVar -> BindFlag
241 tryToBind tv_set tv | tv `elemVarSet` tv_set = BindMe
242 | otherwise = AvoidMe
246 %************************************************************************
250 %************************************************************************
253 unify :: TvSubstEnv -- An existing substitution to extend
254 -> Type -> Type -- Types to be unified
255 -> UM TvSubstEnv -- Just the extended substitution,
256 -- Nothing if unification failed
257 -- We do not require the incoming substitution to be idempotent,
258 -- nor guarantee that the outgoing one is. That's fixed up by
261 -- Respects newtypes, PredTypes
263 unify subst ty1 ty2 = -- pprTrace "unify" (ppr subst <+> pprParendType ty1 <+> pprParendType ty2) $
266 -- in unify_, any NewTcApps/Preds should be taken at face value
267 unify_ subst (TyVarTy tv1) ty2 = uVar False subst tv1 ty2
268 unify_ subst ty1 (TyVarTy tv2) = uVar True subst tv2 ty1
270 unify_ subst (NoteTy _ ty1) ty2 = unify subst ty1 ty2
271 unify_ subst ty1 (NoteTy _ ty2) = unify subst ty1 ty2
273 unify_ subst (PredTy p1) (PredTy p2) = unify_pred subst p1 p2
275 unify_ subst t1@(TyConApp tyc1 tys1) t2@(TyConApp tyc2 tys2)
276 | tyc1 == tyc2 = unify_tys subst tys1 tys2
278 unify_ subst (FunTy ty1a ty1b) (FunTy ty2a ty2b)
279 = do { subst' <- unify subst ty1a ty2a
280 ; unify subst' ty1b ty2b }
282 -- Applications need a bit of care!
283 -- They can match FunTy and TyConApp, so use splitAppTy_maybe
284 -- NB: we've already dealt with type variables and Notes,
285 -- so if one type is an App the other one jolly well better be too
286 unify_ subst (AppTy ty1a ty1b) ty2
287 | Just (ty2a, ty2b) <- repSplitAppTy_maybe ty2
288 = do { subst' <- unify subst ty1a ty2a
289 ; unify subst' ty1b ty2b }
291 unify_ subst ty1 (AppTy ty2a ty2b)
292 | Just (ty1a, ty1b) <- repSplitAppTy_maybe ty1
293 = do { subst' <- unify subst ty1a ty2a
294 ; unify subst' ty1b ty2b }
296 unify_ subst ty1 ty2 = failWith (misMatch ty1 ty2)
298 ------------------------------
299 unify_pred subst (ClassP c1 tys1) (ClassP c2 tys2)
300 | c1 == c2 = unify_tys subst tys1 tys2
301 unify_pred subst (IParam n1 t1) (IParam n2 t2)
302 | n1 == n2 = unify subst t1 t2
303 unify_pred subst p1 p2 = failWith (misMatch (PredTy p1) (PredTy p2))
305 ------------------------------
306 unify_tys = unifyList unify
308 unifyList :: Outputable a
309 => (TvSubstEnv -> a -> a -> UM TvSubstEnv)
310 -> TvSubstEnv -> [a] -> [a] -> UM TvSubstEnv
311 unifyList unifier subst orig_xs orig_ys
312 = go subst orig_xs orig_ys
314 go subst [] [] = return subst
315 go subst (x:xs) (y:ys) = do { subst' <- unifier subst x y
317 go subst _ _ = failWith (lengthMisMatch orig_xs orig_ys)
319 ------------------------------
320 uVar :: Bool -- Swapped
321 -> TvSubstEnv -- An existing substitution to extend
322 -> TyVar -- Type variable to be unified
323 -> Type -- with this type
326 uVar swap subst tv1 ty
327 = -- Check to see whether tv1 is refined by the substitution
328 case (lookupVarEnv subst tv1) of
329 -- Yes, call back into unify'
330 Just ty' | swap -> unify subst ty ty'
331 | otherwise -> unify subst ty' ty
333 Nothing -> uUnrefined subst tv1 ty
336 uUnrefined :: TvSubstEnv -- An existing substitution to extend
337 -> TyVar -- Type variable to be unified
338 -> Type -- with this type
341 -- We know that tv1 isn't refined
342 uUnrefined subst tv1 ty2@(TyVarTy tv2)
343 | tv1 == tv2 -- Same, do nothing
346 -- Check to see whether tv2 is refined
347 | Just ty' <- lookupVarEnv subst tv2
348 = uUnrefined subst tv1 ty'
350 -- So both are unrefined; next, see if the kinds force the direction
351 | k1 == k2 -- Can update either; so check the bind-flags
352 = do { b1 <- tvBindFlag tv1
353 ; b2 <- tvBindFlag tv2
355 (BindMe, _) -> bind tv1 ty2
357 (AvoidMe, BindMe) -> bind tv2 ty1
358 (AvoidMe, _) -> bind tv1 ty2
360 (WildCard, WildCard) -> return subst
361 (WildCard, Skolem) -> return subst
362 (WildCard, _) -> bind tv2 ty1
364 (Skolem, WildCard) -> return subst
365 (Skolem, Skolem) -> failWith (misMatch ty1 ty2)
366 (Skolem, _) -> bind tv2 ty1
369 | k1 `isSubKind` k2 = bindTv subst tv2 ty1 -- Must update tv2
370 | k2 `isSubKind` k1 = bindTv subst tv1 ty2 -- Must update tv1
372 | otherwise = failWith (kindMisMatch tv1 ty2)
377 bind tv ty = return (extendVarEnv subst tv ty)
379 uUnrefined subst tv1 ty2 -- ty2 is not a type variable
380 | tv1 `elemVarSet` substTvSet subst (tyVarsOfType ty2)
381 = failWith (occursCheck tv1 ty2) -- Occurs check
382 | not (k2 `isSubKind` k1)
383 = failWith (kindMisMatch tv1 ty2) -- Kind check
385 = bindTv subst tv1 ty2
390 substTvSet :: TvSubstEnv -> TyVarSet -> TyVarSet
391 -- Apply the non-idempotent substitution to a set of type variables,
392 -- remembering that the substitution isn't necessarily idempotent
394 = foldVarSet (unionVarSet . get) emptyVarSet tvs
396 get tv = case lookupVarEnv subst tv of
397 Nothing -> unitVarSet tv
398 Just ty -> substTvSet subst (tyVarsOfType ty)
400 bindTv subst tv ty -- ty is not a type variable
401 = do { b <- tvBindFlag tv
403 Skolem -> failWith (misMatch (TyVarTy tv) ty)
404 WildCard -> return subst
405 other -> return (extendVarEnv subst tv ty)
409 %************************************************************************
413 %************************************************************************
417 = BindMe -- A regular type variable
418 | AvoidMe -- Like BindMe but, given the choice, avoid binding it
420 | Skolem -- This type variable is a skolem constant
421 -- Don't bind it; it only matches itself
423 | WildCard -- This type variable matches anything,
424 -- and does not affect the substitution
426 newtype UM a = UM { unUM :: (TyVar -> BindFlag)
427 -> MaybeErr Message a }
429 instance Monad UM where
430 return a = UM (\tvs -> Succeeded a)
431 fail s = UM (\tvs -> Failed (text s))
432 m >>= k = UM (\tvs -> case unUM m tvs of
433 Failed err -> Failed err
434 Succeeded v -> unUM (k v) tvs)
436 initUM :: (TyVar -> BindFlag) -> UM a -> MaybeErr Message a
437 initUM badtvs um = unUM um badtvs
439 tvBindFlag :: TyVar -> UM BindFlag
440 tvBindFlag tv = UM (\tv_fn -> Succeeded (tv_fn tv))
442 failWith :: Message -> UM a
443 failWith msg = UM (\tv_fn -> Failed msg)
445 maybeErrToMaybe :: MaybeErr fail succ -> Maybe succ
446 maybeErrToMaybe (Succeeded a) = Just a
447 maybeErrToMaybe (Failed m) = Nothing
449 ------------------------------
450 repSplitAppTy_maybe :: Type -> Maybe (Type,Type)
451 -- Like Type.splitAppTy_maybe, but any coreView stuff is already done
452 repSplitAppTy_maybe (FunTy ty1 ty2) = Just (TyConApp funTyCon [ty1], ty2)
453 repSplitAppTy_maybe (AppTy ty1 ty2) = Just (ty1, ty2)
454 repSplitAppTy_maybe (TyConApp tc tys) = case snocView tys of
455 Just (tys', ty') -> Just (TyConApp tc tys', ty')
457 repSplitAppTy_maybe other = Nothing
461 %************************************************************************
464 We go to a lot more trouble to tidy the types
465 in TcUnify. Maybe we'll end up having to do that
466 here too, but I'll leave it for now.
468 %************************************************************************
472 = ptext SLIT("Can't match types") <+> quotes (ppr t1) <+>
473 ptext SLIT("and") <+> quotes (ppr t2)
475 lengthMisMatch tys1 tys2
476 = sep [ptext SLIT("Can't match unequal length lists"),
477 nest 2 (ppr tys1), nest 2 (ppr tys2) ]
480 = vcat [ptext SLIT("Can't match kinds") <+> quotes (ppr (tyVarKind tv1)) <+>
481 ptext SLIT("and") <+> quotes (ppr (typeKind t2)),
482 ptext SLIT("when matching") <+> quotes (ppr tv1) <+>
483 ptext SLIT("with") <+> quotes (ppr t2)]
486 = hang (ptext SLIT("Can't construct the infinite type"))
487 2 (ppr tv <+> equals <+> ppr ty)