+-- |Normalise the given type as far as possible with toplevel equalities.
+-- This results in a coercion witnessing the type equality, in addition to the
+-- normalised type.
+--
+tcNormaliseFamInst :: TcType -> TcM (CoercionI, TcType)
+tcNormaliseFamInst = tcGenericNormaliseFamInst tcUnfoldSynFamInst
+
+tcNormaliseFamInstPred :: TcPredType -> TcM (CoercionI, TcPredType)
+tcNormaliseFamInstPred = tcGenericNormaliseFamInstPred tcUnfoldSynFamInst
+\end{code}
+
+%************************************************************************
+%* *
+ Equality Configurations
+%* *
+%************************************************************************
+
+We maintain normalised equalities together with the skolems introduced as
+intermediates during flattening of equalities.
+
+!!!TODO: Do we really need to keep track of the skolem variables? They are at
+the moment not used in instantiateAndExtract, but it is hard to say until we
+know exactly how finalisation will fianlly look like.
+
+\begin{code}
+-- |Configuration of normalised equalities used during solving.
+--
+data EqConfig = EqConfig { eqs :: [RewriteInst]
+ , skolems :: TyVarSet
+ }
+
+addSkolems :: EqConfig -> TyVarSet -> EqConfig
+addSkolems eqCfg newSkolems
+ = eqCfg {skolems = skolems eqCfg `unionVarSet` newSkolems}
+
+addEq :: EqConfig -> RewriteInst -> EqConfig
+addEq eqCfg eq = eqCfg {eqs = eq : eqs eqCfg}
+\end{code}
+
+The set of operations on an equality configuration. We obtain the initialise
+configuration by normalisation ('normaliseEqs'), solve the equalities by
+propagation ('propagateEqs'), and eventually finalise the configuration when
+no further propoagation is possible.
+
+!!!TODO: Eventually, normalisation of dictionaries and dictionary
+simplification should be included in propagation.
+
+\begin{code}
+-- |Turn a set of equalities into an equality configuration for solving.
+--
+-- Precondition: The Insts are zonked.
+--
+normaliseEqs :: [Inst] -> TcM EqConfig
+normaliseEqs eqs
+ = do { (eqss, skolemss) <- mapAndUnzipM normEqInst eqs
+ ; return $ EqConfig { eqs = concat eqss
+ , skolems = unionVarSets skolemss
+ }
+ }
+
+-- |Solves the equalities as far as possible by applying propagation rules.
+--
+propagateEqs :: EqConfig -> TcM EqConfig
+propagateEqs eqCfg@(EqConfig {eqs = todoEqs})
+ = propagate todoEqs (eqCfg {eqs = []})
+
+-- |Finalise a set of equalities after propagation. The Boolean value is
+-- `True' iff any flexible variables, except those introduced by flattening
+-- (i.e., those in the `skolems' component of the argument) where instantiated.
+-- The returned set of instances are all residual wanteds.
+--
+finaliseEqs :: EqConfig -> TcM ([Inst], Bool)
+finaliseEqs (EqConfig {eqs = eqs, skolems = skolems})
+ = do { eqs' <- substitute eqs
+ ; instantiateAndExtract eqs' skolems
+ }
+
+-- |Normalise a set of class instances under a given equality configuration.
+-- Both the class instances and the equality configuration may change. The
+-- function returns 'Nothing' if neither changes.
+--
+normaliseDicts :: EqConfig -> [Inst] -> TcM (Maybe (EqConfig, [Inst]))
+normaliseDicts = error "TcTyFuns.normaliseDicts"
+\end{code}
+
+
+%************************************************************************
+%* *
+ Normalisation of equalities
+%* *
+%************************************************************************
+
+A normal equality is a properly oriented equality with associated coercion
+that contains at most one family equality (in its left-hand side) is oriented
+such that it may be used as a reqrite rule. It has one of the following two
+forms:
+
+(1) co :: F t1..tn ~ t (family equalities)
+(2) co :: x ~ t (variable equalities)
+
+Variable equalities fall again in two classes:
+
+(2a) co :: x ~ t, where t is *not* a variable, or
+(2b) co :: x ~ y, where x > y.
+
+The types t, t1, ..., tn may not contain any occurrences of synonym
+families. Moreover, in Forms (2) & (3), the left-hand side may not occur in
+the right-hand side, and the relation x > y is an arbitrary, but total order
+on type variables
+
+!!!TODO: We may need to keep track of swapping for error messages (and to
+re-orient on finilisation).
+
+\begin{code}
+data RewriteInst
+ = RewriteVar -- Form (2) above
+ { rwi_var :: TyVar -- may be rigid or flexible
+ , rwi_right :: TcType -- contains no synonym family applications
+ , rwi_co :: EqInstCo -- the wanted or given coercion
+ , rwi_loc :: InstLoc
+ , rwi_name :: Name -- no semantic significance (cf. TcRnTypes.EqInst)
+ }
+ | RewriteFam -- Forms (1) above
+ { rwi_fam :: TyCon -- synonym family tycon
+ , rwi_args :: [Type] -- contain no synonym family applications
+ , rwi_right :: TcType -- contains no synonym family applications
+ , rwi_co :: EqInstCo -- the wanted or given coercion
+ , rwi_loc :: InstLoc
+ , rwi_name :: Name -- no semantic significance (cf. TcRnTypes.EqInst)
+ }
+
+isWantedRewriteInst :: RewriteInst -> Bool
+isWantedRewriteInst = isWantedCo . rwi_co
+
+rewriteInstToInst :: RewriteInst -> Inst
+rewriteInstToInst eq@(RewriteVar {rwi_var = tv})
+ = EqInst
+ { tci_left = mkTyVarTy tv
+ , tci_right = rwi_right eq
+ , tci_co = rwi_co eq
+ , tci_loc = rwi_loc eq
+ , tci_name = rwi_name eq
+ }
+rewriteInstToInst eq@(RewriteFam {rwi_fam = fam, rwi_args = args})
+ = EqInst
+ { tci_left = mkTyConApp fam args
+ , tci_right = rwi_right eq
+ , tci_co = rwi_co eq
+ , tci_loc = rwi_loc eq
+ , tci_name = rwi_name eq
+ }
+\end{code}
+
+The following functions turn an arbitrary equality into a set of normal
+equalities.
+
+\begin{code}
+normEqInst :: Inst -> TcM ([RewriteInst], TyVarSet)
+normEqInst inst
+ = ASSERT( isEqInst inst )
+ go ty1 ty2 (eqInstCoercion inst)
+ where
+ (ty1, ty2) = eqInstTys inst
+
+ -- look through synonyms
+ go ty1 ty2 co | Just ty1' <- tcView ty1 = go ty1' ty2 co
+ go ty1 ty2 co | Just ty2' <- tcView ty2 = go ty1 ty2' co
+
+ -- left-to-right rule with type family head
+ go (TyConApp con args) ty2 co
+ | isOpenSynTyCon con
+ = mkRewriteFam con args ty2 co
+
+ -- right-to-left rule with type family head
+ go ty1 ty2@(TyConApp con args) co
+ | isOpenSynTyCon con
+ = do { co' <- mkSymEqInstCo co (ty2, ty1)
+ ; mkRewriteFam con args ty1 co'
+ }
+
+ -- no outermost family
+ go ty1 ty2 co
+ = do { (ty1', co1, ty1_eqs, ty1_skolems) <- flattenType inst ty1
+ ; (ty2', co2, ty2_eqs, ty2_skolems) <- flattenType inst ty2
+ ; let ty12_eqs = ty1_eqs ++ ty2_eqs
+ rewriteCo = co1 `mkTransCoercion` mkSymCoercion co2
+ eqTys = (ty1', ty2')
+ ; (co', ty12_eqs') <- adjustCoercions co rewriteCo eqTys ty12_eqs
+ ; eqs <- checkOrientation ty1' ty2' co' inst
+ ; return $ (eqs ++ ty12_eqs',
+ ty1_skolems `unionVarSet` ty2_skolems)
+ }
+
+ mkRewriteFam con args ty2 co
+ = do { (args', cargs, args_eqss, args_skolemss)
+ <- mapAndUnzip4M (flattenType inst) args
+ ; (ty2', co2, ty2_eqs, ty2_skolems) <- flattenType inst ty2
+ ; let rewriteCo = mkTyConApp con cargs `mkTransCoercion`
+ mkSymCoercion co2
+ all_eqs = concat args_eqss ++ ty2_eqs
+ eqTys = (mkTyConApp con args', ty2')
+ ; (co', all_eqs') <- adjustCoercions co rewriteCo eqTys all_eqs
+ ; let thisRewriteFam = RewriteFam
+ { rwi_fam = con
+ , rwi_args = args'
+ , rwi_right = ty2'
+ , rwi_co = co'
+ , rwi_loc = tci_loc inst
+ , rwi_name = tci_name inst
+ }
+ ; return $ (thisRewriteFam : all_eqs',
+ unionVarSets (ty2_skolems:args_skolemss))
+ }
+
+checkOrientation :: Type -> Type -> EqInstCo -> Inst -> TcM [RewriteInst]
+-- Performs the occurs check, decomposition, and proper orientation
+-- (returns a singleton, or an empty list in case of a trivial equality)
+-- NB: We cannot assume that the two types already have outermost type
+-- synonyms expanded due to the recursion in the case of type applications.
+checkOrientation ty1 ty2 co inst
+ = go ty1 ty2
+ where
+ -- look through synonyms
+ go ty1 ty2 | Just ty1' <- tcView ty1 = go ty1' ty2
+ go ty1 ty2 | Just ty2' <- tcView ty2 = go ty1 ty2'
+
+ -- identical types => trivial
+ go ty1 ty2
+ | ty1 `tcEqType` ty2
+ = do { mkIdEqInstCo co ty1
+ ; return []
+ }
+
+ -- two tvs, left greater => unchanged
+ go ty1@(TyVarTy tv1) ty2@(TyVarTy tv2)
+ | tv1 > tv2
+ = mkRewriteVar tv1 ty2 co
+
+ -- two tvs, right greater => swap
+ | otherwise
+ = do { co' <- mkSymEqInstCo co (ty2, ty1)
+ ; mkRewriteVar tv2 ty1 co'
+ }
+
+ -- only lhs is a tv => unchanged
+ go ty1@(TyVarTy tv1) ty2
+ | ty1 `tcPartOfType` ty2 -- occurs check!
+ = occurCheckErr ty1 ty2
+ | otherwise
+ = mkRewriteVar tv1 ty2 co
+
+ -- only rhs is a tv => swap
+ go ty1 ty2@(TyVarTy tv2)
+ | ty2 `tcPartOfType` ty1 -- occurs check!
+ = occurCheckErr ty2 ty1
+ | otherwise
+ = do { co' <- mkSymEqInstCo co (ty2, ty1)
+ ; mkRewriteVar tv2 ty1 co'
+ }
+
+ -- type applications => decompose
+ go ty1 ty2
+ | Just (ty1_l, ty1_r) <- repSplitAppTy_maybe ty1 -- won't split fam apps
+ , Just (ty2_l, ty2_r) <- repSplitAppTy_maybe ty2
+ = do { (co_l, co_r) <- mkAppEqInstCo co (ty1_l, ty2_l) (ty1_r, ty2_r)
+ ; eqs_l <- checkOrientation ty1_l ty2_l co_l inst
+ ; eqs_r <- checkOrientation ty1_r ty2_r co_r inst
+ ; return $ eqs_l ++ eqs_r
+ }
+-- !!!TODO: would be more efficient to handle the FunApp and the data
+-- constructor application explicitly.
+
+ -- inconsistency => type error
+ go ty1 ty2
+ = ASSERT( (not . isForAllTy $ ty1) && (not . isForAllTy $ ty2) )
+ eqInstMisMatch inst
+
+ mkRewriteVar tv ty co = return [RewriteVar
+ { rwi_var = tv
+ , rwi_right = ty
+ , rwi_co = co
+ , rwi_loc = tci_loc inst
+ , rwi_name = tci_name inst
+ }]
+
+flattenType :: Inst -- context to get location & name
+ -> Type -- the type to flatten
+ -> TcM (Type, -- the flattened type
+ Coercion, -- coercion witness of flattening wanteds
+ [RewriteInst], -- extra equalities
+ TyVarSet) -- new intermediate skolems
+-- Removes all family synonyms from a type by moving them into extra equalities
+flattenType inst ty
+ = go ty
+ where
+ -- look through synonyms
+ go ty | Just ty' <- tcView ty = go ty'
+
+ -- type family application => flatten to "id :: F t1'..tn' ~ alpha"
+ go ty@(TyConApp con args)
+ | isOpenSynTyCon con
+ = do { (args', cargs, args_eqss, args_skolemss) <- mapAndUnzip4M go args
+ ; alpha <- newFlexiTyVar (typeKind ty)
+ ; let alphaTy = mkTyVarTy alpha
+ ; cotv <- newMetaCoVar (mkTyConApp con args') alphaTy
+ ; let thisRewriteFam = RewriteFam
+ { rwi_fam = con
+ , rwi_args = args'
+ , rwi_right = alphaTy
+ , rwi_co = mkWantedCo cotv
+ , rwi_loc = tci_loc inst
+ , rwi_name = tci_name inst
+ }
+ ; return (alphaTy,
+ mkTyConApp con cargs `mkTransCoercion` mkTyVarTy cotv,
+ thisRewriteFam : concat args_eqss,
+ unionVarSets args_skolemss `extendVarSet` alpha)
+ } -- adding new unflatten var inst
+
+ -- data constructor application => flatten subtypes
+ -- NB: Special cased for efficiency - could be handled as type application
+ go (TyConApp con args)
+ = do { (args', cargs, args_eqss, args_skolemss) <- mapAndUnzip4M go args
+ ; return (mkTyConApp con args',
+ mkTyConApp con cargs,
+ concat args_eqss,
+ unionVarSets args_skolemss)
+ }
+
+ -- function type => flatten subtypes
+ -- NB: Special cased for efficiency - could be handled as type application
+ go (FunTy ty_l ty_r)
+ = do { (ty_l', co_l, eqs_l, skolems_l) <- go ty_l
+ ; (ty_r', co_r, eqs_r, skolems_r) <- go ty_r
+ ; return (mkFunTy ty_l' ty_r',
+ mkFunTy co_l co_r,
+ eqs_l ++ eqs_r,
+ skolems_l `unionVarSet` skolems_r)
+ }
+
+ -- type application => flatten subtypes
+ go (AppTy ty_l ty_r)
+-- | Just (ty_l, ty_r) <- repSplitAppTy_maybe ty
+ = do { (ty_l', co_l, eqs_l, skolems_l) <- go ty_l
+ ; (ty_r', co_r, eqs_r, skolems_r) <- go ty_r
+ ; return (mkAppTy ty_l' ty_r',
+ mkAppTy co_l co_r,
+ eqs_l ++ eqs_r,
+ skolems_l `unionVarSet` skolems_r)
+ }
+
+ -- free of type families => leave as is
+ go ty
+ = ASSERT( not . isForAllTy $ ty )
+ return (ty, ty, [] , emptyVarSet)
+
+adjustCoercions :: EqInstCo -- coercion of original equality
+ -> Coercion -- coercion witnessing the rewrite
+ -> (Type, Type) -- type sof flattened equality
+ -> [RewriteInst] -- equalities from flattening
+ -> TcM (EqInstCo, -- coercion for flattened equality
+ [RewriteInst]) -- final equalities from flattening
+-- Depending on whether we flattened a local or wanted equality, that equality's
+-- coercion and that of the new ones are adjusted
+adjustCoercions co rewriteCo eqTys all_eqs
+ | isWantedCo co
+ = do { co' <- mkRightTransEqInstCo co rewriteCo eqTys
+ ; return (co', all_eqs)
+ }
+ | otherwise
+ = return (co, map wantedToLocal all_eqs)
+ where
+ wantedToLocal eq = eq {rwi_co = mkGivenCo (rwi_right eq)}
+\end{code}
+
+
+%************************************************************************
+%* *
+ Propagation of equalities
+%* *
+%************************************************************************
+
+Apply the propagation rules exhaustively.
+
+\begin{code}
+propagate :: [RewriteInst] -> EqConfig -> TcM EqConfig
+propagate [] eqCfg = return eqCfg
+propagate (eq:eqs) eqCfg
+ = do { optEqs <- applyTop eq
+ ; case optEqs of
+
+ -- Top applied to 'eq' => retry with new equalities
+ Just (eqs2, skolems2)
+ -> propagate (eqs2 ++ eqs) (eqCfg `addSkolems` skolems2)
+
+ -- Top doesn't apply => try subst rules with all other
+ -- equalities, after that 'eq' can go into the residual list
+ Nothing
+ -> do { (eqs', eqCfg') <- applySubstRules eq eqs eqCfg
+ ; propagate eqs' (eqCfg' `addEq` eq)
+ }
+ }
+
+applySubstRules :: RewriteInst -- currently considered eq
+ -> [RewriteInst] -- todo eqs list
+ -> EqConfig -- residual
+ -> TcM ([RewriteInst], EqConfig) -- new todo & residual
+applySubstRules eq todoEqs (eqConfig@EqConfig {eqs = resEqs})
+ = do { (newEqs_t, unchangedEqs_t, skolems_t) <- mapSubstRules eq todoEqs
+ ; (newEqs_r, unchangedEqs_r, skolems_r) <- mapSubstRules eq resEqs
+ ; return (newEqs_t ++ newEqs_r ++ unchangedEqs_t,
+ eqConfig {eqs = unchangedEqs_r}
+ `addSkolems` (skolems_t `unionVarSet` skolems_r))
+ }
+
+mapSubstRules :: RewriteInst -- try substituting this equality
+ -> [RewriteInst] -- into these equalities
+ -> TcM ([RewriteInst], [RewriteInst], TyVarSet)
+mapSubstRules eq eqs
+ = do { (newEqss, unchangedEqss, skolemss) <- mapAndUnzip3M (substRules eq) eqs
+ ; return (concat newEqss, concat unchangedEqss, unionVarSets skolemss)
+ }
+ where
+ substRules eq1 eq2
+ = do { -- try the SubstFam rule
+ optEqs <- applySubstFam eq1 eq2
+ ; case optEqs of
+ Just (eqs, skolems) -> return (eqs, [], skolems)
+ Nothing -> do
+ { -- try the SubstVarVar rule
+ optEqs <- applySubstVarVar eq1 eq2
+ ; case optEqs of
+ Just (eqs, skolems) -> return (eqs, [], skolems)
+ Nothing -> do
+ { -- try the SubstVarFam rule
+ optEqs <- applySubstVarFam eq1 eq2
+ ; case optEqs of
+ Just eq -> return ([eq], [], emptyVarSet)
+ Nothing -> return ([], [eq2], emptyVarSet)
+ -- if no rule matches, we return the equlity we tried to
+ -- substitute into unchanged
+ }}}
+\end{code}
+
+Attempt to apply the Top rule. The rule is
+
+ co :: F t1..tn ~ t
+ =(Top)=>
+ co' :: [s1/x1, .., sm/xm]s ~ t with co = g s1..sm |> co'
+
+where g :: forall x1..xm. F u1..um ~ s and [s1/x1, .., sm/xm]u1 == t1.
+
+Returns Nothing if the rule could not be applied. Otherwise, the resulting
+equality is normalised and a list of the normal equalities is returned.
+
+\begin{code}
+applyTop :: RewriteInst -> TcM (Maybe ([RewriteInst], TyVarSet))
+
+applyTop eq@(RewriteFam {rwi_fam = fam, rwi_args = args})
+ = do { optTyCo <- tcUnfoldSynFamInst (TyConApp fam args)
+ ; case optTyCo of
+ Nothing -> return Nothing
+ Just (lhs, rewrite_co)
+ -> do { co' <- mkRightTransEqInstCo co rewrite_co (lhs, rhs)
+ ; let eq' = EqInst
+ { tci_left = lhs
+ , tci_right = rhs
+ , tci_co = co'
+ , tci_loc = rwi_loc eq
+ , tci_name = rwi_name eq
+ }
+ ; liftM Just $ normEqInst eq'
+ }
+ }
+ where
+ co = rwi_co eq
+ rhs = rwi_right eq
+
+applyTop _ = return Nothing
+\end{code}
+
+Attempt to apply the SubstFam rule. The rule is
+
+ co1 :: F t1..tn ~ t & co2 :: F t1..tn ~ s
+ =(SubstFam)=>
+ co1 :: F t1..tn ~ t & co2' :: t ~ s with co2 = co1 |> co2'
+
+where co1 may be a wanted only if co2 is a wanted, too.
+
+Returns Nothing if the rule could not be applied. Otherwise, the equality
+co2' is normalised and a list of the normal equalities is returned. (The
+equality co1 is not returned as it remain unaltered.)
+
+\begin{code}
+applySubstFam :: RewriteInst
+ -> RewriteInst
+ -> TcM (Maybe ([RewriteInst], TyVarSet))
+applySubstFam eq1@(RewriteFam {rwi_fam = fam1, rwi_args = args1})
+ eq2@(RewriteFam {rwi_fam = fam2, rwi_args = args2})
+ | fam1 == fam2 && tcEqTypes args1 args2 &&
+ (isWantedRewriteInst eq2 || not (isWantedRewriteInst eq1))
+-- !!!TODO: tcEqTypes is insufficient as it does not look through type synonyms
+-- !!!Check whether anything breaks by making tcEqTypes look through synonyms.
+-- !!!Should be ok and we don't want three type equalities.
+ = do { co2' <- mkRightTransEqInstCo co2 co1 (lhs, rhs)
+ ; let eq2' = EqInst
+ { tci_left = lhs
+ , tci_right = rhs
+ , tci_co = co2'
+ , tci_loc = rwi_loc eq2
+ , tci_name = rwi_name eq2
+ }
+ ; liftM Just $ normEqInst eq2'
+ }
+ where
+ lhs = rwi_right eq1
+ rhs = rwi_right eq2
+ co1 = eqInstCoType (rwi_co eq1)
+ co2 = rwi_co eq2
+applySubstFam _ _ = return Nothing
+\end{code}
+
+Attempt to apply the SubstVarVar rule. The rule is
+
+ co1 :: x ~ t & co2 :: x ~ s
+ =(SubstVarVar)=>
+ co1 :: x ~ t & co2' :: t ~ s with co2 = co1 |> co2'
+
+where co1 may be a wanted only if co2 is a wanted, too.
+
+Returns Nothing if the rule could not be applied. Otherwise, the equality
+co2' is normalised and a list of the normal equalities is returned. (The
+equality co1 is not returned as it remain unaltered.)
+
+\begin{code}
+applySubstVarVar :: RewriteInst
+ -> RewriteInst
+ -> TcM (Maybe ([RewriteInst], TyVarSet))
+applySubstVarVar eq1@(RewriteVar {rwi_var = tv1})
+ eq2@(RewriteVar {rwi_var = tv2})
+ | tv1 == tv2 &&
+ (isWantedRewriteInst eq2 || not (isWantedRewriteInst eq1))
+ = do { co2' <- mkRightTransEqInstCo co2 co1 (lhs, rhs)
+ ; let eq2' = EqInst
+ { tci_left = lhs
+ , tci_right = rhs
+ , tci_co = co2'
+ , tci_loc = rwi_loc eq2
+ , tci_name = rwi_name eq2
+ }
+ ; liftM Just $ normEqInst eq2'
+ }
+ where
+ lhs = rwi_right eq1
+ rhs = rwi_right eq2
+ co1 = eqInstCoType (rwi_co eq1)
+ co2 = rwi_co eq2
+applySubstVarVar _ _ = return Nothing
+\end{code}
+
+Attempt to apply the SubstVarFam rule. The rule is