3 -- Matching and unification
4 tcMatchTys, tcMatchTyX, tcMatchPreds, MatchEnv(..),
6 tcUnifyTys, tcUnifyTysX,
8 gadtRefineTys, gadtMatchTys, coreRefineTys,
14 #include "HsVersions.h"
16 import Var ( Var, TyVar, tyVarKind )
19 import Kind ( isSubKind )
20 import Type ( typeKind, tyVarsOfType, tyVarsOfTypes, tyVarsOfTheta,
21 TvSubstEnv, TvSubst(..), substTy, tcEqTypeX )
22 import TypeRep ( Type(..), PredType(..), funTyCon )
23 import Util ( snocView )
24 import ErrUtils ( Message )
30 %************************************************************************
34 %************************************************************************
37 Matching is much tricker than you might think.
39 1. The substitution we generate binds the *template type variables*
40 which are given to us explicitly.
42 2. We want to match in the presence of foralls;
43 e.g (forall a. t1) ~ (forall b. t2)
45 That is what the RnEnv2 is for; it does the alpha-renaming
46 that makes it as if a and b were the same variable.
47 Initialising the RnEnv2, so that it can generate a fresh
48 binder when necessary, entails knowing the free variables of
51 3. We must be careful not to bind a template type variable to a
52 locally bound variable. E.g.
53 (forall a. x) ~ (forall b. b)
54 where x is the template type variable. Then we do not want to
55 bind x to a/b! This is a kind of occurs check.
56 The necessary locals accumulate in the RnEnv2.
61 = ME { me_tmpls :: VarSet -- Template tyvars
62 , me_env :: RnEnv2 -- Renaming envt for nested foralls
63 } -- In-scope set includes template tyvars
65 tcMatchTys :: TyVarSet -- Template tyvars
68 -> Maybe TvSubstEnv -- One-shot; in principle the template
69 -- variables could be free in the target
71 tcMatchTys tmpls tys1 tys2
72 = match_tys (ME { me_tmpls = tmpls, me_env = mkRnEnv2 in_scope_tyvars})
76 in_scope_tyvars = mkInScopeSet (tmpls `unionVarSet` tyVarsOfTypes tys2)
77 -- We're assuming that all the interesting
78 -- tyvars in tys1 are in tmpls
81 :: [TyVar] -- Bind these
82 -> [PredType] -> [PredType]
84 tcMatchPreds tmpls ps1 ps2
85 = match_list (match_pred menv) emptyTvSubstEnv ps1 ps2
87 menv = ME { me_tmpls = mkVarSet tmpls, me_env = mkRnEnv2 in_scope_tyvars }
88 in_scope_tyvars = mkInScopeSet (tyVarsOfTheta ps1 `unionVarSet` tyVarsOfTheta ps2)
90 tcMatchTyX :: MatchEnv
91 -> TvSubstEnv -- Substitution to extend
96 tcMatchTyX menv subst ty1 ty2 = match menv subst ty1 ty2 -- Rename for export
99 Now the internals of matching
102 match :: MatchEnv -- For the most part this is pushed downwards
103 -> TvSubstEnv -- Substitution so far:
104 -- Domain is subset of template tyvars
105 -- Free vars of range is subset of
106 -- in-scope set of the RnEnv2
107 -> Type -> Type -- Template and target respectively
109 -- This matcher works on source types; that is,
110 -- it respects NewTypes and PredType
112 match menv subst (NoteTy _ ty1) ty2 = match menv subst ty1 ty2
113 match menv subst ty1 (NoteTy _ ty2) = match menv subst ty1 ty2
115 match menv subst (TyVarTy tv1) ty2
116 | tv1 `elemVarSet` me_tmpls menv
117 = case lookupVarEnv subst tv1' of
118 Nothing | any (inRnEnvR rn_env) (varSetElems (tyVarsOfType ty2))
119 -> Nothing -- Occurs check
120 | not (typeKind ty2 `isSubKind` tyVarKind tv1)
121 -> Nothing -- Kind mis-match
123 -> Just (extendVarEnv subst tv1 ty2)
125 Just ty1' | tcEqTypeX (nukeRnEnvL rn_env) ty1' ty2
126 -- ty1 has no locally-bound variables, hence nukeRnEnvL
127 -- Note tcEqType...we are doing source-type matching here
132 | otherwise -- tv1 is not a template tyvar
134 TyVarTy tv2 | tv1' == rnOccR rn_env tv2 -> Just subst
138 tv1' = rnOccL rn_env tv1
140 match menv subst (ForAllTy tv1 ty1) (ForAllTy tv2 ty2)
141 = match menv' subst ty1 ty2
142 where -- Use the magic of rnBndr2 to go under the binders
143 menv' = menv { me_env = rnBndr2 (me_env menv) tv1 tv2 }
145 match menv subst (PredTy p1) (PredTy p2)
146 = match_pred menv subst p1 p2
147 match menv subst (TyConApp tc1 tys1) (TyConApp tc2 tys2)
148 | tc1 == tc2 = match_tys menv subst tys1 tys2
149 match menv subst (FunTy ty1a ty1b) (FunTy ty2a ty2b)
150 = do { subst' <- match menv subst ty1a ty2a
151 ; match menv subst' ty1b ty2b }
152 match menv subst (AppTy ty1a ty1b) ty2
153 | Just (ty2a, ty2b) <- repSplitAppTy_maybe ty2
154 = do { subst' <- match menv subst ty1a ty2a
155 ; match menv subst' ty1b ty2b }
157 match menv subst ty1 ty2
161 match_tys menv subst tys1 tys2 = match_list (match menv) subst tys1 tys2
164 match_list :: (TvSubstEnv -> a -> a -> Maybe TvSubstEnv)
165 -> TvSubstEnv -> [a] -> [a] -> Maybe TvSubstEnv
166 match_list fn subst [] [] = Just subst
167 match_list fn subst (ty1:tys1) (ty2:tys2) = do { subst' <- fn subst ty1 ty2
168 ; match_list fn subst' tys1 tys2 }
169 match_list fn subst tys1 tys2 = Nothing
172 match_pred menv subst (ClassP c1 tys1) (ClassP c2 tys2)
173 | c1 == c2 = match_tys menv subst tys1 tys2
174 match_pred menv subst (IParam n1 t1) (IParam n2 t2)
175 | n1 == n2 = match menv subst t1 t2
176 match_pred menv subst p1 p2 = Nothing
180 %************************************************************************
184 %************************************************************************
187 gadtRefineTys, gadtMatchTys
188 :: [TyVar] -- Try to unify these
189 -> TvSubstEnv -- Not idempotent
191 -> MaybeErr Message TvSubstEnv -- Not idempotent
192 -- This one is used by the type checker. Neither the input nor result
193 -- substitition is idempotent
194 gadtRefineTys ex_tvs subst tys1 tys2
195 = initUM (tryToBind (mkVarSet ex_tvs)) (unify_tys subst tys1 tys2)
197 gadtMatchTys ex_tvs subst tys1 tys2
198 = initUM (bindOnly (mkVarSet ex_tvs)) (unify_tys subst tys1 tys2)
200 ----------------------------
201 coreRefineTys :: [TyVar] -- Try to unify these
202 -> TvSubst -- A full-blown apply-once substitition
203 -> Type -- Both types should be a fixed point
204 -> Type -- of the incoming substitution
205 -> Maybe TvSubstEnv -- In-scope set is unaffected
206 -- Used by Core Lint and the simplifier. Takes a full apply-once substitution.
207 -- The incoming substitution's in-scope set should mention all the variables free
208 -- in the incoming types
209 coreRefineTys ex_tvs subst@(TvSubst in_scope orig_env) ty1 ty2
210 = maybeErrToMaybe $ initUM (tryToBind (mkVarSet ex_tvs)) $
211 do { -- Run the unifier, starting with an empty env
212 ; extra_env <- unify emptyTvSubstEnv ty1 ty2
214 -- Find the fixed point of the resulting non-idempotent
215 -- substitution, and apply it to the incoming substitution
216 ; let extra_subst = TvSubst in_scope extra_env_fixpt
217 extra_env_fixpt = mapVarEnv (substTy extra_subst) extra_env
218 orig_env' = mapVarEnv (substTy extra_subst) orig_env
219 ; return (orig_env' `plusVarEnv` extra_env_fixpt) }
221 ----------------------------
222 tcUnifyTys :: TyVarSet -> [Type] -> [Type] -> Maybe TvSubstEnv
223 tcUnifyTys bind_these tys1 tys2
224 = maybeErrToMaybe $ initUM (bindOnly bind_these) $
225 unify_tys emptyTvSubstEnv tys1 tys2
227 tcUnifyTysX :: TyVarSet -> TvSubstEnv -> [Type] -> [Type] -> Maybe TvSubstEnv
228 tcUnifyTysX bind_these subst tys1 tys2
229 = maybeErrToMaybe $ initUM (bindOnly bind_these) $
230 unify_tys subst tys1 tys2
232 ----------------------------
233 tryToBind, bindOnly :: TyVarSet -> TyVar -> BindFlag
234 tryToBind tv_set tv | tv `elemVarSet` tv_set = BindMe
235 | otherwise = AvoidMe
237 bindOnly tv_set tv | tv `elemVarSet` tv_set = BindMe
238 | otherwise = DontBindMe
240 emptyTvSubstEnv :: TvSubstEnv
241 emptyTvSubstEnv = emptyVarEnv
245 %************************************************************************
249 %************************************************************************
252 unify :: TvSubstEnv -- An existing substitution to extend
253 -> Type -> Type -- Types to be unified
254 -> UM TvSubstEnv -- Just the extended substitution,
255 -- Nothing if unification failed
256 -- We do not require the incoming substitution to be idempotent,
257 -- nor guarantee that the outgoing one is. That's fixed up by
260 -- Respects newtypes, PredTypes
262 unify subst ty1 ty2 = -- pprTrace "unify" (ppr subst <+> pprParendType ty1 <+> pprParendType ty2) $
265 -- in unify_, any NewTcApps/Preds should be taken at face value
266 unify_ subst (TyVarTy tv1) ty2 = uVar False subst tv1 ty2
267 unify_ subst ty1 (TyVarTy tv2) = uVar True subst tv2 ty1
269 unify_ subst (NoteTy _ ty1) ty2 = unify subst ty1 ty2
270 unify_ subst ty1 (NoteTy _ ty2) = unify subst ty1 ty2
272 unify_ subst (PredTy p1) (PredTy p2) = unify_pred subst p1 p2
274 unify_ subst t1@(TyConApp tyc1 tys1) t2@(TyConApp tyc2 tys2)
275 | tyc1 == tyc2 = unify_tys subst tys1 tys2
277 unify_ subst (FunTy ty1a ty1b) (FunTy ty2a ty2b)
278 = do { subst' <- unify subst ty1a ty2a
279 ; unify subst' ty1b ty2b }
281 -- Applications need a bit of care!
282 -- They can match FunTy and TyConApp, so use splitAppTy_maybe
283 -- NB: we've already dealt with type variables and Notes,
284 -- so if one type is an App the other one jolly well better be too
285 unify_ subst (AppTy ty1a ty1b) ty2
286 | Just (ty2a, ty2b) <- repSplitAppTy_maybe ty2
287 = do { subst' <- unify subst ty1a ty2a
288 ; unify subst' ty1b ty2b }
290 unify_ subst ty1 (AppTy ty2a ty2b)
291 | Just (ty1a, ty1b) <- repSplitAppTy_maybe ty1
292 = do { subst' <- unify subst ty1a ty2a
293 ; unify subst' ty1b ty2b }
295 unify_ subst ty1 ty2 = failWith (misMatch ty1 ty2)
297 ------------------------------
298 unify_pred subst (ClassP c1 tys1) (ClassP c2 tys2)
299 | c1 == c2 = unify_tys subst tys1 tys2
300 unify_pred subst (IParam n1 t1) (IParam n2 t2)
301 | n1 == n2 = unify subst t1 t2
302 unify_pred subst p1 p2 = failWith (misMatch (PredTy p1) (PredTy p2))
304 ------------------------------
305 unify_tys = unifyList unify
307 unifyList :: Outputable a
308 => (TvSubstEnv -> a -> a -> UM TvSubstEnv)
309 -> TvSubstEnv -> [a] -> [a] -> UM TvSubstEnv
310 unifyList unifier subst orig_xs orig_ys
311 = go subst orig_xs orig_ys
313 go subst [] [] = return subst
314 go subst (x:xs) (y:ys) = do { subst' <- unifier subst x y
316 go subst _ _ = failWith (lengthMisMatch orig_xs orig_ys)
318 ------------------------------
319 uVar :: Bool -- Swapped
320 -> TvSubstEnv -- An existing substitution to extend
321 -> TyVar -- Type variable to be unified
322 -> Type -- with this type
325 uVar swap subst tv1 ty
326 = -- check to see whether tv1 is refined
327 case (lookupVarEnv subst tv1) of
328 -- yes, call back into unify'
329 Just ty' | swap -> unify subst ty ty'
330 | otherwise -> unify subst ty' ty
332 Nothing -> uUnrefined subst tv1 ty
335 uUnrefined :: TvSubstEnv -- An existing substitution to extend
336 -> TyVar -- Type variable to be unified
337 -> Type -- with this type
340 -- We know that tv1 isn't refined
341 uUnrefined subst tv1 ty2@(TyVarTy tv2)
342 | tv1 == tv2 -- Same, do nothing
345 -- Check to see whether tv2 is refined
346 | Just ty' <- lookupVarEnv subst tv2
347 = uUnrefined subst tv1 ty'
349 -- So both are unrefined; next, see if the kinds force the direction
350 | k1 == k2 -- Can update either; so check the bind-flags
351 = do { b1 <- tvBindFlag tv1
352 ; b2 <- tvBindFlag tv2
354 (DontBindMe, DontBindMe) -> failWith (misMatch ty1 ty2)
355 (DontBindMe, _) -> bindTv subst tv2 ty1
356 (BindMe, _) -> bindTv subst tv1 ty2
357 (AvoidMe, BindMe) -> bindTv subst tv2 ty1
358 (AvoidMe, _) -> bindTv subst tv1 ty2
361 | k1 `isSubKind` k2 -- Must update tv2
362 = do { b2 <- tvBindFlag tv2
364 DontBindMe -> failWith (misMatch ty1 ty2)
365 other -> bindTv subst tv2 ty1
368 | k2 `isSubKind` k1 -- Must update tv1
369 = do { b1 <- tvBindFlag tv1
371 DontBindMe -> failWith (misMatch ty1 ty2)
372 other -> bindTv subst tv1 ty2
375 | otherwise = failWith (kindMisMatch tv1 ty2)
381 uUnrefined subst tv1 ty2 -- ty2 is not a type variable
382 -- Do occurs check...
383 | tv1 `elemVarSet` substTvSet subst (tyVarsOfType ty2)
384 = failWith (occursCheck tv1 ty2)
385 -- And a kind check...
387 = do { b1 <- tvBindFlag tv1
388 ; case b1 of -- And check that tv1 is bindable
389 DontBindMe -> failWith (misMatch ty1 ty2)
390 other -> bindTv subst tv1 ty2
393 = pprTrace "kind" (ppr tv1 <+> ppr k1 $$ ppr ty2 <+> ppr k2) $
394 failWith (kindMisMatch tv1 ty2)
400 substTvSet :: TvSubstEnv -> TyVarSet -> TyVarSet
401 -- Apply the non-idempotent substitution to a set of type variables,
402 -- remembering that the substitution isn't necessarily idempotent
404 = foldVarSet (unionVarSet . get) emptyVarSet tvs
406 get tv = case lookupVarEnv subst tv of
407 Nothing -> unitVarSet tv
408 Just ty -> substTvSet subst (tyVarsOfType ty)
410 bindTv subst tv ty = return (extendVarEnv subst tv ty)
413 %************************************************************************
417 %************************************************************************
420 data BindFlag = BindMe | AvoidMe | DontBindMe
422 newtype UM a = UM { unUM :: (TyVar -> BindFlag)
423 -> MaybeErr Message a }
425 instance Monad UM where
426 return a = UM (\tvs -> Succeeded a)
427 fail s = UM (\tvs -> Failed (text s))
428 m >>= k = UM (\tvs -> case unUM m tvs of
429 Failed err -> Failed err
430 Succeeded v -> unUM (k v) tvs)
432 initUM :: (TyVar -> BindFlag) -> UM a -> MaybeErr Message a
433 initUM badtvs um = unUM um badtvs
435 tvBindFlag :: TyVar -> UM BindFlag
436 tvBindFlag tv = UM (\tv_fn -> Succeeded (tv_fn tv))
438 failWith :: Message -> UM a
439 failWith msg = UM (\tv_fn -> Failed msg)
441 maybeErrToMaybe :: MaybeErr fail succ -> Maybe succ
442 maybeErrToMaybe (Succeeded a) = Just a
443 maybeErrToMaybe (Failed m) = Nothing
445 ------------------------------
446 repSplitAppTy_maybe :: Type -> Maybe (Type,Type)
447 -- Like Type.splitAppTy_maybe, but any coreView stuff is already done
448 repSplitAppTy_maybe (FunTy ty1 ty2) = Just (TyConApp funTyCon [ty1], ty2)
449 repSplitAppTy_maybe (AppTy ty1 ty2) = Just (ty1, ty2)
450 repSplitAppTy_maybe (TyConApp tc tys) = case snocView tys of
451 Just (tys', ty') -> Just (TyConApp tc tys', ty')
453 repSplitAppTy_maybe other = Nothing
457 %************************************************************************
460 We go to a lot more trouble to tidy the types
461 in TcUnify. Maybe we'll end up having to do that
462 here too, but I'll leave it for now.
464 %************************************************************************
468 = ptext SLIT("Can't match types") <+> quotes (ppr t1) <+>
469 ptext SLIT("and") <+> quotes (ppr t2)
471 lengthMisMatch tys1 tys2
472 = sep [ptext SLIT("Can't match unequal length lists"),
473 nest 2 (ppr tys1), nest 2 (ppr tys2) ]
476 = vcat [ptext SLIT("Can't match kinds") <+> quotes (ppr (tyVarKind tv1)) <+>
477 ptext SLIT("and") <+> quotes (ppr (typeKind t2)),
478 ptext SLIT("when matching") <+> quotes (ppr tv1) <+>
479 ptext SLIT("with") <+> quotes (ppr t2)]
482 = hang (ptext SLIT("Can't construct the infinite type"))
483 2 (ppr tv <+> equals <+> ppr ty)