3 -- Matching and unification
4 tcMatchTys, tcMatchTyX, ruleMatchTyX, tcMatchPreds, MatchEnv(..),
8 gadtRefineTys, BindFlag(..),
10 coreRefineTys, dataConCanMatch, 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 mkOpenTvSubst, tcView )
25 import TypeRep ( Type(..), PredType(..), funTyCon )
26 import DataCon ( DataCon, isVanillaDataCon, dataConResTys, dataConInstResTy )
27 import Util ( snocView )
28 import ErrUtils ( Message )
34 %************************************************************************
38 %************************************************************************
41 Matching is much tricker than you might think.
43 1. The substitution we generate binds the *template type variables*
44 which are given to us explicitly.
46 2. We want to match in the presence of foralls;
47 e.g (forall a. t1) ~ (forall b. t2)
49 That is what the RnEnv2 is for; it does the alpha-renaming
50 that makes it as if a and b were the same variable.
51 Initialising the RnEnv2, so that it can generate a fresh
52 binder when necessary, entails knowing the free variables of
55 3. We must be careful not to bind a template type variable to a
56 locally bound variable. E.g.
57 (forall a. x) ~ (forall b. b)
58 where x is the template type variable. Then we do not want to
59 bind x to a/b! This is a kind of occurs check.
60 The necessary locals accumulate in the RnEnv2.
65 = ME { me_tmpls :: VarSet -- Template tyvars
66 , me_env :: RnEnv2 -- Renaming envt for nested foralls
67 } -- In-scope set includes template tyvars
69 tcMatchTys :: TyVarSet -- Template tyvars
72 -> Maybe TvSubst -- One-shot; in principle the template
73 -- variables could be free in the target
75 tcMatchTys tmpls tys1 tys2
76 = case match_tys menv emptyTvSubstEnv tys1 tys2 of
77 Just subst_env -> Just (TvSubst in_scope subst_env)
80 menv = ME { me_tmpls = tmpls, me_env = mkRnEnv2 in_scope }
81 in_scope = mkInScopeSet (tmpls `unionVarSet` tyVarsOfTypes tys2)
82 -- We're assuming that all the interesting
83 -- tyvars in tys1 are in tmpls
85 -- This is similar, but extends a substitution
86 tcMatchTyX :: TyVarSet -- Template tyvars
87 -> TvSubst -- Substitution to extend
91 tcMatchTyX tmpls (TvSubst in_scope subst_env) ty1 ty2
92 = case match menv subst_env ty1 ty2 of
93 Just subst_env -> Just (TvSubst in_scope subst_env)
96 menv = ME {me_tmpls = tmpls, me_env = mkRnEnv2 in_scope}
99 :: [TyVar] -- Bind these
100 -> [PredType] -> [PredType]
102 tcMatchPreds tmpls ps1 ps2
103 = match_list (match_pred menv) emptyTvSubstEnv ps1 ps2
105 menv = ME { me_tmpls = mkVarSet tmpls, me_env = mkRnEnv2 in_scope_tyvars }
106 in_scope_tyvars = mkInScopeSet (tyVarsOfTheta ps1 `unionVarSet` tyVarsOfTheta ps2)
108 -- This one is called from the expression matcher, which already has a MatchEnv in hand
109 ruleMatchTyX :: MatchEnv
110 -> TvSubstEnv -- Substitution to extend
115 ruleMatchTyX menv subst ty1 ty2 = match menv subst ty1 ty2 -- Rename for export
118 Now the internals of matching
121 match :: MatchEnv -- For the most part this is pushed downwards
122 -> TvSubstEnv -- Substitution so far:
123 -- Domain is subset of template tyvars
124 -- Free vars of range is subset of
125 -- in-scope set of the RnEnv2
126 -> Type -> Type -- Template and target respectively
128 -- This matcher works on source types; that is,
129 -- it respects NewTypes and PredType
131 match menv subst ty1 ty2 | Just ty1' <- tcView ty1 = match menv subst ty1' ty2
132 match menv subst ty1 ty2 | Just ty2' <- tcView ty2 = match menv subst ty1 ty2'
134 match menv subst (TyVarTy tv1) ty2
135 | tv1 `elemVarSet` me_tmpls menv
136 = case lookupVarEnv subst tv1' of
137 Nothing | any (inRnEnvR rn_env) (varSetElems (tyVarsOfType ty2))
138 -> Nothing -- Occurs check
139 | not (typeKind ty2 `isSubKind` tyVarKind tv1)
140 -> Nothing -- Kind mis-match
142 -> Just (extendVarEnv subst tv1 ty2)
144 Just ty1' | tcEqTypeX (nukeRnEnvL rn_env) ty1' ty2
145 -- ty1 has no locally-bound variables, hence nukeRnEnvL
146 -- Note tcEqType...we are doing source-type matching here
151 | otherwise -- tv1 is not a template tyvar
153 TyVarTy tv2 | tv1' == rnOccR rn_env tv2 -> Just subst
157 tv1' = rnOccL rn_env tv1
159 match menv subst (ForAllTy tv1 ty1) (ForAllTy tv2 ty2)
160 = match menv' subst ty1 ty2
161 where -- Use the magic of rnBndr2 to go under the binders
162 menv' = menv { me_env = rnBndr2 (me_env menv) tv1 tv2 }
164 match menv subst (PredTy p1) (PredTy p2)
165 = match_pred menv subst p1 p2
166 match menv subst (TyConApp tc1 tys1) (TyConApp tc2 tys2)
167 | tc1 == tc2 = match_tys menv subst tys1 tys2
168 match menv subst (FunTy ty1a ty1b) (FunTy ty2a ty2b)
169 = do { subst' <- match menv subst ty1a ty2a
170 ; match menv subst' ty1b ty2b }
171 match menv subst (AppTy ty1a ty1b) ty2
172 | Just (ty2a, ty2b) <- repSplitAppTy_maybe ty2
173 = do { subst' <- match menv subst ty1a ty2a
174 ; match menv subst' ty1b ty2b }
176 match menv subst ty1 ty2
180 match_tys menv subst tys1 tys2 = match_list (match menv) subst tys1 tys2
183 match_list :: (TvSubstEnv -> a -> a -> Maybe TvSubstEnv)
184 -> TvSubstEnv -> [a] -> [a] -> Maybe TvSubstEnv
185 match_list fn subst [] [] = Just subst
186 match_list fn subst (ty1:tys1) (ty2:tys2) = do { subst' <- fn subst ty1 ty2
187 ; match_list fn subst' tys1 tys2 }
188 match_list fn subst tys1 tys2 = Nothing
191 match_pred menv subst (ClassP c1 tys1) (ClassP c2 tys2)
192 | c1 == c2 = match_tys menv subst tys1 tys2
193 match_pred menv subst (IParam n1 t1) (IParam n2 t2)
194 | n1 == n2 = match menv subst t1 t2
195 match_pred menv subst p1 p2 = Nothing
199 %************************************************************************
203 %************************************************************************
206 tcUnifyTys :: (TyVar -> BindFlag)
208 -> Maybe TvSubst -- A regular one-shot substitution
209 -- The two types may have common type variables, and indeed do so in the
210 -- second call to tcUnifyTys in FunDeps.checkClsFD
211 tcUnifyTys bind_fn tys1 tys2
212 = maybeErrToMaybe $ initUM bind_fn $
213 do { subst_env <- unify_tys emptyTvSubstEnv tys1 tys2
215 -- Find the fixed point of the resulting non-idempotent substitution
216 ; let in_scope = mkInScopeSet (tvs1 `unionVarSet` tvs2)
217 subst = TvSubst in_scope subst_env_fixpt
218 subst_env_fixpt = mapVarEnv (substTy subst) subst_env
221 tvs1 = tyVarsOfTypes tys1
222 tvs2 = tyVarsOfTypes tys2
224 ----------------------------
225 dataConCanMatch :: DataCon -> [Type] -> Bool
226 -- Returns True iff the data con can match a scrutinee of type (T tys)
227 -- where T is the type constructor for the data con
228 dataConCanMatch con tys
229 | isVanillaDataCon con
232 = isSuccess $ initUM (\tv -> BindMe) $
233 unify_tys emptyTvSubstEnv (dataConResTys con) tys
235 ----------------------------
236 coreRefineTys :: DataCon -> [TyVar] -- Case pattern (con tv1 .. tvn ...)
237 -> Type -- Type of scrutinee
238 -> Maybe TypeRefinement
240 type TypeRefinement = (TvSubstEnv, Bool)
241 -- The Bool is True iff all the bindings in the
242 -- env are for the pattern type variables
243 -- In this case, there is no type refinement
244 -- for already-in-scope type variables
246 -- Used by Core Lint and the simplifier.
247 coreRefineTys con tvs scrut_ty
248 = maybeErrToMaybe $ initUM (tryToBind tv_set) $
249 do { -- Run the unifier, starting with an empty env
250 ; subst_env <- unify emptyTvSubstEnv pat_res_ty scrut_ty
252 -- Find the fixed point of the resulting non-idempotent substitution
253 ; let subst = mkOpenTvSubst subst_env_fixpt
254 subst_env_fixpt = mapVarEnv (substTy subst) subst_env
256 ; return (subst_env_fixpt, all_bound_here subst_env) }
258 pat_res_ty = dataConInstResTy con (mkTyVarTys tvs)
260 -- 'tvs' are the tyvars bound by the pattern
261 tv_set = mkVarSet tvs
262 all_bound_here env = all bound_here (varEnvKeys env)
263 bound_here uniq = elemVarSetByKey uniq tv_set
265 -- This version is used by the type checker
266 gadtRefineTys :: TvSubst
267 -> DataCon -> [TyVar]
269 -> MaybeErr Message (TvSubst, Bool)
270 -- The bool is True <=> the only *new* bindings are for pat_tvs
272 gadtRefineTys (TvSubst in_scope env1) con pat_tvs pat_tys ctxt_tys
273 = initUM (tryToBind tv_set) $
274 do { -- Run the unifier, starting with an empty env
275 ; env2 <- unify_tys env1 pat_tys ctxt_tys
277 -- Find the fixed point of the resulting non-idempotent substitution
278 ; let subst2 = TvSubst in_scope subst_env_fixpt
279 subst_env_fixpt = mapVarEnv (substTy subst2) env2
281 ; return (subst2, all_bound_here env2) }
283 -- 'tvs' are the tyvars bound by the pattern
284 tv_set = mkVarSet pat_tvs
285 all_bound_here env = all bound_here (varEnvKeys env)
286 bound_here uniq = elemVarEnvByKey uniq env1 || elemVarSetByKey uniq tv_set
287 -- The bool is True <=> the only *new* bindings are for pat_tvs
289 ----------------------------
290 tryToBind :: TyVarSet -> TyVar -> BindFlag
291 tryToBind tv_set tv | tv `elemVarSet` tv_set = BindMe
292 | otherwise = AvoidMe
296 %************************************************************************
300 %************************************************************************
303 unify :: TvSubstEnv -- An existing substitution to extend
304 -> Type -> Type -- Types to be unified
305 -> UM TvSubstEnv -- Just the extended substitution,
306 -- Nothing if unification failed
307 -- We do not require the incoming substitution to be idempotent,
308 -- nor guarantee that the outgoing one is. That's fixed up by
311 -- Respects newtypes, PredTypes
313 unify subst ty1 ty2 = -- pprTrace "unify" (ppr subst <+> pprParendType ty1 <+> pprParendType ty2) $
316 -- in unify_, any NewTcApps/Preds should be taken at face value
317 unify_ subst (TyVarTy tv1) ty2 = uVar False subst tv1 ty2
318 unify_ subst ty1 (TyVarTy tv2) = uVar True subst tv2 ty1
320 unify_ subst ty1 ty2 | Just ty1' <- tcView ty1 = unify subst ty1' ty2
321 unify_ subst ty1 ty2 | Just ty2' <- tcView ty2 = unify subst ty1 ty2'
323 unify_ subst (PredTy p1) (PredTy p2) = unify_pred subst p1 p2
325 unify_ subst t1@(TyConApp tyc1 tys1) t2@(TyConApp tyc2 tys2)
326 | tyc1 == tyc2 = unify_tys subst tys1 tys2
328 unify_ subst (FunTy ty1a ty1b) (FunTy ty2a ty2b)
329 = do { subst' <- unify subst ty1a ty2a
330 ; unify subst' ty1b ty2b }
332 -- Applications need a bit of care!
333 -- They can match FunTy and TyConApp, so use splitAppTy_maybe
334 -- NB: we've already dealt with type variables and Notes,
335 -- so if one type is an App the other one jolly well better be too
336 unify_ subst (AppTy ty1a ty1b) ty2
337 | Just (ty2a, ty2b) <- repSplitAppTy_maybe ty2
338 = do { subst' <- unify subst ty1a ty2a
339 ; unify subst' ty1b ty2b }
341 unify_ subst ty1 (AppTy ty2a ty2b)
342 | Just (ty1a, ty1b) <- repSplitAppTy_maybe ty1
343 = do { subst' <- unify subst ty1a ty2a
344 ; unify subst' ty1b ty2b }
346 unify_ subst ty1 ty2 = failWith (misMatch ty1 ty2)
348 ------------------------------
349 unify_pred subst (ClassP c1 tys1) (ClassP c2 tys2)
350 | c1 == c2 = unify_tys subst tys1 tys2
351 unify_pred subst (IParam n1 t1) (IParam n2 t2)
352 | n1 == n2 = unify subst t1 t2
353 unify_pred subst p1 p2 = failWith (misMatch (PredTy p1) (PredTy p2))
355 ------------------------------
356 unify_tys = unifyList unify
358 unifyList :: Outputable a
359 => (TvSubstEnv -> a -> a -> UM TvSubstEnv)
360 -> TvSubstEnv -> [a] -> [a] -> UM TvSubstEnv
361 unifyList unifier subst orig_xs orig_ys
362 = go subst orig_xs orig_ys
364 go subst [] [] = return subst
365 go subst (x:xs) (y:ys) = do { subst' <- unifier subst x y
367 go subst _ _ = failWith (lengthMisMatch orig_xs orig_ys)
369 ------------------------------
370 uVar :: Bool -- Swapped
371 -> TvSubstEnv -- An existing substitution to extend
372 -> TyVar -- Type variable to be unified
373 -> Type -- with this type
376 uVar swap subst tv1 ty
377 = -- Check to see whether tv1 is refined by the substitution
378 case (lookupVarEnv subst tv1) of
379 -- Yes, call back into unify'
380 Just ty' | swap -> unify subst ty ty'
381 | otherwise -> unify subst ty' ty
383 Nothing -> uUnrefined subst tv1 ty ty
386 uUnrefined :: TvSubstEnv -- An existing substitution to extend
387 -> TyVar -- Type variable to be unified
388 -> Type -- with this type
389 -> Type -- (de-noted version)
392 -- We know that tv1 isn't refined
394 uUnrefined subst tv1 ty2 ty2'
395 | Just ty2'' <- tcView ty2'
396 = uUnrefined subst tv1 ty2 ty2'' -- Unwrap synonyms
397 -- This is essential, in case we have
399 -- and then unify a :=: Foo a
401 uUnrefined subst tv1 ty2 (TyVarTy tv2)
402 | tv1 == tv2 -- Same type variable
405 -- Check to see whether tv2 is refined
406 | Just ty' <- lookupVarEnv subst tv2
407 = uUnrefined subst tv1 ty' ty'
409 -- So both are unrefined; next, see if the kinds force the direction
410 | k1 == k2 -- Can update either; so check the bind-flags
411 = do { b1 <- tvBindFlag tv1
412 ; b2 <- tvBindFlag tv2
414 (BindMe, _) -> bind tv1 ty2
416 (AvoidMe, BindMe) -> bind tv2 ty1
417 (AvoidMe, _) -> bind tv1 ty2
419 (WildCard, WildCard) -> return subst
420 (WildCard, Skolem) -> return subst
421 (WildCard, _) -> bind tv2 ty1
423 (Skolem, WildCard) -> return subst
424 (Skolem, Skolem) -> failWith (misMatch ty1 ty2)
425 (Skolem, _) -> bind tv2 ty1
428 | k1 `isSubKind` k2 = bindTv subst tv2 ty1 -- Must update tv2
429 | k2 `isSubKind` k1 = bindTv subst tv1 ty2 -- Must update tv1
431 | otherwise = failWith (kindMisMatch tv1 ty2)
436 bind tv ty = return (extendVarEnv subst tv ty)
438 uUnrefined subst tv1 ty2 ty2' -- ty2 is not a type variable
439 | tv1 `elemVarSet` substTvSet subst (tyVarsOfType ty2')
440 = failWith (occursCheck tv1 ty2) -- Occurs check
441 | not (k2 `isSubKind` k1)
442 = failWith (kindMisMatch tv1 ty2) -- Kind check
444 = bindTv subst tv1 ty2 -- Bind tyvar to the synonym if poss
449 substTvSet :: TvSubstEnv -> TyVarSet -> TyVarSet
450 -- Apply the non-idempotent substitution to a set of type variables,
451 -- remembering that the substitution isn't necessarily idempotent
453 = foldVarSet (unionVarSet . get) emptyVarSet tvs
455 get tv = case lookupVarEnv subst tv of
456 Nothing -> unitVarSet tv
457 Just ty -> substTvSet subst (tyVarsOfType ty)
459 bindTv subst tv ty -- ty is not a type variable
460 = do { b <- tvBindFlag tv
462 Skolem -> failWith (misMatch (TyVarTy tv) ty)
463 WildCard -> return subst
464 other -> return (extendVarEnv subst tv ty)
468 %************************************************************************
472 %************************************************************************
476 = BindMe -- A regular type variable
477 | AvoidMe -- Like BindMe but, given the choice, avoid binding it
479 | Skolem -- This type variable is a skolem constant
480 -- Don't bind it; it only matches itself
482 | WildCard -- This type variable matches anything,
483 -- and does not affect the substitution
485 newtype UM a = UM { unUM :: (TyVar -> BindFlag)
486 -> MaybeErr Message a }
488 instance Monad UM where
489 return a = UM (\tvs -> Succeeded a)
490 fail s = UM (\tvs -> Failed (text s))
491 m >>= k = UM (\tvs -> case unUM m tvs of
492 Failed err -> Failed err
493 Succeeded v -> unUM (k v) tvs)
495 initUM :: (TyVar -> BindFlag) -> UM a -> MaybeErr Message a
496 initUM badtvs um = unUM um badtvs
498 tvBindFlag :: TyVar -> UM BindFlag
499 tvBindFlag tv = UM (\tv_fn -> Succeeded (tv_fn tv))
501 failWith :: Message -> UM a
502 failWith msg = UM (\tv_fn -> Failed msg)
504 maybeErrToMaybe :: MaybeErr fail succ -> Maybe succ
505 maybeErrToMaybe (Succeeded a) = Just a
506 maybeErrToMaybe (Failed m) = Nothing
508 ------------------------------
509 repSplitAppTy_maybe :: Type -> Maybe (Type,Type)
510 -- Like Type.splitAppTy_maybe, but any coreView stuff is already done
511 repSplitAppTy_maybe (FunTy ty1 ty2) = Just (TyConApp funTyCon [ty1], ty2)
512 repSplitAppTy_maybe (AppTy ty1 ty2) = Just (ty1, ty2)
513 repSplitAppTy_maybe (TyConApp tc tys) = case snocView tys of
514 Just (tys', ty') -> Just (TyConApp tc tys', ty')
516 repSplitAppTy_maybe other = Nothing
520 %************************************************************************
523 We go to a lot more trouble to tidy the types
524 in TcUnify. Maybe we'll end up having to do that
525 here too, but I'll leave it for now.
527 %************************************************************************
531 = ptext SLIT("Can't match types") <+> quotes (ppr t1) <+>
532 ptext SLIT("and") <+> quotes (ppr t2)
534 lengthMisMatch tys1 tys2
535 = sep [ptext SLIT("Can't match unequal length lists"),
536 nest 2 (ppr tys1), nest 2 (ppr tys2) ]
539 = vcat [ptext SLIT("Can't match kinds") <+> quotes (ppr (tyVarKind tv1)) <+>
540 ptext SLIT("and") <+> quotes (ppr (typeKind t2)),
541 ptext SLIT("when matching") <+> quotes (ppr tv1) <+>
542 ptext SLIT("with") <+> quotes (ppr t2)]
545 = hang (ptext SLIT("Can't construct the infinite type"))
546 2 (ppr tv <+> equals <+> ppr ty)