Note [Put instances at the end]
There is no point including type family instances or class instances in the graph for SCC analysis because instances are not referred to by name. We cannot discover, by looking at the free variables of a declaration, what instances it depends on. Instead, we create one singleton "SCC" per instance using mkInstGroups and put them at the end. This is simple and guarantees that the FVs of all instances are bound in the preceding TyClGroups. The problem is that if there are any declarations that depend on instances, they're going to fail kind checking, because instances come after the declarations. To account for that, the kind checker goes through a multipass ordeal described in Note [Retrying TyClGroups] in GHC.Tc.TyCl. One might ask, "why not insert instances at the earliest positions where their FVs are bound?" Indeed, this sounds like a plausible solution, and GHC used to do it at one point. However, there are many tickets (and now test cases) demonstrating its inadequacy: #12088, #12239, #14668, #15561, #16410, #16448, #16693, #19611, #20875, #21172, #22257, #25238, #25834, etc. As to why we put each instance in its own group, as opposed to using just one group with all the instances, the reason is that an instance may depend on another instance, so we better add them to the environment one by one.
References 1
- Retrying TyClGroups GHC.Tc.TyCl
Referenced by 3
- GHC.Tc.TyCl call site ×2
- Dependency analysis of type and class decls GHC.Rename.Module