2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
5 %************************************************************************
7 Type refinement for GADTs
9 %************************************************************************
13 Refinement, emptyRefinement, gadtRefine,
14 refineType, refineResType,
16 tcUnifyTys, BindFlag(..)
19 import HsSyn ( ExprCoFn(..), idCoercion, isIdCoercion )
20 import Coercion ( Coercion, mkSymCoercion, mkTransCoercion, mkUnsafeCoercion,
21 mkLeftCoercion, mkRightCoercion,
22 splitCoercionKind, decomposeCo )
23 import TcType ( TvSubst(..), TvSubstEnv, substTy, mkTvSubst,
24 substTyVar, zipTopTvSubst, typeKind,
25 eqKind, isSubKind, repSplitAppTy_maybe,
28 import Type ( Type, tyVarsOfType, tyVarsOfTypes )
29 import TypeRep ( Type(..), PredType(..) )
30 import DataCon ( DataCon, dataConUnivTyVars, dataConEqSpec )
31 import Var ( CoVar, TyVar, tyVarKind )
34 import ErrUtils ( Message )
35 import Maybes ( MaybeErr(..), isJust )
36 import Control.Monad ( foldM )
39 #include "HsVersions.h"
43 %************************************************************************
47 %************************************************************************
50 data Refinement = Reft InScopeSet InternalReft
51 -- INVARIANT: a->(co,ty) then co :: (a:=:ty)
52 -- Not necessarily idemopotent
54 instance Outputable Refinement where
55 ppr (Reft in_scope env)
56 = ptext SLIT("Refinement") <+>
59 emptyRefinement :: Refinement
60 emptyRefinement = (Reft emptyInScopeSet emptyVarEnv)
62 refineType :: Refinement -> Type -> (ExprCoFn, Type)
63 -- Apply the refinement to the type.
64 -- If (refineType r ty) = (co, ty')
65 -- Then co :: ty:=:ty'
66 refineType (Reft in_scope env) ty
67 | not (isEmptyVarEnv env), -- Common case
68 any (`elemVarEnv` env) (varSetElems (tyVarsOfType ty))
69 = (ExprCoFn (substTy co_subst ty), substTy tv_subst ty)
71 = (idCoercion, ty) -- The type doesn't mention any refined type variables
73 tv_subst = mkTvSubst in_scope (mapVarEnv snd env)
74 co_subst = mkTvSubst in_scope (mapVarEnv fst env)
76 refineResType :: Refinement -> Type -> (ExprCoFn, Type)
77 -- Like refineType, but returns the 'sym' coercion
78 -- If (refineResType r ty) = (co, ty')
79 -- Then co :: ty':=:ty
81 = case refineType reft ty of
82 (ExprCoFn co, ty1) -> (ExprCoFn (mkSymCoercion co), ty1)
83 (id_co, ty1) -> ASSERT( isIdCoercion id_co )
88 %************************************************************************
90 Generating a type refinement
92 %************************************************************************
95 gadtRefine :: Refinement
96 -> [TyVar] -- Bind these by preference
98 -> MaybeErr Message Refinement
101 (gadtRefine cvs) takes a list of coercion variables, and returns a
102 list of coercions, obtained by unifying the types equated by the
103 incoming coercions. The returned coercions all have kinds of form
104 (a:=:ty), where a is a rigid type variable.
107 gadtRefine [c :: (a,Int):=:(Bool,b)]
108 = [ right (left c) :: a:=:Bool,
109 sym (right c) :: b:=:Int ]
111 That is, given evidence 'c' that (a,Int)=(Bool,b), it returns derived
112 evidence in easy-to-use form. In particular, given any e::ty, we know
114 e `cast` ty[right (left c)/a, sym (right c)/b]
115 :: ty [Bool/a, Int/b]
119 - It can fail, if the coercion is unsatisfiable.
121 - It's biased, by being given a set of type variables to bind
122 when there is a choice. Example:
123 MkT :: forall a. a -> T [a]
124 f :: forall b. T [b] -> b
125 f x = let v = case x of { MkT y -> y }
127 Here we want to bind [a->b], not the other way round, because
128 in this example the return type is wobbly, and we want the
132 -- E.g. (a, Bool, right (left c))
133 -- INVARIANT: in the triple (tv, ty, co), we have (co :: tv:=:ty)
134 -- The result is idempotent: the
137 gadtRefine (Reft in_scope env1)
139 -- Precondition: fvs( co_vars ) # env1
140 -- That is, the kinds of the co_vars are a
141 -- fixed point of the incoming refinement
143 = initUM (tryToBind tv_set) $
144 do { -- Run the unifier, starting with an empty env
145 ; env2 <- foldM do_one emptyInternalReft co_vars
147 -- Find the fixed point of the resulting
148 -- non-idempotent substitution
149 ; let tmp_env = env1 `plusVarEnv` env2
150 out_env = fixTvCoEnv in_scope' tmp_env
151 ; return (Reft in_scope' out_env) }
153 tv_set = mkVarSet ex_tvs
154 in_scope' = foldr extend in_scope co_vars
155 extend co_var in_scope
156 = extendInScopeSetSet (extendInScopeSet in_scope co_var)
157 (tyVarsOfType (tyVarKind co_var))
159 do_one reft co_var = unify reft (TyVarTy co_var) ty1 ty2
161 (ty1,ty2) = splitCoercionKind (tyVarKind co_var)
164 %************************************************************************
168 %************************************************************************
171 tcUnifyTys :: (TyVar -> BindFlag)
173 -> Maybe TvSubst -- A regular one-shot substitution
174 -- The two types may have common type variables, and indeed do so in the
175 -- second call to tcUnifyTys in FunDeps.checkClsFD
177 -- We implement tcUnifyTys using the evidence-generating 'unify' function
178 -- in this module, even though we don't need to generate any evidence.
179 -- This is simply to avoid replicating all all the code for unify
180 tcUnifyTys bind_fn tys1 tys2
181 = maybeErrToMaybe $ initUM bind_fn $
182 do { reft <- unifyList emptyInternalReft cos tys1 tys2
184 -- Find the fixed point of the resulting non-idempotent substitution
185 ; let in_scope = mkInScopeSet (tvs1 `unionVarSet` tvs2)
186 tv_env = fixTvSubstEnv in_scope (mapVarEnv snd reft)
188 ; return (mkTvSubst in_scope tv_env) }
190 tvs1 = tyVarsOfTypes tys1
191 tvs2 = tyVarsOfTypes tys2
192 cos = zipWith mkUnsafeCoercion tys1 tys2
195 ----------------------------
196 fixTvCoEnv :: InScopeSet -> InternalReft -> InternalReft
197 -- Find the fixed point of a Refinement
198 -- (assuming it has no loops!)
199 fixTvCoEnv in_scope env
202 fixpt = mapVarEnv step env
204 step (co, ty) = (co', ty')
205 -- Apply fixpt one step:
206 -- Use refineType to get a substituted type, ty', and a coercion, co_fn,
207 -- which justifies the substitution. If the coercion is not the identity
208 -- then use transitivity with the original coercion
210 (co_fn, ty') = refineType (Reft in_scope fixpt) ty
211 co' | ExprCoFn co'' <- co_fn = mkTransCoercion co co''
212 | otherwise = ASSERT( isIdCoercion co_fn ) co
214 -----------------------------
215 fixTvSubstEnv :: InScopeSet -> TvSubstEnv -> TvSubstEnv
216 fixTvSubstEnv in_scope env
219 fixpt = mapVarEnv (substTy (mkTvSubst in_scope fixpt)) env
221 ----------------------------
222 dataConCanMatch :: DataCon -> [Type] -> Bool
223 -- Returns True iff the data con can match a scrutinee of type (T tys)
224 -- where T is the type constructor for the data con
226 -- Instantiate the equations and try to unify them
227 dataConCanMatch con tys
228 = isJust (tcUnifyTys (\tv -> BindMe)
229 (map (substTyVar subst . fst) eq_spec)
232 dc_tvs = dataConUnivTyVars con
233 eq_spec = dataConEqSpec con
234 subst = zipTopTvSubst dc_tvs tys
236 ----------------------------
237 tryToBind :: TyVarSet -> TyVar -> BindFlag
238 tryToBind tv_set tv | tv `elemVarSet` tv_set = BindMe
239 | otherwise = AvoidMe
243 %************************************************************************
247 %************************************************************************
250 type InternalReft = TyVarEnv (Coercion, Type)
252 -- INVARIANT: a->(co,ty) then co :: (a:=:ty)
253 -- Not necessarily idemopotent
255 emptyInternalReft :: InternalReft
256 emptyInternalReft = emptyVarEnv
258 unify :: InternalReft -- An existing substitution to extend
259 -> Coercion -- Witness of their equality
260 -> Type -> Type -- Types to be unified, and witness of their equality
261 -> UM InternalReft -- Just the extended substitution,
262 -- Nothing if unification failed
263 -- We do not require the incoming substitution to be idempotent,
264 -- nor guarantee that the outgoing one is. That's fixed up by
267 -- PRE-CONDITION: in the call (unify r co ty1 ty2), we know that
270 -- Respects newtypes, PredTypes
272 unify subst co ty1 ty2 = -- pprTrace "unify" (ppr subst <+> pprParendType ty1 <+> pprParendType ty2) $
273 unify_ subst co ty1 ty2
275 -- in unify_, any NewTcApps/Preds should be taken at face value
276 unify_ subst co (TyVarTy tv1) ty2 = uVar False subst co tv1 ty2
277 unify_ subst co ty1 (TyVarTy tv2) = uVar True subst co tv2 ty1
279 unify_ subst co ty1 ty2 | Just ty1' <- tcView ty1 = unify subst co ty1' ty2
280 unify_ subst co ty1 ty2 | Just ty2' <- tcView ty2 = unify subst co ty1 ty2'
282 unify_ subst co (PredTy p1) (PredTy p2) = unify_pred subst co p1 p2
284 unify_ subst co t1@(TyConApp tyc1 tys1) t2@(TyConApp tyc2 tys2)
285 | tyc1 == tyc2 = unify_tys subst co tys1 tys2
287 unify_ subst co (FunTy ty1a ty1b) (FunTy ty2a ty2b)
288 = do { let [co1,co2] = decomposeCo 2 co
289 ; subst' <- unify subst co1 ty1a ty2a
290 ; unify subst' co2 ty1b ty2b }
292 -- Applications need a bit of care!
293 -- They can match FunTy and TyConApp, so use splitAppTy_maybe
294 -- NB: we've already dealt with type variables and Notes,
295 -- so if one type is an App the other one jolly well better be too
296 unify_ subst co (AppTy ty1a ty1b) ty2
297 | Just (ty2a, ty2b) <- repSplitAppTy_maybe ty2
298 = do { subst' <- unify subst (mkLeftCoercion co) ty1a ty2a
299 ; unify subst' (mkRightCoercion co) ty1b ty2b }
301 unify_ subst co ty1 (AppTy ty2a ty2b)
302 | Just (ty1a, ty1b) <- repSplitAppTy_maybe ty1
303 = do { subst' <- unify subst (mkLeftCoercion co) ty1a ty2a
304 ; unify subst' (mkRightCoercion co) ty1b ty2b }
306 unify_ subst co ty1 ty2 = failWith (misMatch ty1 ty2)
310 ------------------------------
311 unify_pred subst co (ClassP c1 tys1) (ClassP c2 tys2)
312 | c1 == c2 = unify_tys subst co tys1 tys2
313 unify_pred subst co (IParam n1 t1) (IParam n2 t2)
314 | n1 == n2 = unify subst co t1 t2
315 unify_pred subst co p1 p2 = failWith (misMatch (PredTy p1) (PredTy p2))
317 ------------------------------
318 unify_tys :: InternalReft -> Coercion -> [Type] -> [Type] -> UM InternalReft
319 unify_tys subst co xs ys
320 = unifyList subst (decomposeCo (length xs) co) xs ys
322 unifyList :: InternalReft -> [Coercion] -> [Type] -> [Type] -> UM InternalReft
323 unifyList subst orig_cos orig_xs orig_ys
324 = go subst orig_cos orig_xs orig_ys
326 go subst _ [] [] = return subst
327 go subst (co:cos) (x:xs) (y:ys) = do { subst' <- unify subst co x y
328 ; go subst' cos xs ys }
329 go subst _ _ _ = failWith (lengthMisMatch orig_xs orig_ys)
331 ---------------------------------
332 uVar :: Bool -- Swapped
333 -> InternalReft -- An existing substitution to extend
335 -> TyVar -- Type variable to be unified
336 -> Type -- with this type
339 -- PRE-CONDITION: in the call (uVar swap r co tv1 ty), we know that
340 -- if swap=False co :: (tv1:=:ty)
341 -- if swap=True co :: (ty:=:tv1)
343 uVar swap subst co tv1 ty
344 = -- Check to see whether tv1 is refined by the substitution
345 case (lookupVarEnv subst tv1) of
347 -- Yes, call back into unify'
348 Just (co',ty') -- co' :: (tv1:=:ty')
349 | swap -- co :: (ty:=:tv1)
350 -> unify subst (mkTransCoercion co co') ty ty'
351 | otherwise -- co :: (tv1:=:ty)
352 -> unify subst (mkTransCoercion (mkSymCoercion co') co) ty' ty
355 Nothing -> uUnrefined subst (if swap then mkSymCoercion co else co)
359 uUnrefined :: InternalReft -- An existing substitution to extend
361 -> TyVar -- Type variable to be unified
362 -> Type -- with this type
363 -> Type -- (de-noted version)
366 -- We know that tv1 isn't refined
367 -- PRE-CONDITION: in the call (uUnrefined r co tv ty ty'), we know that
370 uUnrefined subst co tv1 ty2 ty2'
371 | Just ty2'' <- tcView ty2'
372 = uUnrefined subst co tv1 ty2 ty2'' -- Unwrap synonyms
373 -- This is essential, in case we have
375 -- and then unify a :=: Foo a
377 uUnrefined subst co tv1 ty2 (TyVarTy tv2)
378 | tv1 == tv2 -- Same type variable
381 -- Check to see whether tv2 is refined
382 | Just (co',ty') <- lookupVarEnv subst tv2
383 = uUnrefined subst (mkTransCoercion co co') tv1 ty' ty'
385 -- So both are unrefined; next, see if the kinds force the direction
386 | eqKind k1 k2 -- Can update either; so check the bind-flags
387 = do { b1 <- tvBindFlag tv1
388 ; b2 <- tvBindFlag tv2
390 (BindMe, _) -> bind tv1 ty2
392 (AvoidMe, BindMe) -> bind tv2 ty1
393 (AvoidMe, _) -> bind tv1 ty2
395 (WildCard, WildCard) -> return subst
396 (WildCard, Skolem) -> return subst
397 (WildCard, _) -> bind tv2 ty1
399 (Skolem, WildCard) -> return subst
400 (Skolem, Skolem) -> failWith (misMatch ty1 ty2)
401 (Skolem, _) -> bind tv2 ty1
404 | k1 `isSubKind` k2 = bindTv subst co tv2 ty1 -- Must update tv2
405 | k2 `isSubKind` k1 = bindTv subst co tv1 ty2 -- Must update tv1
407 | otherwise = failWith (kindMisMatch tv1 ty2)
412 bind tv ty = return (extendVarEnv subst tv (co,ty))
414 uUnrefined subst co tv1 ty2 ty2' -- ty2 is not a type variable
415 | tv1 `elemVarSet` substTvSet subst (tyVarsOfType ty2')
416 = failWith (occursCheck tv1 ty2) -- Occurs check
417 | not (k2 `isSubKind` k1)
418 = failWith (kindMisMatch tv1 ty2) -- Kind check
420 = bindTv subst co tv1 ty2 -- Bind tyvar to the synonym if poss
425 substTvSet :: InternalReft -> TyVarSet -> TyVarSet
426 -- Apply the non-idempotent substitution to a set of type variables,
427 -- remembering that the substitution isn't necessarily idempotent
429 = foldVarSet (unionVarSet . get) emptyVarSet tvs
431 get tv = case lookupVarEnv subst tv of
432 Nothing -> unitVarSet tv
433 Just (_,ty) -> substTvSet subst (tyVarsOfType ty)
435 bindTv subst co tv ty -- ty is not a type variable
436 = do { b <- tvBindFlag tv
438 Skolem -> failWith (misMatch (TyVarTy tv) ty)
439 WildCard -> return subst
440 other -> return (extendVarEnv subst tv (co,ty))
444 %************************************************************************
448 %************************************************************************
452 = BindMe -- A regular type variable
453 | AvoidMe -- Like BindMe but, given the choice, avoid binding it
455 | Skolem -- This type variable is a skolem constant
456 -- Don't bind it; it only matches itself
458 | WildCard -- This type variable matches anything,
459 -- and does not affect the substitution
461 newtype UM a = UM { unUM :: (TyVar -> BindFlag)
462 -> MaybeErr Message a }
464 instance Monad UM where
465 return a = UM (\tvs -> Succeeded a)
466 fail s = UM (\tvs -> Failed (text s))
467 m >>= k = UM (\tvs -> case unUM m tvs of
468 Failed err -> Failed err
469 Succeeded v -> unUM (k v) tvs)
471 initUM :: (TyVar -> BindFlag) -> UM a -> MaybeErr Message a
472 initUM badtvs um = unUM um badtvs
474 tvBindFlag :: TyVar -> UM BindFlag
475 tvBindFlag tv = UM (\tv_fn -> Succeeded (tv_fn tv))
477 failWith :: Message -> UM a
478 failWith msg = UM (\tv_fn -> Failed msg)
480 maybeErrToMaybe :: MaybeErr fail succ -> Maybe succ
481 maybeErrToMaybe (Succeeded a) = Just a
482 maybeErrToMaybe (Failed m) = Nothing
486 %************************************************************************
489 We go to a lot more trouble to tidy the types
490 in TcUnify. Maybe we'll end up having to do that
491 here too, but I'll leave it for now.
493 %************************************************************************
497 = ptext SLIT("Can't match types") <+> quotes (ppr t1) <+>
498 ptext SLIT("and") <+> quotes (ppr t2)
500 lengthMisMatch tys1 tys2
501 = sep [ptext SLIT("Can't match unequal length lists"),
502 nest 2 (ppr tys1), nest 2 (ppr tys2) ]
505 = vcat [ptext SLIT("Can't match kinds") <+> quotes (ppr (tyVarKind tv1)) <+>
506 ptext SLIT("and") <+> quotes (ppr (typeKind t2)),
507 ptext SLIT("when matching") <+> quotes (ppr tv1) <+>
508 ptext SLIT("with") <+> quotes (ppr t2)]
511 = hang (ptext SLIT("Can't construct the infinite type"))
512 2 (ppr tv <+> equals <+> ppr ty)