3 -- Matching and unification
4 tcMatchTys, tcMatchTyX, tcMatchPreds, MatchEnv(..),
8 gadtRefineTys, BindFlag(..),
10 coreRefineTys, TypeRefinement,
16 #include "HsVersions.h"
18 import Var ( Var, TyVar, tyVarKind )
21 import Kind ( isSubKind )
22 import Type ( typeKind, tyVarsOfType, tyVarsOfTypes, tyVarsOfTheta, mkTyVarTys,
23 TvSubstEnv, emptyTvSubstEnv, TvSubst(..), substTy, tcEqTypeX )
24 import TypeRep ( Type(..), PredType(..), funTyCon )
25 import DataCon ( DataCon, dataConResTy )
26 import Util ( snocView )
27 import ErrUtils ( Message )
33 %************************************************************************
37 %************************************************************************
40 Matching is much tricker than you might think.
42 1. The substitution we generate binds the *template type variables*
43 which are given to us explicitly.
45 2. We want to match in the presence of foralls;
46 e.g (forall a. t1) ~ (forall b. t2)
48 That is what the RnEnv2 is for; it does the alpha-renaming
49 that makes it as if a and b were the same variable.
50 Initialising the RnEnv2, so that it can generate a fresh
51 binder when necessary, entails knowing the free variables of
54 3. We must be careful not to bind a template type variable to a
55 locally bound variable. E.g.
56 (forall a. x) ~ (forall b. b)
57 where x is the template type variable. Then we do not want to
58 bind x to a/b! This is a kind of occurs check.
59 The necessary locals accumulate in the RnEnv2.
64 = ME { me_tmpls :: VarSet -- Template tyvars
65 , me_env :: RnEnv2 -- Renaming envt for nested foralls
66 } -- In-scope set includes template tyvars
68 tcMatchTys :: TyVarSet -- Template tyvars
71 -> Maybe TvSubst -- One-shot; in principle the template
72 -- variables could be free in the target
74 tcMatchTys tmpls tys1 tys2
75 = case match_tys menv emptyTvSubstEnv tys1 tys2 of
76 Just subst_env -> Just (TvSubst in_scope subst_env)
79 menv = ME { me_tmpls = tmpls, me_env = mkRnEnv2 in_scope }
80 in_scope = mkInScopeSet (tmpls `unionVarSet` tyVarsOfTypes tys2)
81 -- We're assuming that all the interesting
82 -- tyvars in tys1 are in tmpls
85 :: [TyVar] -- Bind these
86 -> [PredType] -> [PredType]
88 tcMatchPreds tmpls ps1 ps2
89 = match_list (match_pred menv) emptyTvSubstEnv ps1 ps2
91 menv = ME { me_tmpls = mkVarSet tmpls, me_env = mkRnEnv2 in_scope_tyvars }
92 in_scope_tyvars = mkInScopeSet (tyVarsOfTheta ps1 `unionVarSet` tyVarsOfTheta ps2)
94 -- This one is called from the expression matcher, which already has a MatchEnv in hand
95 tcMatchTyX :: MatchEnv
96 -> TvSubstEnv -- Substitution to extend
101 tcMatchTyX menv subst ty1 ty2 = match menv subst ty1 ty2 -- Rename for export
104 Now the internals of matching
107 match :: MatchEnv -- For the most part this is pushed downwards
108 -> TvSubstEnv -- Substitution so far:
109 -- Domain is subset of template tyvars
110 -- Free vars of range is subset of
111 -- in-scope set of the RnEnv2
112 -> Type -> Type -- Template and target respectively
114 -- This matcher works on source types; that is,
115 -- it respects NewTypes and PredType
117 match menv subst (NoteTy _ ty1) ty2 = match menv subst ty1 ty2
118 match menv subst ty1 (NoteTy _ ty2) = match menv subst ty1 ty2
120 match menv subst (TyVarTy tv1) ty2
121 | tv1 `elemVarSet` me_tmpls menv
122 = case lookupVarEnv subst tv1' of
123 Nothing | any (inRnEnvR rn_env) (varSetElems (tyVarsOfType ty2))
124 -> Nothing -- Occurs check
125 | not (typeKind ty2 `isSubKind` tyVarKind tv1)
126 -> Nothing -- Kind mis-match
128 -> Just (extendVarEnv subst tv1 ty2)
130 Just ty1' | tcEqTypeX (nukeRnEnvL rn_env) ty1' ty2
131 -- ty1 has no locally-bound variables, hence nukeRnEnvL
132 -- Note tcEqType...we are doing source-type matching here
137 | otherwise -- tv1 is not a template tyvar
139 TyVarTy tv2 | tv1' == rnOccR rn_env tv2 -> Just subst
143 tv1' = rnOccL rn_env tv1
145 match menv subst (ForAllTy tv1 ty1) (ForAllTy tv2 ty2)
146 = match menv' subst ty1 ty2
147 where -- Use the magic of rnBndr2 to go under the binders
148 menv' = menv { me_env = rnBndr2 (me_env menv) tv1 tv2 }
150 match menv subst (PredTy p1) (PredTy p2)
151 = match_pred menv subst p1 p2
152 match menv subst (TyConApp tc1 tys1) (TyConApp tc2 tys2)
153 | tc1 == tc2 = match_tys menv subst tys1 tys2
154 match menv subst (FunTy ty1a ty1b) (FunTy ty2a ty2b)
155 = do { subst' <- match menv subst ty1a ty2a
156 ; match menv subst' ty1b ty2b }
157 match menv subst (AppTy ty1a ty1b) ty2
158 | Just (ty2a, ty2b) <- repSplitAppTy_maybe ty2
159 = do { subst' <- match menv subst ty1a ty2a
160 ; match menv subst' ty1b ty2b }
162 match menv subst ty1 ty2
166 match_tys menv subst tys1 tys2 = match_list (match menv) subst tys1 tys2
169 match_list :: (TvSubstEnv -> a -> a -> Maybe TvSubstEnv)
170 -> TvSubstEnv -> [a] -> [a] -> Maybe TvSubstEnv
171 match_list fn subst [] [] = Just subst
172 match_list fn subst (ty1:tys1) (ty2:tys2) = do { subst' <- fn subst ty1 ty2
173 ; match_list fn subst' tys1 tys2 }
174 match_list fn subst tys1 tys2 = Nothing
177 match_pred menv subst (ClassP c1 tys1) (ClassP c2 tys2)
178 | c1 == c2 = match_tys menv subst tys1 tys2
179 match_pred menv subst (IParam n1 t1) (IParam n2 t2)
180 | n1 == n2 = match menv subst t1 t2
181 match_pred menv subst p1 p2 = Nothing
185 %************************************************************************
189 %************************************************************************
192 tcUnifyTys :: (TyVar -> BindFlag)
194 -> Maybe TvSubst -- A regular one-shot substitution
195 -- The two types may have common type variables, and indeed do so in the
196 -- second call to tcUnifyTys in FunDeps.checkClsFD
197 tcUnifyTys bind_fn tys1 tys2
198 = maybeErrToMaybe $ initUM bind_fn $
199 do { subst_env <- unify_tys emptyTvSubstEnv tys1 tys2
201 -- Find the fixed point of the resulting non-idempotent substitution
202 ; let in_scope = mkInScopeSet (tvs1 `unionVarSet` tvs2)
203 subst = TvSubst in_scope subst_env_fixpt
204 subst_env_fixpt = mapVarEnv (substTy subst) subst_env
207 tvs1 = tyVarsOfTypes tys1
208 tvs2 = tyVarsOfTypes tys2
210 ----------------------------
211 coreRefineTys :: InScopeSet -- Superset of free vars of either type
212 -> DataCon -> [TyVar] -- Case pattern (con tv1 .. tvn ...)
213 -> Type -- Type of scrutinee
214 -> Maybe TypeRefinement
216 type TypeRefinement = (TvSubstEnv, Bool)
217 -- The Bool is True iff all the bindings in the
218 -- env are for the pattern type variables
219 -- In this case, there is no type refinement
220 -- for already-in-scope type variables
222 -- Used by Core Lint and the simplifier.
223 coreRefineTys in_scope con tvs scrut_ty
224 = maybeErrToMaybe $ initUM (tryToBind tv_set) $
225 do { -- Run the unifier, starting with an empty env
226 ; subst_env <- unify emptyTvSubstEnv pat_res_ty scrut_ty
228 -- Find the fixed point of the resulting non-idempotent substitution
229 ; let subst = TvSubst in_scope subst_env_fixpt
230 subst_env_fixpt = mapVarEnv (substTy subst) subst_env
232 ; return (subst_env_fixpt, all_bound_here subst_env) }
234 pat_res_ty = dataConResTy con (mkTyVarTys tvs)
236 -- 'tvs' are the tyvars bound by the pattern
237 tv_set = mkVarSet tvs
238 all_bound_here env = all bound_here (varEnvKeys env)
239 bound_here uniq = elemVarSetByKey uniq tv_set
242 ----------------------------
244 :: (TyVar -> BindFlag) -- Try to unify these
245 -> TvSubstEnv -- Not idempotent
247 -> MaybeErr Message TvSubstEnv -- Not idempotent
248 -- This one is used by the type checker. Neither the input nor result
249 -- substitition is idempotent
250 gadtRefineTys bind_fn subst tys1 tys2
251 = initUM bind_fn (unify_tys subst tys1 tys2)
253 ----------------------------
254 tryToBind :: TyVarSet -> TyVar -> BindFlag
255 tryToBind tv_set tv | tv `elemVarSet` tv_set = BindMe
256 | otherwise = AvoidMe
260 %************************************************************************
264 %************************************************************************
267 unify :: TvSubstEnv -- An existing substitution to extend
268 -> Type -> Type -- Types to be unified
269 -> UM TvSubstEnv -- Just the extended substitution,
270 -- Nothing if unification failed
271 -- We do not require the incoming substitution to be idempotent,
272 -- nor guarantee that the outgoing one is. That's fixed up by
275 -- Respects newtypes, PredTypes
277 unify subst ty1 ty2 = -- pprTrace "unify" (ppr subst <+> pprParendType ty1 <+> pprParendType ty2) $
280 -- in unify_, any NewTcApps/Preds should be taken at face value
281 unify_ subst (TyVarTy tv1) ty2 = uVar False subst tv1 ty2
282 unify_ subst ty1 (TyVarTy tv2) = uVar True subst tv2 ty1
284 unify_ subst (NoteTy _ ty1) ty2 = unify subst ty1 ty2
285 unify_ subst ty1 (NoteTy _ ty2) = unify subst ty1 ty2
287 unify_ subst (PredTy p1) (PredTy p2) = unify_pred subst p1 p2
289 unify_ subst t1@(TyConApp tyc1 tys1) t2@(TyConApp tyc2 tys2)
290 | tyc1 == tyc2 = unify_tys subst tys1 tys2
292 unify_ subst (FunTy ty1a ty1b) (FunTy ty2a ty2b)
293 = do { subst' <- unify subst ty1a ty2a
294 ; unify subst' ty1b ty2b }
296 -- Applications need a bit of care!
297 -- They can match FunTy and TyConApp, so use splitAppTy_maybe
298 -- NB: we've already dealt with type variables and Notes,
299 -- so if one type is an App the other one jolly well better be too
300 unify_ subst (AppTy ty1a ty1b) ty2
301 | Just (ty2a, ty2b) <- repSplitAppTy_maybe ty2
302 = do { subst' <- unify subst ty1a ty2a
303 ; unify subst' ty1b ty2b }
305 unify_ subst ty1 (AppTy ty2a ty2b)
306 | Just (ty1a, ty1b) <- repSplitAppTy_maybe ty1
307 = do { subst' <- unify subst ty1a ty2a
308 ; unify subst' ty1b ty2b }
310 unify_ subst ty1 ty2 = failWith (misMatch ty1 ty2)
312 ------------------------------
313 unify_pred subst (ClassP c1 tys1) (ClassP c2 tys2)
314 | c1 == c2 = unify_tys subst tys1 tys2
315 unify_pred subst (IParam n1 t1) (IParam n2 t2)
316 | n1 == n2 = unify subst t1 t2
317 unify_pred subst p1 p2 = failWith (misMatch (PredTy p1) (PredTy p2))
319 ------------------------------
320 unify_tys = unifyList unify
322 unifyList :: Outputable a
323 => (TvSubstEnv -> a -> a -> UM TvSubstEnv)
324 -> TvSubstEnv -> [a] -> [a] -> UM TvSubstEnv
325 unifyList unifier subst orig_xs orig_ys
326 = go subst orig_xs orig_ys
328 go subst [] [] = return subst
329 go subst (x:xs) (y:ys) = do { subst' <- unifier subst x y
331 go subst _ _ = failWith (lengthMisMatch orig_xs orig_ys)
333 ------------------------------
334 uVar :: Bool -- Swapped
335 -> TvSubstEnv -- An existing substitution to extend
336 -> TyVar -- Type variable to be unified
337 -> Type -- with this type
340 uVar swap subst tv1 ty
341 = -- Check to see whether tv1 is refined by the substitution
342 case (lookupVarEnv subst tv1) of
343 -- Yes, call back into unify'
344 Just ty' | swap -> unify subst ty ty'
345 | otherwise -> unify subst ty' ty
347 Nothing -> uUnrefined subst tv1 ty ty
350 uUnrefined :: TvSubstEnv -- An existing substitution to extend
351 -> TyVar -- Type variable to be unified
352 -> Type -- with this type
353 -> Type -- (de-noted version)
356 -- We know that tv1 isn't refined
358 uUnrefined subst tv1 ty2 (NoteTy _ ty2')
359 = uUnrefined subst tv1 ty2 ty2' -- Unwrap synonyms
360 -- This is essential, in case we have
362 -- and then unify a :=: Foo a
364 uUnrefined subst tv1 ty2 (TyVarTy tv2)
365 | tv1 == tv2 -- Same type variable
368 -- Check to see whether tv2 is refined
369 | Just ty' <- lookupVarEnv subst tv2
370 = uUnrefined subst tv1 ty' ty'
372 -- So both are unrefined; next, see if the kinds force the direction
373 | k1 == k2 -- Can update either; so check the bind-flags
374 = do { b1 <- tvBindFlag tv1
375 ; b2 <- tvBindFlag tv2
377 (BindMe, _) -> bind tv1 ty2
379 (AvoidMe, BindMe) -> bind tv2 ty1
380 (AvoidMe, _) -> bind tv1 ty2
382 (WildCard, WildCard) -> return subst
383 (WildCard, Skolem) -> return subst
384 (WildCard, _) -> bind tv2 ty1
386 (Skolem, WildCard) -> return subst
387 (Skolem, Skolem) -> failWith (misMatch ty1 ty2)
388 (Skolem, _) -> bind tv2 ty1
391 | k1 `isSubKind` k2 = bindTv subst tv2 ty1 -- Must update tv2
392 | k2 `isSubKind` k1 = bindTv subst tv1 ty2 -- Must update tv1
394 | otherwise = failWith (kindMisMatch tv1 ty2)
399 bind tv ty = return (extendVarEnv subst tv ty)
401 uUnrefined subst tv1 ty2 ty2' -- ty2 is not a type variable
402 | tv1 `elemVarSet` substTvSet subst (tyVarsOfType ty2')
403 = failWith (occursCheck tv1 ty2) -- Occurs check
404 | not (k2 `isSubKind` k1)
405 = failWith (kindMisMatch tv1 ty2) -- Kind check
407 = bindTv subst tv1 ty2 -- Bind tyvar to the synonym if poss
412 substTvSet :: TvSubstEnv -> TyVarSet -> TyVarSet
413 -- Apply the non-idempotent substitution to a set of type variables,
414 -- remembering that the substitution isn't necessarily idempotent
416 = foldVarSet (unionVarSet . get) emptyVarSet tvs
418 get tv = case lookupVarEnv subst tv of
419 Nothing -> unitVarSet tv
420 Just ty -> substTvSet subst (tyVarsOfType ty)
422 bindTv subst tv ty -- ty is not a type variable
423 = do { b <- tvBindFlag tv
425 Skolem -> failWith (misMatch (TyVarTy tv) ty)
426 WildCard -> return subst
427 other -> return (extendVarEnv subst tv ty)
431 %************************************************************************
435 %************************************************************************
439 = BindMe -- A regular type variable
440 | AvoidMe -- Like BindMe but, given the choice, avoid binding it
442 | Skolem -- This type variable is a skolem constant
443 -- Don't bind it; it only matches itself
445 | WildCard -- This type variable matches anything,
446 -- and does not affect the substitution
448 newtype UM a = UM { unUM :: (TyVar -> BindFlag)
449 -> MaybeErr Message a }
451 instance Monad UM where
452 return a = UM (\tvs -> Succeeded a)
453 fail s = UM (\tvs -> Failed (text s))
454 m >>= k = UM (\tvs -> case unUM m tvs of
455 Failed err -> Failed err
456 Succeeded v -> unUM (k v) tvs)
458 initUM :: (TyVar -> BindFlag) -> UM a -> MaybeErr Message a
459 initUM badtvs um = unUM um badtvs
461 tvBindFlag :: TyVar -> UM BindFlag
462 tvBindFlag tv = UM (\tv_fn -> Succeeded (tv_fn tv))
464 failWith :: Message -> UM a
465 failWith msg = UM (\tv_fn -> Failed msg)
467 maybeErrToMaybe :: MaybeErr fail succ -> Maybe succ
468 maybeErrToMaybe (Succeeded a) = Just a
469 maybeErrToMaybe (Failed m) = Nothing
471 ------------------------------
472 repSplitAppTy_maybe :: Type -> Maybe (Type,Type)
473 -- Like Type.splitAppTy_maybe, but any coreView stuff is already done
474 repSplitAppTy_maybe (FunTy ty1 ty2) = Just (TyConApp funTyCon [ty1], ty2)
475 repSplitAppTy_maybe (AppTy ty1 ty2) = Just (ty1, ty2)
476 repSplitAppTy_maybe (TyConApp tc tys) = case snocView tys of
477 Just (tys', ty') -> Just (TyConApp tc tys', ty')
479 repSplitAppTy_maybe other = Nothing
483 %************************************************************************
486 We go to a lot more trouble to tidy the types
487 in TcUnify. Maybe we'll end up having to do that
488 here too, but I'll leave it for now.
490 %************************************************************************
494 = ptext SLIT("Can't match types") <+> quotes (ppr t1) <+>
495 ptext SLIT("and") <+> quotes (ppr t2)
497 lengthMisMatch tys1 tys2
498 = sep [ptext SLIT("Can't match unequal length lists"),
499 nest 2 (ppr tys1), nest 2 (ppr tys2) ]
502 = vcat [ptext SLIT("Can't match kinds") <+> quotes (ppr (tyVarKind tv1)) <+>
503 ptext SLIT("and") <+> quotes (ppr (typeKind t2)),
504 ptext SLIT("when matching") <+> quotes (ppr tv1) <+>
505 ptext SLIT("with") <+> quotes (ppr t2)]
508 = hang (ptext SLIT("Can't construct the infinite type"))
509 2 (ppr tv <+> equals <+> ppr ty)