+\begin{code}
+depAnalTyClDecls :: [(LTyClDecl Name, FreeVars)] -> [SCC (LTyClDecl Name)]
+-- See Note [Dependency analysis of type and class decls]
+depAnalTyClDecls ds_w_fvs
+ = stronglyConnCompFromEdgedVertices edges
+ where
+ edges = [ (d, tcdName (unLoc d), map get_assoc (nameSetToList fvs))
+ | (d, fvs) <- ds_w_fvs ]
+ get_assoc n = lookupNameEnv assoc_env n `orElse` n
+ assoc_env = mkNameEnv [ (tcdName assoc_decl, cls_name)
+ | (L _ (ClassDecl { tcdLName = L _ cls_name
+ , tcdATs = ats }) ,_) <- ds_w_fvs
+ , L _ assoc_decl <- ats ]
+\end{code}
+
+Note [Dependency analysis of type and class decls]
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+We need to do dependency analysis on type and class declarations
+else we get bad error messages. Consider
+
+ data T f a = MkT f a
+ data S f a = MkS f (T f a)
+
+This has a kind error, but the error message is better if you
+check T first, (fixing its kind) and *then* S. If you do kind
+inference together, you might get an error reported in S, which
+is jolly confusing. See Trac #4875
+
+