1 Normalisation of type terms relative to type instances as well as
2 normalisation and entailment checking of equality constraints.
8 normaliseGivenEqs, normaliseGivenDicts,
9 normaliseWantedEqs, normaliseWantedDicts,
14 misMatchMsg, failWithMisMatch
18 #include "HsVersions.h"
30 import TypeRep ( Type(..) )
38 import SrcLoc ( Located(..) )
43 import Control.Monad (liftM)
47 %************************************************************************
49 Normalisation of types
51 %************************************************************************
53 Unfold a single synonym family instance and yield the witnessing coercion.
54 Return 'Nothing' if the given type is either not synonym family instance
55 or is a synonym family instance that has no matching instance declaration.
56 (Applies only if the type family application is outermost.)
58 For example, if we have
60 :Co:R42T a :: T [a] ~ :R42T a
62 then 'T [Int]' unfolds to (:R42T Int, :Co:R42T Int).
65 tcUnfoldSynFamInst :: Type -> TcM (Maybe (Type, Coercion))
66 tcUnfoldSynFamInst (TyConApp tycon tys)
67 | not (isOpenSynTyCon tycon) -- unfold *only* _synonym_ family instances
70 = do { -- we only use the indexing arguments for matching,
71 -- not the additional ones
72 ; maybeFamInst <- tcLookupFamInst tycon idxTys
73 ; case maybeFamInst of
74 Nothing -> return Nothing
75 Just (rep_tc, rep_tys) -> return $ Just (mkTyConApp rep_tc tys',
76 mkTyConApp coe_tc tys')
78 tys' = rep_tys ++ restTys
79 coe_tc = expectJust "TcTyFun.tcUnfoldSynFamInst"
80 (tyConFamilyCoercion_maybe rep_tc)
84 (idxTys, restTys) = splitAt n tys
85 tcUnfoldSynFamInst _other = return Nothing
88 Normalise 'Type's and 'PredType's by unfolding type family applications where
89 possible (ie, we treat family instances as a TRS). Also zonk meta variables.
91 tcNormaliseFamInst ty = (co, ty')
95 tcNormaliseFamInst :: TcType -> TcM (CoercionI, TcType)
96 tcNormaliseFamInst = tcGenericNormaliseFamInst tcUnfoldSynFamInst
98 tcNormaliseFamInstPred :: TcPredType -> TcM (CoercionI, TcPredType)
99 tcNormaliseFamInstPred = tcGenericNormaliseFamInstPred tcUnfoldSynFamInst
102 An elementary rewrite is a properly oriented equality with associated coercion
103 that has one of the following two forms:
105 (1) co :: F t1..tn ~ t
106 (2) co :: a ~ t , where t /= F t1..tn and a is a skolem tyvar
108 NB: We do *not* use equalities of the form a ~ t where a is a meta tyvar as a
109 reqrite rule. Instead, such equalities are solved by unification. This is
110 essential; cf Note [skolemOccurs loop].
112 The following functions takes an equality instance and turns it into an
113 elementary rewrite if possible.
116 data Rewrite = Rewrite TcType -- lhs of rewrite rule
117 TcType -- rhs of rewrite rule
118 TcType -- coercion witnessing the rewrite rule
120 eqInstToRewrite :: Inst -> Maybe (Rewrite, Bool)
121 -- True iff rewrite swapped equality
123 = ASSERT( isEqInst inst )
124 go ty1 ty2 (eqInstType inst)
126 (ty1,ty2) = eqInstTys inst
128 -- look through synonyms
129 go ty1 ty2 co | Just ty1' <- tcView ty1 = go ty1' ty2 co
130 go ty1 ty2 co | Just ty2' <- tcView ty2 = go ty1 ty2' co
132 -- left-to-right rule with type family head
133 go ty1@(TyConApp con _) ty2 co
135 = Just (Rewrite ty1 ty2 co, False) -- not swapped
137 -- left-to-right rule with type variable head
138 go ty1@(TyVarTy tv) ty2 co
140 = Just (Rewrite ty1 ty2 co, False) -- not swapped
142 -- right-to-left rule with type family head, only after
143 -- having checked whether we can work left-to-right
144 go ty1 ty2@(TyConApp con _) co
146 = Just (Rewrite ty2 ty1 (mkSymCoercion co), True) -- swapped
148 -- right-to-left rule with type variable head, only after
149 -- having checked whether we can work left-to-right
150 go ty1 ty2@(TyVarTy tv) co
152 = Just (Rewrite ty2 ty1 (mkSymCoercion co), True) -- swapped
154 -- this equality is not a rewrite rule => ignore
158 Normalise a type relative to an elementary rewrite implied by an EqInst or an
159 explicitly given elementary rewrite.
163 -- Precondition: the EqInst passes the occurs check
164 tcEqInstNormaliseFamInst :: Inst -> TcType -> TcM (CoercionI, TcType)
165 tcEqInstNormaliseFamInst inst ty
166 = case eqInstToRewrite inst of
167 Just (rewrite, _) -> tcEqRuleNormaliseFamInst rewrite ty
168 Nothing -> return (IdCo, ty)
170 -- Rewrite by equality rewrite rule
171 tcEqRuleNormaliseFamInst :: Rewrite -- elementary rewrite
172 -> TcType -- type to rewrite
173 -> TcM (CoercionI, -- witnessing coercion
174 TcType) -- rewritten type
175 tcEqRuleNormaliseFamInst (Rewrite pat rhs co) ty
176 = tcGenericNormaliseFamInst matchEqRule ty
178 matchEqRule sty | pat `tcEqType` sty = return $ Just (rhs, co)
179 | otherwise = return $ Nothing
182 Generic normalisation of 'Type's and 'PredType's; ie, walk the type term and
183 apply the normalisation function gives as the first argument to every TyConApp
184 and every TyVarTy subterm.
186 tcGenericNormaliseFamInst fun ty = (co, ty')
189 This function is (by way of using smart constructors) careful to ensure that
190 the returned coercion is exactly IdCo (and not some semantically equivalent,
191 but syntactically different coercion) whenever (ty' `tcEqType` ty). This
192 makes it easy for the caller to determine whether the type changed. BUT
193 even if we return IdCo, ty' may be *syntactically* different from ty due to
194 unfolded closed type synonyms (by way of tcCoreView). In the interest of
195 good error messages, callers should discard ty' in favour of ty in this case.
198 tcGenericNormaliseFamInst :: (TcType -> TcM (Maybe (TcType, Coercion)))
199 -- what to do with type functions and tyvars
200 -> TcType -- old type
201 -> TcM (CoercionI, TcType) -- (coercion, new type)
202 tcGenericNormaliseFamInst fun ty
203 | Just ty' <- tcView ty = tcGenericNormaliseFamInst fun ty'
204 tcGenericNormaliseFamInst fun (TyConApp tyCon tys)
205 = do { (cois, ntys) <- mapAndUnzipM (tcGenericNormaliseFamInst fun) tys
206 ; let tycon_coi = mkTyConAppCoI tyCon ntys cois
207 ; maybe_ty_co <- fun (mkTyConApp tyCon ntys) -- use normalised args!
208 ; case maybe_ty_co of
209 -- a matching family instance exists
211 do { let first_coi = mkTransCoI tycon_coi (ACo co)
212 ; (rest_coi, nty) <- tcGenericNormaliseFamInst fun ty'
213 ; let fix_coi = mkTransCoI first_coi rest_coi
214 ; return (fix_coi, nty)
216 -- no matching family instance exists
217 -- we do not do anything
218 Nothing -> return (tycon_coi, mkTyConApp tyCon ntys)
220 tcGenericNormaliseFamInst fun (AppTy ty1 ty2)
221 = do { (coi1,nty1) <- tcGenericNormaliseFamInst fun ty1
222 ; (coi2,nty2) <- tcGenericNormaliseFamInst fun ty2
223 ; return (mkAppTyCoI nty1 coi1 nty2 coi2, mkAppTy nty1 nty2)
225 tcGenericNormaliseFamInst fun (FunTy ty1 ty2)
226 = do { (coi1,nty1) <- tcGenericNormaliseFamInst fun ty1
227 ; (coi2,nty2) <- tcGenericNormaliseFamInst fun ty2
228 ; return (mkFunTyCoI nty1 coi1 nty2 coi2, mkFunTy nty1 nty2)
230 tcGenericNormaliseFamInst fun (ForAllTy tyvar ty1)
231 = do { (coi,nty1) <- tcGenericNormaliseFamInst fun ty1
232 ; return (mkForAllTyCoI tyvar coi, mkForAllTy tyvar nty1)
234 tcGenericNormaliseFamInst fun (NoteTy note ty1)
235 = do { (coi,nty1) <- tcGenericNormaliseFamInst fun ty1
236 ; return (mkNoteTyCoI note coi, NoteTy note nty1)
238 tcGenericNormaliseFamInst fun ty@(TyVarTy tv)
240 = do { traceTc (text "tcGenericNormaliseFamInst" <+> ppr ty)
241 ; res <- lookupTcTyVar tv
244 do { maybe_ty' <- fun ty
246 Nothing -> return (IdCo, ty)
248 do { (coi2, ty'') <- tcGenericNormaliseFamInst fun ty'
249 ; return (ACo co1 `mkTransCoI` coi2, ty'')
252 IndirectTv ty' -> tcGenericNormaliseFamInst fun ty'
256 tcGenericNormaliseFamInst fun (PredTy predty)
257 = do { (coi, pred') <- tcGenericNormaliseFamInstPred fun predty
258 ; return (coi, PredTy pred') }
260 ---------------------------------
261 tcGenericNormaliseFamInstPred :: (TcType -> TcM (Maybe (TcType,Coercion)))
263 -> TcM (CoercionI, TcPredType)
265 tcGenericNormaliseFamInstPred fun (ClassP cls tys)
266 = do { (cois, tys')<- mapAndUnzipM (tcGenericNormaliseFamInst fun) tys
267 ; return (mkClassPPredCoI cls tys' cois, ClassP cls tys')
269 tcGenericNormaliseFamInstPred fun (IParam ipn ty)
270 = do { (coi, ty') <- tcGenericNormaliseFamInst fun ty
271 ; return $ (mkIParamPredCoI ipn coi, IParam ipn ty')
273 tcGenericNormaliseFamInstPred fun (EqPred ty1 ty2)
274 = do { (coi1, ty1') <- tcGenericNormaliseFamInst fun ty1
275 ; (coi2, ty2') <- tcGenericNormaliseFamInst fun ty2
276 ; return (mkEqPredCoI ty1' coi1 ty2' coi2, EqPred ty1' ty2') }
280 %************************************************************************
282 \section{Normalisation of equality constraints}
284 %************************************************************************
286 Note [Inconsistencies in equality constraints]
287 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
288 We guarantee that we raise an error if we discover any inconsistencies (i.e.,
289 equalities that if presented to the unifer in TcUnify would result in an
290 error) during normalisation of wanted constraints. This is especially so that
291 we don't solve wanted constraints under an inconsistent given set. In
292 particular, we don't want to permit signatures, such as
294 bad :: (Int ~ Bool => Int) -> a -> a
297 normaliseGivenEqs :: [Inst] -> TcM ([Inst], TcM ())
298 normaliseGivenEqs givens
299 = do { traceTc (text "normaliseGivenEqs <-" <+> ppr givens)
300 ; (result, deSkolem) <-
301 rewriteToFixedPoint (Just ("(SkolemOccurs)", skolemOccurs))
302 [ ("(ZONK)", dontRerun $ zonkInsts)
303 , ("(TRIVIAL)", dontRerun $ trivialRule)
304 , ("(DECOMP)", decompRule)
306 , ("(SUBST)", substRule) -- incl. occurs check
308 ; traceTc (text "normaliseGivenEqs ->" <+> ppr result)
309 ; return (result, deSkolem)
314 normaliseWantedEqs :: [Inst] -> TcM [Inst]
315 normaliseWantedEqs insts
316 = do { traceTc (text "normaliseWantedEqs <-" <+> ppr insts)
317 ; result <- liftM fst $ rewriteToFixedPoint Nothing
318 [ ("(ZONK)", dontRerun $ zonkInsts)
319 , ("(TRIVIAL)", dontRerun $ trivialRule)
320 , ("(DECOMP)", decompRule)
322 , ("(UNIFY)", unifyMetaRule) -- incl. occurs check
323 , ("(SUBST)", substRule) -- incl. occurs check
325 ; traceTc (text "normaliseWantedEqs ->" <+> ppr result)
331 %************************************************************************
333 \section{Solving of wanted constraints with respect to a given set}
335 %************************************************************************
337 The set of given equalities must have been normalised already.
340 solveWantedEqs :: [Inst] -- givens
342 -> TcM [Inst] -- irreducible wanteds
343 solveWantedEqs givens wanteds
344 = do { traceTc $ text "solveWantedEqs <-" <+> ppr wanteds <+> text "with" <+>
346 ; result <- liftM fst $ rewriteToFixedPoint Nothing
347 [ ("(ZONK)", dontRerun $ zonkInsts)
348 , ("(TRIVIAL)", dontRerun $ trivialRule)
349 , ("(DECOMP)", decompRule)
351 , ("(GIVEN)", substGivens givens) -- incl. occurs check
352 , ("(UNIFY)", unifyMetaRule) -- incl. occurs check
354 ; traceTc (text "solveWantedEqs ->" <+> ppr result)
358 -- Use `substInst' with every given on all the wanteds.
359 substGivens :: [Inst] -> [Inst] -> TcM ([Inst], Bool)
360 substGivens [] wanteds = return (wanteds, False)
361 substGivens (g:gs) wanteds
362 = do { (wanteds1, changed1) <- substGivens gs wanteds
363 ; (wanteds2, changed2) <- substInst g wanteds1
364 ; return (wanteds2, changed1 || changed2)
369 %************************************************************************
371 \section{Normalisation of non-equality dictionaries}
373 %************************************************************************
376 normaliseGivenDicts, normaliseWantedDicts
377 :: [Inst] -- given equations
378 -> [Inst] -- dictionaries
379 -> TcM ([Inst],TcDictBinds)
381 normaliseGivenDicts eqs dicts = normalise_dicts eqs dicts False
382 normaliseWantedDicts eqs dicts = normalise_dicts eqs dicts True
385 :: [Inst] -- given equations
386 -> [Inst] -- dictionaries
387 -> Bool -- True <=> the dicts are wanted
388 -- Fals <=> they are given
389 -> TcM ([Inst],TcDictBinds)
390 normalise_dicts given_eqs dicts is_wanted
391 = do { traceTc $ text "normalise???Dicts <-" <+> ppr dicts <+>
392 text "with" <+> ppr given_eqs
393 ; (dicts0, binds0) <- normaliseInsts is_wanted dicts
394 ; (dicts1, binds1) <- substEqInDictInsts given_eqs dicts0
395 ; let binds01 = binds0 `unionBags` binds1
396 ; if isEmptyBag binds1
397 then return (dicts1, binds01)
398 else do { (dicts2, binds2) <- normaliseGivenDicts given_eqs dicts1
399 ; return (dicts2, binds01 `unionBags` binds2) } }
403 %************************************************************************
405 \section{Normalisation rules and iterative rule application}
407 %************************************************************************
409 We have three kinds of normalising rewrite rules:
411 (1) Normalisation rules that rewrite a set of insts and return a flag indicating
412 whether any changes occurred during rewriting that necessitate re-running
413 the current rule set.
415 (2) Precondition rules that rewrite a set of insts and return a monadic action
416 that reverts the effect of preconditioning.
418 (3) Idempotent normalisation rules that never require re-running the rule set.
421 type RewriteRule = [Inst] -> TcM ([Inst], Bool) -- rewrite, maybe re-run
422 type PrecondRule = [Inst] -> TcM ([Inst], TcM ()) -- rewrite, revertable
423 type IdemRewriteRule = [Inst] -> TcM [Inst] -- rewrite, don't re-run
425 type NamedRule = (String, RewriteRule) -- rule with description
426 type NamedPreRule = (String, PrecondRule) -- precond with desc
429 Template lifting idempotent rules to full rules (which can be put into a rule
433 dontRerun :: IdemRewriteRule -> RewriteRule
434 dontRerun rule insts = liftM addFalse $ rule insts
436 addFalse x = (x, False)
439 The following function applies a set of rewrite rules until a fixed point is
440 reached; i.e., none of the `RewriteRule's require re-running the rule set.
441 Optionally, there may be a pre-conditing rule that is applied before any other
442 rules are applied and before the rule set is re-run.
444 The result is the set of rewritten (i.e., normalised) insts and, in case of a
445 pre-conditing rule, a monadic action that reverts the effects of
446 pre-conditioning - specifically, this is removing introduced skolems.
449 rewriteToFixedPoint :: Maybe NamedPreRule -- optional preconditioning rule
450 -> [NamedRule] -- rule set
451 -> [Inst] -- insts to rewrite
452 -> TcM ([Inst], TcM ())
453 rewriteToFixedPoint precondRule rules insts
454 = completeRewrite (return ()) precondRule insts
456 completeRewrite :: TcM () -> Maybe NamedPreRule -> [Inst]
457 -> TcM ([Inst], TcM ())
458 completeRewrite dePrecond (Just (precondName, precond)) insts
459 = do { traceTc $ text precondName <+> text " <- " <+> ppr insts
460 ; (insts', dePrecond') <- precond insts
461 ; traceTc $ text precondName <+> text " -> " <+> ppr insts'
462 ; tryRules (dePrecond >> dePrecond') rules insts'
464 completeRewrite dePrecond Nothing insts
465 = tryRules dePrecond rules insts
467 tryRules dePrecond _ [] = return ([] , dePrecond)
468 tryRules dePrecond [] insts = return (insts, dePrecond)
469 tryRules dePrecond ((name, rule):rules) insts
470 = do { traceTc $ text name <+> text " <- " <+> ppr insts
471 ; (insts', rerun) <- rule insts
472 ; traceTc $ text name <+> text " -> " <+> ppr insts'
473 ; if rerun then completeRewrite dePrecond precondRule insts'
474 else tryRules dePrecond rules insts'
479 %************************************************************************
481 \section{Different forms of Inst rewrite rules}
483 %************************************************************************
485 Splitting of non-terminating given constraints: skolemOccurs
486 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
487 This is a preconditioning rule exclusively applied to given constraints.
488 Moreover, its rewriting is only temporary, as it is undone by way of
489 side-effecting mutable type variables after simplification and constraint
490 entailment has been completed.
492 This version is an (attempt at, yet unproven, an) *unflattened* version of
493 the SubstL-Ev completion rule.
495 The above rule is essential to catch non-terminating rules that cannot be
496 oriented properly, like
500 a ~ [G a] , where a is a skolem tyvar
502 The left-to-right orientiation is not suitable because it does not
503 terminate. The right-to-left orientation is not suitable because it
504 does not have a type-function on the left. This is undesirable because
505 it would hide information. E.g. assume
509 then rewriting C [G (F a)] to C (F a) is bad because we cannot now
510 see that the C [x] instance applies.
512 The rule also caters for badly-oriented rules of the form:
516 for which other solutions are possible, but this one will do too.
520 co : ty1 ~ ty2{F ty1}
523 sym (F co) : F ty2{b} ~ b
524 where b is a fresh skolem variable
526 We also cater for the symmetric situation *if* the rule cannot be used as a
527 left-to-right rewrite rule.
529 We also return an action (b := ty1) which is used to eliminate b
530 after the dust of normalisation with the completed rewrite system
533 A subtle point of this transformation is that both coercions in the results
534 are strictly speaking incorrect. However, they are correct again after the
535 action {B := ty1} has removed the skolem again. This happens immediately
536 after constraint entailment has been checked; ie, code outside of the
537 simplification and entailment checking framework will never see these
538 temporarily incorrect coercions.
540 NB: We perform this transformation for multiple occurences of ty1 under one
541 or multiple family applications on the left-hand side at once (ie, the
542 rule doesn't need to be applied multiple times at a single inst). As a
543 result we can get two or more insts back.
545 Note [skolemOccurs loop]
546 ~~~~~~~~~~~~~~~~~~~~~~~~
547 You might think that under
550 type instance F [a] = [F a]
554 foo :: (F [a] ~ a) => a
556 will get us into a loop. However, this is *not* the case. Here is why:
567 F [b<tau>] ~ b<tau> , with b := F a
572 [F b<tau>] ~ b<tau> , with b := F a
574 At this point (SkolemOccurs) does *not* apply anymore, as
578 is not used as a rewrite rule. The variable b<tau> is not a skolem (cf
581 (The regression test indexed-types/should_compile/Simple20 checks that the
582 described property of the system does not change.)
585 skolemOccurs :: PrecondRule
587 = do { (instss, undoSkolems) <- mapAndUnzipM oneSkolemOccurs insts
588 ; return (concat instss, sequence_ undoSkolems)
592 = ASSERT( isEqInst inst )
593 case eqInstToRewrite inst of
594 Just (rewrite, swapped) -> breakRecursion rewrite swapped
595 Nothing -> return ([inst], return ())
597 -- inst is an elementary rewrite rule, check whether we need to break
599 breakRecursion (Rewrite pat body _) swapped
601 -- skolemOccurs does not apply, leave as is
603 = do { traceTc $ text "oneSkolemOccurs: no tys to lift out"
604 ; return ([inst], return ())
607 -- recursive occurence of pat in body under a type family application
609 = do { traceTc $ text "oneSkolemOccurs[TLO]:" <+> ppr tysToLiftOut
610 ; skTvs <- mapM (newMetaTyVar TauTv . typeKind) tysToLiftOut
611 ; let skTvs_tysTLO = zip skTvs tysToLiftOut
612 insertSkolems = return . replace skTvs_tysTLO
613 ; (_, body') <- tcGenericNormaliseFamInst insertSkolems body
614 ; inst' <- if swapped then mkEqInst (EqPred body' pat) co
615 else mkEqInst (EqPred pat body') co
616 -- ensure to reconstruct the inst in the
617 -- original orientation
618 ; traceTc $ text "oneSkolemOccurs[inst']:" <+> ppr inst'
619 ; (insts, undoSk) <- mapAndUnzipM (mkSkolemInst inst')
621 ; return (inst':insts, sequence_ undoSk)
624 co = eqInstCoercion inst
626 -- all subtypes that are (1) type family instances and (2) contain
627 -- the lhs type as part of the type arguments of the type family
629 tysToLiftOut = [mkTyConApp tc tys | (tc, tys) <- tyFamInsts body
630 , any (pat `tcPartOfType`) tys]
632 replace :: [(TcTyVar, Type)] -> Type -> Maybe (Type, Coercion)
633 replace [] _ = Nothing
634 replace ((skTv, tyTLO):rest) ty
635 | tyTLO `tcEqType` ty = Just (mkTyVarTy skTv, undefined)
636 | otherwise = replace rest ty
638 -- create the EqInst for the equality determining the skolem and a
639 -- TcM action undoing the skolem introduction
640 mkSkolemInst inst' (skTv, tyTLO)
641 = do { (co, tyLiftedOut) <- tcEqInstNormaliseFamInst inst' tyTLO
642 ; inst <- mkEqInst (EqPred tyLiftedOut (mkTyVarTy skTv))
643 (mkGivenCo $ mkSymCoercion (fromACo co))
644 -- co /= IdCo due to construction of inst'
645 ; return (inst, writeMetaTyVar skTv tyTLO)
650 Removal of trivial equalities: trivialRule
651 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
652 The following rules exploits the reflexivity of equality:
660 trivialRule :: IdemRewriteRule
662 = liftM catMaybes $ mappM trivial insts
665 | ASSERT( isEqInst inst )
667 = do { eitherEqInst inst
668 (\cotv -> writeMetaTyVar cotv ty1)
675 (ty1,ty2) = eqInstTys inst
679 Decomposition of data type constructors: decompRule
680 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
681 Whenever, the same *data* constructors occurs on both sides of an equality, we
682 can decompose as in standard unification.
687 g21 : c1 ~ d1, ..., g2n : cn ~ dn
690 Works also for the case where T is actually an application of a type family
691 constructor to a set of types, provided the applications on both sides of the
692 ~ are identical; see also Note [OpenSynTyCon app] in TcUnify.
694 We guarantee to raise an error for any inconsistent equalities;
695 cf Note [Inconsistencies in equality constraints].
698 decompRule :: RewriteRule
700 = do { (insts, changed) <- mapAndUnzipM decomp insts
701 ; return (concat insts, or changed)
705 = ASSERT( isEqInst inst )
708 (ty1,ty2) = eqInstTys inst
710 | Just ty1' <- tcView ty1 = go ty1' ty2
711 | Just ty2' <- tcView ty2 = go ty1 ty2'
713 go (TyConApp con1 tys1) (TyConApp con2 tys2)
714 | con1 == con2 && identicalHead
715 = mkArgInsts (mkTyConApp con1) tys1 tys2
717 | con1 /= con2 && not (isOpenSynTyCon con1 || isOpenSynTyCon con2)
718 -- not matching data constructors (of any flavour) are bad news
719 = eqInstMisMatch inst
722 (idxTys1, _) = splitAt n tys1
723 (idxTys2, _) = splitAt n tys2
724 identicalHead = not (isOpenSynTyCon con1) ||
725 idxTys1 `tcEqTypes` idxTys2
727 go (FunTy fun1 arg1) (FunTy fun2 arg2)
728 = mkArgInsts (\[funCo, argCo] -> mkFunTy funCo argCo) [fun1, arg1]
731 -- Applications need a bit of care!
732 -- They can match FunTy and TyConApp, so use splitAppTy_maybe
734 | Just (s2, t2) <- tcSplitAppTy_maybe ty2
735 = mkArgInsts (\[s, t] -> mkAppTy s t) [s1, t1] [s2, t2]
739 | Just (s1, t1) <- tcSplitAppTy_maybe ty1
740 = mkArgInsts (\[s, t] -> mkAppTy s t) [s1, t1] [s2, t2]
742 -- We already covered all the consistent cases of rigid types on both
743 -- sides; so, if we see two rigid types here, we discovered an
746 | isRigid ty1 && isRigid ty2
747 = eqInstMisMatch inst
749 -- We can neither assert consistency nor inconsistency => defer
750 go _ _ = return ([inst], False)
752 isRigid (TyConApp con _) = not (isOpenSynTyCon con)
753 isRigid (FunTy _ _) = True
754 isRigid (AppTy _ _) = True
757 -- Create insts for matching argument positions (ie, the bit after
758 -- '>-->' in the rule description above)
759 mkArgInsts con tys1 tys2
760 = do { cos <- eitherEqInst inst
761 -- old_co := Con1 cos
763 do { cotvs <- zipWithM newMetaCoVar tys1 tys2
764 ; let cos = map mkTyVarTy cotvs
765 ; writeMetaTyVar old_covar (con cos)
766 ; return $ map mkWantedCo cotvs
768 -- co_i := Con_i old_co
770 return $ map mkGivenCo $
771 mkRightCoercions (length tys1) old_co)
772 ; insts <- zipWithM mkEqInst (zipWith EqPred tys1 tys2) cos
773 ; traceTc (text "decomp identicalHead" <+> ppr insts)
774 ; return (insts, not $ null insts)
779 Rewriting with type instances: topRule
780 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
781 We use (toplevel) type instances to normalise both sides of equalities.
785 >--> co1 :: t ~ t' / co2 :: s ~ s'
787 g1 := co1 * g2 * sym co2
790 topRule :: RewriteRule
792 = do { (insts, changed) <- mapAndUnzipM top insts
793 ; return (insts, or changed)
797 = ASSERT( isEqInst inst )
798 do { (coi1, ty1') <- tcNormaliseFamInst ty1
799 ; (coi2, ty2') <- tcNormaliseFamInst ty2
800 ; case (coi1, coi2) of
801 (IdCo, IdCo) -> return (inst, False)
805 -- old_co = co1 * new_co * sym co2
807 do { new_cotv <- newMetaCoVar ty1' ty2'
808 ; let new_co = mkTyVarTy new_cotv
809 old_coi = coi1 `mkTransCoI`
810 ACo new_co `mkTransCoI`
812 ; writeMetaTyVar old_covar (fromACo old_coi)
813 ; return $ mkWantedCo new_cotv
815 -- new_co = sym co1 * old_co * co2
820 mkSymCoI coi1 `mkTransCoI`
821 ACo old_co `mkTransCoI` coi2)
822 ; new_inst <- mkEqInst (EqPred ty1' ty2') wg_co
823 ; return (new_inst, True)
827 (ty1,ty2) = eqInstTys inst
831 Rewriting with equalities: substRule
832 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
833 From a set of insts, use all insts that can be read as rewrite rules to
834 rewrite the types in all other insts.
838 forall g1 : s1{F c} ~ s2{F c}
841 g1 := s1{g} * g2 * sym s2{g} <=> g2 := sym s1{g} * g1 * s2{g}
843 Alternatively, the rewrite rule may have the form (g : a ~ t).
845 To avoid having to swap rules of the form (g : t ~ F c) and (g : t ~ a),
846 where t is neither a variable nor a type family application, we use them for
847 rewriting from right-to-left. However, it is crucial to only apply rules
848 from right-to-left if they cannot be used left-to-right.
850 The workhorse is substInst, which performs an occurs check before actually
851 using an equality for rewriting. If the type pattern occurs in the type we
852 substitute for the pattern, normalisation would diverge.
855 substRule :: RewriteRule
856 substRule insts = tryAllInsts insts []
858 -- for every inst check whether it can be used to rewrite the others
859 -- (we make an effort to keep the insts in order; it makes debugging
861 tryAllInsts [] triedInsts = return (reverse triedInsts, False)
862 tryAllInsts (inst:insts) triedInsts
863 = do { (insts', changed) <- substInst inst (reverse triedInsts ++ insts)
864 ; if changed then return (insertAt (length triedInsts) inst insts',
866 else tryAllInsts insts (inst:triedInsts)
869 insertAt n x xs = let (xs1, xs2) = splitAt n xs
872 -- Use the given inst as a rewrite rule to normalise the insts in the second
873 -- argument. Don't do anything if the inst cannot be used as a rewrite rule,
874 -- but do apply it right-to-left, if possible, and if it cannot be used
877 substInst :: Inst -> [Inst] -> TcM ([Inst], Bool)
879 = case eqInstToRewrite inst of
880 Just (rewrite, _) -> substEquality rewrite insts
881 Nothing -> return (insts, False)
883 substEquality :: Rewrite -- elementary rewrite
884 -> [Inst] -- insts to rewrite
885 -> TcM ([Inst], Bool)
886 substEquality eqRule@(Rewrite pat rhs _) insts
887 | pat `tcPartOfType` rhs -- occurs check!
888 = occurCheckErr pat rhs
890 = do { (insts', changed) <- mapAndUnzipM substOne insts
891 ; return (insts', or changed)
895 = ASSERT( isEqInst inst )
896 do { (coi1, ty1') <- tcEqRuleNormaliseFamInst eqRule ty1
897 ; (coi2, ty2') <- tcEqRuleNormaliseFamInst eqRule ty2
898 ; case (coi1, coi2) of
899 (IdCo, IdCo) -> return (inst, False)
903 -- old_co := co1 * new_co * sym co2
905 do { new_cotv <- newMetaCoVar ty1' ty2'
906 ; let new_co = mkTyVarTy new_cotv
907 old_coi = coi1 `mkTransCoI`
908 ACo new_co `mkTransCoI`
910 ; writeMetaTyVar old_covar (fromACo old_coi)
911 ; return $ mkWantedCo new_cotv
913 -- new_co := sym co1 * old_co * co2
918 mkSymCoI coi1 `mkTransCoI`
919 ACo old_co `mkTransCoI` coi2)
920 ; new_inst <- mkEqInst (EqPred ty1' ty2') gw_co
921 ; return (new_inst, True)
925 (ty1,ty2) = eqInstTys inst
929 Instantiate meta variables: unifyMetaRule
930 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
931 If an equality equates a meta type variable with a type, we simply instantiate
940 Meta variables can only appear in wanted constraints, and this rule should
941 only be applied to wanted constraints. We also know that t definitely is
942 distinct from alpha (as the trivialRule) has been run on the insts beforehand.
944 NB: We cannot assume that meta tyvars are empty. They may have been updated
945 by another inst in the currently processed wanted list. We need to be very
946 careful when updateing type variables (see TcUnify.uUnfilledVar), but at least
947 we know that we have no boxes. It's unclear that it would be an advantage to
948 common up the code in TcUnify and the code below. Firstly, we don't want
949 calls to TcUnify.defer_unification here, and secondly, TcUnify import the
950 current module, so we would have to move everything here (Yuk!) or to
951 TcMType. Besides, the code here is much simpler due to the lack of boxes.
954 unifyMetaRule :: RewriteRule
956 = do { (insts', changed) <- mapAndUnzipM unifyMeta insts
957 ; return (concat insts', or changed)
961 = ASSERT( isEqInst inst )
963 (fromWantedCo "unifyMetaRule" $ eqInstCoercion inst)
965 (ty1,ty2) = eqInstTys inst
967 | Just ty1' <- tcView ty1 = go ty1' ty2 cotv
968 | Just ty2' <- tcView ty2 = go ty1 ty2' cotv
971 , isMetaTyVar tv1 = do { lookupTV <- lookupTcTyVar tv1
972 ; uMeta False tv1 lookupTV ty2 cotv
975 , isMetaTyVar tv2 = do { lookupTV <- lookupTcTyVar tv2
976 ; uMeta True tv2 lookupTV ty1 cotv
978 | otherwise = return ([inst], False)
980 -- meta variable has been filled already
981 -- => ignore this inst (we'll come around again, after zonking)
982 uMeta _swapped _tv (IndirectTv _) _ty _cotv
983 = return ([inst], False)
985 -- signature skolem meets non-variable type
987 uMeta _swapped _tv (DoneTv (MetaTv (SigTv _) _)) ty _cotv
989 = return ([inst], False)
991 -- type variable meets type variable
992 -- => check that tv2 hasn't been updated yet and choose which to update
993 uMeta swapped tv1 (DoneTv details1) (TyVarTy tv2) cotv
994 = do { lookupTV2 <- lookupTcTyVar tv2
996 IndirectTv ty -> uMeta swapped tv1 (DoneTv details1) ty cotv
998 uMetaVar swapped tv1 details1 tv2 details2 cotv
1001 -- updatable meta variable meets non-variable type
1002 -- => occurs check, monotype check, and kinds match check, then update
1003 uMeta swapped tv (DoneTv (MetaTv _ ref)) ty cotv
1004 = do { mb_ty' <- checkTauTvUpdate tv ty -- occurs + monotype check
1006 Nothing -> return ([inst], False) -- tv occurs in faminst
1008 do { checkUpdateMeta swapped tv ref ty' -- update meta var
1009 ; writeMetaTyVar cotv ty' -- update co var
1014 uMeta _ _ _ _ _ = panic "uMeta"
1016 -- meta variable meets skolem
1018 uMetaVar swapped tv1 (MetaTv _ ref) tv2 (SkolemTv _) cotv
1019 = do { checkUpdateMeta swapped tv1 ref (mkTyVarTy tv2)
1020 ; writeMetaTyVar cotv (mkTyVarTy tv2)
1024 -- meta variable meets meta variable
1025 -- => be clever about which of the two to update
1026 -- (from TcUnify.uUnfilledVars minus boxy stuff)
1027 uMetaVar swapped tv1 (MetaTv info1 ref1) tv2 (MetaTv info2 ref2) cotv
1028 = do { case (info1, info2) of
1029 -- Avoid SigTvs if poss
1030 (SigTv _, _ ) | k1_sub_k2 -> update_tv2
1031 (_, SigTv _) | k2_sub_k1 -> update_tv1
1033 (_, _) | k1_sub_k2 -> if k2_sub_k1 && nicer_to_update_tv1
1034 then update_tv1 -- Same kinds
1036 | k2_sub_k1 -> update_tv1
1037 | otherwise -> kind_err
1038 -- Update the variable with least kind info
1039 -- See notes on type inference in Kind.lhs
1040 -- The "nicer to" part only applies if the two kinds are the same,
1041 -- so we can choose which to do.
1043 ; writeMetaTyVar cotv (mkTyVarTy tv2)
1047 -- Kinds should be guaranteed ok at this point
1048 update_tv1 = updateMeta tv1 ref1 (mkTyVarTy tv2)
1049 update_tv2 = updateMeta tv2 ref2 (mkTyVarTy tv1)
1051 kind_err = addErrCtxtM (unifyKindCtxt swapped tv1 (mkTyVarTy tv2)) $
1052 unifyKindMisMatch k1 k2
1056 k1_sub_k2 = k1 `isSubKind` k2
1057 k2_sub_k1 = k2 `isSubKind` k1
1059 nicer_to_update_tv1 = isSystemName (Var.varName tv1)
1060 -- Try to update sys-y type variables in preference to ones
1061 -- gotten (say) by instantiating a polymorphic function with
1062 -- a user-written type sig
1064 uMetaVar _ _ _ _ _ _ = panic "uMetaVar"
1068 %************************************************************************
1070 \section{Normalisation of Insts}
1072 %************************************************************************
1074 Normalises a set of dictionaries relative to a set of given equalities (which
1075 are interpreted as rewrite rules). We only consider given equalities of the
1080 where F is a type family.
1083 substEqInDictInsts :: [Inst] -- given equalities (used as rewrite rules)
1084 -> [Inst] -- dictinaries to be normalised
1085 -> TcM ([Inst], TcDictBinds)
1086 substEqInDictInsts eqInsts dictInsts
1087 = do { traceTc (text "substEqInDictInst <-" <+> ppr dictInsts)
1089 foldlM rewriteWithOneEquality (dictInsts, emptyBag) eqInsts
1090 ; traceTc (text "substEqInDictInst ->" <+> ppr dictInsts')
1094 -- (1) Given equality of form 'F ts ~ t' or 'a ~ t': use for rewriting
1095 rewriteWithOneEquality (dictInsts, dictBinds)
1096 eqInst@(EqInst {tci_left = pattern,
1097 tci_right = target})
1098 | isOpenSynTyConApp pattern || isTyVarTy pattern
1099 = do { (dictInsts', moreDictBinds) <-
1100 genericNormaliseInsts True {- wanted -} applyThisEq dictInsts
1101 ; return (dictInsts', dictBinds `unionBags` moreDictBinds)
1104 applyThisEq = tcGenericNormaliseFamInstPred (return . matchResult)
1106 -- rewrite in case of an exact match
1107 matchResult ty | tcEqType pattern ty = Just (target, eqInstType eqInst)
1108 | otherwise = Nothing
1110 -- (2) Given equality has the wrong form: ignore
1111 rewriteWithOneEquality (dictInsts, dictBinds) _not_a_rewrite_rule
1112 = return (dictInsts, dictBinds)
1116 Take a bunch of Insts (not EqInsts), and normalise them wrt the top-level
1117 type-function equations, where
1119 (norm_insts, binds) = normaliseInsts is_wanted insts
1122 = True, (binds + norm_insts) defines insts (wanteds)
1123 = False, (binds + insts) defines norm_insts (givens)
1125 Ie, in the case of normalising wanted dictionaries, we use the normalised
1126 dictionaries to define the originally wanted ones. However, in the case of
1127 given dictionaries, we use the originally given ones to define the normalised
1131 normaliseInsts :: Bool -- True <=> wanted insts
1132 -> [Inst] -- wanted or given insts
1133 -> TcM ([Inst], TcDictBinds) -- normalised insts and bindings
1134 normaliseInsts isWanted insts
1135 = genericNormaliseInsts isWanted tcNormaliseFamInstPred insts
1137 genericNormaliseInsts :: Bool -- True <=> wanted insts
1138 -> (TcPredType -> TcM (CoercionI, TcPredType))
1140 -> [Inst] -- wanted or given insts
1141 -> TcM ([Inst], TcDictBinds) -- normalised insts & binds
1142 genericNormaliseInsts isWanted fun insts
1143 = do { (insts', binds) <- mapAndUnzipM (normaliseOneInst isWanted fun) insts
1144 ; return (insts', unionManyBags binds)
1147 normaliseOneInst isWanted fun
1148 dict@(Dict {tci_pred = pred,
1150 = do { traceTc $ text "genericNormaliseInst <-" <+> ppr dict
1151 ; (coi, pred') <- fun pred
1155 do { traceTc $ text "genericNormaliseInst ->" <+> ppr dict
1156 ; return (dict, emptyBag)
1158 -- don't use pred' in this case; otherwise, we get
1159 -- more unfolded closed type synonyms in error messages
1161 do { -- an inst for the new pred
1162 ; dict' <- newDictBndr loc pred'
1163 -- relate the old inst to the new one
1164 -- target_dict = source_dict `cast` st_co
1165 ; let (target_dict, source_dict, st_co)
1166 | isWanted = (dict, dict', mkSymCoercion co)
1167 | otherwise = (dict', dict, co)
1169 -- co :: dict ~ dict'
1170 -- hence, if isWanted
1171 -- dict = dict' `cast` sym co
1173 -- dict' = dict `cast` co
1174 expr = HsVar $ instToId source_dict
1175 cast_expr = HsWrap (WpCo st_co) expr
1176 rhs = L (instLocSpan loc) cast_expr
1177 binds = instToDictBind target_dict rhs
1178 -- return the new inst
1179 ; traceTc $ text "genericNormaliseInst ->" <+> ppr dict'
1180 ; return (dict', binds)
1184 -- TOMDO: What do we have to do about ImplicInst, Method, and LitInst??
1185 normaliseOneInst _isWanted _fun inst
1186 = do { inst' <- zonkInst inst
1187 ; return (inst', emptyBag)
1192 %************************************************************************
1196 %************************************************************************
1198 The infamous couldn't match expected type soandso against inferred type
1199 somethingdifferent message.
1202 eqInstMisMatch :: Inst -> TcM a
1204 = ASSERT( isEqInst inst )
1205 setErrCtxt ctxt $ failWithMisMatch ty_act ty_exp
1207 (ty_act, ty_exp) = eqInstTys inst
1208 InstLoc _ _ ctxt = instLoc inst
1210 -----------------------
1211 failWithMisMatch :: TcType -> TcType -> TcM a
1212 -- Generate the message when two types fail to match,
1213 -- going to some trouble to make it helpful.
1214 -- The argument order is: actual type, expected type
1215 failWithMisMatch ty_act ty_exp
1216 = do { env0 <- tcInitTidyEnv
1217 ; ty_exp <- zonkTcType ty_exp
1218 ; ty_act <- zonkTcType ty_act
1219 ; failWithTcM (misMatchMsg env0 (ty_act, ty_exp))
1222 misMatchMsg :: TidyEnv -> (TcType, TcType) -> (TidyEnv, SDoc)
1223 misMatchMsg env0 (ty_act, ty_exp)
1224 = let (env1, pp_exp, extra_exp) = ppr_ty env0 ty_exp
1225 (env2, pp_act, extra_act) = ppr_ty env1 ty_act
1226 msg = sep [sep [ptext SLIT("Couldn't match expected type") <+> pp_exp,
1228 ptext SLIT("against inferred type") <+> pp_act],
1229 nest 2 (extra_exp $$ extra_act)]
1234 ppr_ty :: TidyEnv -> TcType -> (TidyEnv, SDoc, SDoc)
1236 = let (env1, tidy_ty) = tidyOpenType env ty
1237 (env2, extra) = ppr_extra env1 tidy_ty
1239 (env2, quotes (ppr tidy_ty), extra)
1241 -- (ppr_extra env ty) shows extra info about 'ty'
1242 ppr_extra :: TidyEnv -> Type -> (TidyEnv, SDoc)
1243 ppr_extra env (TyVarTy tv)
1244 | isTcTyVar tv && (isSkolemTyVar tv || isSigTyVar tv) && not (isUnk tv)
1245 = (env1, pprSkolTvBinding tv1)
1247 (env1, tv1) = tidySkolemTyVar env tv
1249 ppr_extra env _ty = (env, empty) -- Normal case