2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
6 %************************************************************************
8 Type refinement for GADTs
10 %************************************************************************
14 Refinement, emptyRefinement, isEmptyRefinement,
16 refineType, refinePred, refineResType,
17 tcUnifyTys, BindFlag(..)
20 #include "HsVersions.h"
44 %************************************************************************
48 %************************************************************************
51 data Refinement = Reft InScopeSet InternalReft
53 type InternalReft = TyVarEnv (Coercion, Type)
54 -- INVARIANT: a->(co,ty) then co :: (a:=:ty)
55 -- Not necessarily idemopotent
57 instance Outputable Refinement where
58 ppr (Reft in_scope env)
59 = ptext SLIT("Refinement") <+>
62 emptyRefinement :: Refinement
63 emptyRefinement = (Reft emptyInScopeSet emptyVarEnv)
65 isEmptyRefinement :: Refinement -> Bool
66 isEmptyRefinement (Reft _ env) = isEmptyVarEnv env
68 refineType :: Refinement -> Type -> Maybe (Coercion, Type)
69 -- Apply the refinement to the type.
70 -- If (refineType r ty) = (co, ty')
71 -- Then co :: ty:=:ty'
72 -- Nothing => the refinement does nothing to this type
73 refineType (Reft in_scope env) ty
74 | not (isEmptyVarEnv env), -- Common case
75 any (`elemVarEnv` env) (varSetElems (tyVarsOfType ty))
76 = Just (substTy co_subst ty, substTy tv_subst ty)
78 = Nothing -- The type doesn't mention any refined type variables
80 tv_subst = mkTvSubst in_scope (mapVarEnv snd env)
81 co_subst = mkTvSubst in_scope (mapVarEnv fst env)
83 refinePred :: Refinement -> PredType -> Maybe (Coercion, PredType)
84 refinePred (Reft in_scope env) pred
85 | not (isEmptyVarEnv env), -- Common case
86 any (`elemVarEnv` env) (varSetElems (tyVarsOfPred pred))
87 = Just (mkPredTy (substPred co_subst pred), substPred tv_subst pred)
89 = Nothing -- The type doesn't mention any refined type variables
91 tv_subst = mkTvSubst in_scope (mapVarEnv snd env)
92 co_subst = mkTvSubst in_scope (mapVarEnv fst env)
94 refineResType :: Refinement -> Type -> (HsWrapper, Type)
95 -- Like refineType, but returns the 'sym' coercion
96 -- If (refineResType r ty) = (co, ty')
97 -- Then co :: ty':=:ty
98 -- It's convenient to return a HsWrapper here
100 = case refineType reft ty of
101 Just (co, ty1) -> (WpCo (mkSymCoercion co), ty1)
102 Nothing -> (idHsWrapper, ty)
106 %************************************************************************
108 Generating a type refinement
110 %************************************************************************
113 gadtRefine :: Refinement
114 -> [TyVar] -- Bind these by preference
116 -> MaybeErr Message Refinement
119 (gadtRefine cvs) takes a list of coercion variables, and returns a
120 list of coercions, obtained by unifying the types equated by the
121 incoming coercions. The returned coercions all have kinds of form
122 (a:=:ty), where a is a rigid type variable.
125 gadtRefine [c :: (a,Int):=:(Bool,b)]
126 = [ right (left c) :: a:=:Bool,
127 sym (right c) :: b:=:Int ]
129 That is, given evidence 'c' that (a,Int)=(Bool,b), it returns derived
130 evidence in easy-to-use form. In particular, given any e::ty, we know
132 e `cast` ty[right (left c)/a, sym (right c)/b]
133 :: ty [Bool/a, Int/b]
137 - It can fail, if the coercion is unsatisfiable.
139 - It's biased, by being given a set of type variables to bind
140 when there is a choice. Example:
141 MkT :: forall a. a -> T [a]
142 f :: forall b. T [b] -> b
143 f x = let v = case x of { MkT y -> y }
145 Here we want to bind [a->b], not the other way round, because
146 in this example the return type is wobbly, and we want the
150 -- E.g. (a, Bool, right (left c))
151 -- INVARIANT: in the triple (tv, ty, co), we have (co :: tv:=:ty)
152 -- The result is idempotent: the
155 gadtRefine (Reft in_scope env1)
157 -- Precondition: fvs( co_vars ) # env1
158 -- That is, the kinds of the co_vars are a
159 -- fixed point of the incoming refinement
161 = ASSERT2( not $ any (`elemVarEnv` env1) (varSetElems $ tyVarsOfTypes $ map tyVarKind co_vars),
162 ppr env1 $$ ppr co_vars $$ ppr (map tyVarKind co_vars) )
163 initUM (tryToBind tv_set) $
164 do { -- Run the unifier, starting with an empty env
165 ; env2 <- foldM do_one emptyInternalReft co_vars
167 -- Find the fixed point of the resulting
168 -- non-idempotent substitution
169 ; let tmp_env = env1 `plusVarEnv` env2
170 out_env = fixTvCoEnv in_scope' tmp_env
171 ; WARN( not (null (badReftElts tmp_env)), ppr (badReftElts tmp_env) $$ ppr tmp_env )
172 WARN( not (null (badReftElts out_env)), ppr (badReftElts out_env) $$ ppr out_env )
173 return (Reft in_scope' out_env) }
175 tv_set = mkVarSet ex_tvs
176 in_scope' = foldr extend in_scope co_vars
178 -- For each co_var, add it *and* the tyvars it mentions, to in_scope
179 extend co_var in_scope
180 = extendInScopeSetSet in_scope $
181 extendVarSet (tyVarsOfType (tyVarKind co_var)) co_var
183 do_one reft co_var = unify reft (TyVarTy co_var) ty1 ty2
185 (ty1,ty2) = splitCoercionKind (tyVarKind co_var)
188 %************************************************************************
192 %************************************************************************
195 tcUnifyTys :: (TyVar -> BindFlag)
197 -> Maybe TvSubst -- A regular one-shot substitution
198 -- The two types may have common type variables, and indeed do so in the
199 -- second call to tcUnifyTys in FunDeps.checkClsFD
201 -- We implement tcUnifyTys using the evidence-generating 'unify' function
202 -- in this module, even though we don't need to generate any evidence.
203 -- This is simply to avoid replicating all all the code for unify
204 tcUnifyTys bind_fn tys1 tys2
205 = maybeErrToMaybe $ initUM bind_fn $
206 do { reft <- unifyList emptyInternalReft cos tys1 tys2
208 -- Find the fixed point of the resulting non-idempotent substitution
209 ; let in_scope = mkInScopeSet (tvs1 `unionVarSet` tvs2)
210 tv_env = fixTvSubstEnv in_scope (mapVarEnv snd reft)
212 ; return (mkTvSubst in_scope tv_env) }
214 tvs1 = tyVarsOfTypes tys1
215 tvs2 = tyVarsOfTypes tys2
216 cos = zipWith mkUnsafeCoercion tys1 tys2
219 ----------------------------
220 fixTvCoEnv :: InScopeSet -> InternalReft -> InternalReft
221 -- Find the fixed point of a Refinement
222 -- (assuming it has no loops!)
223 fixTvCoEnv in_scope env
226 fixpt = mapVarEnv step env
228 step (co, ty) = case refineType (Reft in_scope fixpt) ty of
230 Just (co', ty') -> (mkTransCoercion co co', ty')
231 -- Apply fixpt one step:
232 -- Use refineType to get a substituted type, ty', and a coercion, co_fn,
233 -- which justifies the substitution. If the coercion is not the identity
234 -- then use transitivity with the original coercion
236 -----------------------------
237 fixTvSubstEnv :: InScopeSet -> TvSubstEnv -> TvSubstEnv
238 fixTvSubstEnv in_scope env
241 fixpt = mapVarEnv (substTy (mkTvSubst in_scope fixpt)) env
243 ----------------------------
244 tryToBind :: TyVarSet -> TyVar -> BindFlag
245 tryToBind tv_set tv | tv `elemVarSet` tv_set = BindMe
246 | otherwise = AvoidMe
251 %************************************************************************
255 %************************************************************************
259 badReftElts :: InternalReft -> [(Unique, (Coercion,Type))]
260 -- Return the BAD elements of the refinement
261 -- Should be empty; used in asserions only
263 = filter (not . ok) (ufmToList env)
265 ok :: (Unique, (Coercion, Type)) -> Bool
266 ok (u, (co, ty)) | Just tv <- tcGetTyVar_maybe ty1
267 = varUnique tv == u && ty `tcEqType` ty2
270 (ty1,ty2) = coercionKind co
273 emptyInternalReft :: InternalReft
274 emptyInternalReft = emptyVarEnv
276 unify :: InternalReft -- An existing substitution to extend
277 -> Coercion -- Witness of their equality
278 -> Type -> Type -- Types to be unified, and witness of their equality
279 -> UM InternalReft -- Just the extended substitution,
280 -- Nothing if unification failed
281 -- We do not require the incoming substitution to be idempotent,
282 -- nor guarantee that the outgoing one is. That's fixed up by
285 -- PRE-CONDITION: in the call (unify r co ty1 ty2), we know that
288 -- Respects newtypes, PredTypes
290 unify subst co ty1 ty2 = -- pprTrace "unify" (ppr subst <+> pprParendType ty1 <+> pprParendType ty2) $
291 unify_ subst co ty1 ty2
293 -- in unify_, any NewTcApps/Preds should be taken at face value
294 unify_ subst co (TyVarTy tv1) ty2 = uVar False subst co tv1 ty2
295 unify_ subst co ty1 (TyVarTy tv2) = uVar True subst co tv2 ty1
297 unify_ subst co ty1 ty2 | Just ty1' <- tcView ty1 = unify subst co ty1' ty2
298 unify_ subst co ty1 ty2 | Just ty2' <- tcView ty2 = unify subst co ty1 ty2'
300 unify_ subst co (PredTy p1) (PredTy p2) = unify_pred subst co p1 p2
302 unify_ subst co t1@(TyConApp tyc1 tys1) t2@(TyConApp tyc2 tys2)
303 | tyc1 == tyc2 = unify_tys subst co tys1 tys2
305 unify_ subst co (FunTy ty1a ty1b) (FunTy ty2a ty2b)
306 = do { let [co1,co2] = decomposeCo 2 co
307 ; subst' <- unify subst co1 ty1a ty2a
308 ; unify subst' co2 ty1b ty2b }
310 -- Applications need a bit of care!
311 -- They can match FunTy and TyConApp, so use splitAppTy_maybe
312 -- NB: we've already dealt with type variables and Notes,
313 -- so if one type is an App the other one jolly well better be too
314 unify_ subst co (AppTy ty1a ty1b) ty2
315 | Just (ty2a, ty2b) <- repSplitAppTy_maybe ty2
316 = do { subst' <- unify subst (mkLeftCoercion co) ty1a ty2a
317 ; unify subst' (mkRightCoercion co) ty1b ty2b }
319 unify_ subst co ty1 (AppTy ty2a ty2b)
320 | Just (ty1a, ty1b) <- repSplitAppTy_maybe ty1
321 = do { subst' <- unify subst (mkLeftCoercion co) ty1a ty2a
322 ; unify subst' (mkRightCoercion co) ty1b ty2b }
324 unify_ subst co ty1 ty2 = failWith (misMatch ty1 ty2)
328 ------------------------------
329 unify_pred subst co (ClassP c1 tys1) (ClassP c2 tys2)
330 | c1 == c2 = unify_tys subst co tys1 tys2
331 unify_pred subst co (IParam n1 t1) (IParam n2 t2)
332 | n1 == n2 = unify subst co t1 t2
333 unify_pred subst co p1 p2 = failWith (misMatch (PredTy p1) (PredTy p2))
335 ------------------------------
336 unify_tys :: InternalReft -> Coercion -> [Type] -> [Type] -> UM InternalReft
337 unify_tys subst co xs ys
338 = unifyList subst (decomposeCo (length xs) co) xs ys
340 unifyList :: InternalReft -> [Coercion] -> [Type] -> [Type] -> UM InternalReft
341 unifyList subst orig_cos orig_xs orig_ys
342 = go subst orig_cos orig_xs orig_ys
344 go subst _ [] [] = return subst
345 go subst (co:cos) (x:xs) (y:ys) = do { subst' <- unify subst co x y
346 ; go subst' cos xs ys }
347 go subst _ _ _ = failWith (lengthMisMatch orig_xs orig_ys)
349 ---------------------------------
350 uVar :: Bool -- Swapped
351 -> InternalReft -- An existing substitution to extend
353 -> TyVar -- Type variable to be unified
354 -> Type -- with this type
357 -- PRE-CONDITION: in the call (uVar swap r co tv1 ty), we know that
358 -- if swap=False co :: (tv1:=:ty)
359 -- if swap=True co :: (ty:=:tv1)
361 uVar swap subst co tv1 ty
362 = -- Check to see whether tv1 is refined by the substitution
363 case (lookupVarEnv subst tv1) of
365 -- Yes, call back into unify'
366 Just (co',ty') -- co' :: (tv1:=:ty')
367 | swap -- co :: (ty:=:tv1)
368 -> unify subst (mkTransCoercion co co') ty ty'
369 | otherwise -- co :: (tv1:=:ty)
370 -> unify subst (mkTransCoercion (mkSymCoercion co') co) ty' ty
373 Nothing -> uUnrefined swap subst co
377 uUnrefined :: Bool -- Whether the input is swapped
378 -> InternalReft -- An existing substitution to extend
380 -> TyVar -- Type variable to be unified
381 -> Type -- with this type
382 -> Type -- (de-noted version)
385 -- We know that tv1 isn't refined
386 -- PRE-CONDITION: in the call (uUnrefined False r co tv1 ty2 ty2'), we know that
388 -- and if the first argument is True instead, we know
391 uUnrefined swap subst co tv1 ty2 ty2'
392 | Just ty2'' <- tcView ty2'
393 = uUnrefined swap subst co tv1 ty2 ty2'' -- Unwrap synonyms
394 -- This is essential, in case we have
396 -- and then unify a :=: Foo a
398 uUnrefined swap subst co tv1 ty2 (TyVarTy tv2)
399 | tv1 == tv2 -- Same type variable
402 -- Check to see whether tv2 is refined
403 | Just (co',ty') <- lookupVarEnv subst tv2 -- co' :: tv2:=:ty'
404 = uUnrefined False subst (mkTransCoercion (doSwap swap co) co') tv1 ty' ty'
406 -- So both are unrefined; next, see if the kinds force the direction
407 | eqKind k1 k2 -- Can update either; so check the bind-flags
408 = do { b1 <- tvBindFlag tv1
409 ; b2 <- tvBindFlag tv2
411 (BindMe, _) -> bind swap tv1 ty2
413 (AvoidMe, BindMe) -> bind (not swap) tv2 ty1
414 (AvoidMe, _) -> bind swap tv1 ty2
416 (WildCard, WildCard) -> return subst
417 (WildCard, Skolem) -> return subst
418 (WildCard, _) -> bind (not swap) tv2 ty1
420 (Skolem, WildCard) -> return subst
421 (Skolem, Skolem) -> failWith (misMatch ty1 ty2)
422 (Skolem, _) -> bind (not swap) tv2 ty1
425 | k1 `isSubKind` k2 = bindTv (not swap) subst co tv2 ty1 -- Must update tv2
426 | k2 `isSubKind` k1 = bindTv swap subst co tv1 ty2 -- Must update tv1
428 | otherwise = failWith (kindMisMatch tv1 ty2)
433 bind swap tv ty = extendReft swap subst tv co ty
435 uUnrefined swap subst co tv1 ty2 ty2' -- ty2 is not a type variable
436 | tv1 `elemVarSet` substTvSet subst (tyVarsOfType ty2')
437 = failWith (occursCheck tv1 ty2) -- Occurs check
438 | not (k2 `isSubKind` k1)
439 = failWith (kindMisMatch tv1 ty2) -- Kind check
441 = bindTv swap subst co tv1 ty2 -- Bind tyvar to the synonym if poss
446 substTvSet :: InternalReft -> TyVarSet -> TyVarSet
447 -- Apply the non-idempotent substitution to a set of type variables,
448 -- remembering that the substitution isn't necessarily idempotent
450 = foldVarSet (unionVarSet . get) emptyVarSet tvs
452 get tv = case lookupVarEnv subst tv of
453 Nothing -> unitVarSet tv
454 Just (_,ty) -> substTvSet subst (tyVarsOfType ty)
456 bindTv swap subst co tv ty -- ty is not a type variable
457 = do { b <- tvBindFlag tv
459 Skolem -> failWith (misMatch (TyVarTy tv) ty)
460 WildCard -> return subst
461 other -> extendReft swap subst tv co ty
464 doSwap :: Bool -> Coercion -> Coercion
465 doSwap swap co = if swap then mkSymCoercion co else co
473 extendReft swap subst tv co ty
474 = ASSERT2( (coercionKindPredTy co1 `tcEqType` mkCoKind (mkTyVarTy tv) ty),
475 (text "Refinement invariant failure: co = " <+> ppr co1 <+> ppr (coercionKindPredTy co1) $$ text "subst = " <+> ppr tv <+> ppr (mkCoKind (mkTyVarTy tv) ty)) )
476 return (extendVarEnv subst tv (co1, ty))
482 %************************************************************************
486 %************************************************************************
490 = BindMe -- A regular type variable
491 | AvoidMe -- Like BindMe but, given the choice, avoid binding it
493 | Skolem -- This type variable is a skolem constant
494 -- Don't bind it; it only matches itself
496 | WildCard -- This type variable matches anything,
497 -- and does not affect the substitution
499 newtype UM a = UM { unUM :: (TyVar -> BindFlag)
500 -> MaybeErr Message a }
502 instance Monad UM where
503 return a = UM (\tvs -> Succeeded a)
504 fail s = UM (\tvs -> Failed (text s))
505 m >>= k = UM (\tvs -> case unUM m tvs of
506 Failed err -> Failed err
507 Succeeded v -> unUM (k v) tvs)
509 initUM :: (TyVar -> BindFlag) -> UM a -> MaybeErr Message a
510 initUM badtvs um = unUM um badtvs
512 tvBindFlag :: TyVar -> UM BindFlag
513 tvBindFlag tv = UM (\tv_fn -> Succeeded (tv_fn tv))
515 failWith :: Message -> UM a
516 failWith msg = UM (\tv_fn -> Failed msg)
518 maybeErrToMaybe :: MaybeErr fail succ -> Maybe succ
519 maybeErrToMaybe (Succeeded a) = Just a
520 maybeErrToMaybe (Failed m) = Nothing
524 %************************************************************************
527 We go to a lot more trouble to tidy the types
528 in TcUnify. Maybe we'll end up having to do that
529 here too, but I'll leave it for now.
531 %************************************************************************
535 = ptext SLIT("Can't match types") <+> quotes (ppr t1) <+>
536 ptext SLIT("and") <+> quotes (ppr t2)
538 lengthMisMatch tys1 tys2
539 = sep [ptext SLIT("Can't match unequal length lists"),
540 nest 2 (ppr tys1), nest 2 (ppr tys2) ]
543 = vcat [ptext SLIT("Can't match kinds") <+> quotes (ppr (tyVarKind tv1)) <+>
544 ptext SLIT("and") <+> quotes (ppr (typeKind t2)),
545 ptext SLIT("when matching") <+> quotes (ppr tv1) <+>
546 ptext SLIT("with") <+> quotes (ppr t2)]
549 = hang (ptext SLIT("Can't construct the infinite type"))
550 2 (ppr tv <+> equals <+> ppr ty)