TTG: Addressing orphan instance technical debt
## Background
The "Trees that Grow" technique, described in
[Trees that Grow](https://www.cs.tufts.edu/comp/150FP/archive/simon-peyton-jones/trees-that-grow.pdf),
lets one syntax tree support multiple compiler phases by parameterizing the tree over a pass and by using open
type families for constructor fields, extension constructors, and annotations. In GHC, that allows
`Language.Haskell.Syntax` to own the reusable, phase-indexed AST while the `GHC` module-space supplies concrete
GHC pass instantiations and compiler behavior. The decoupling progressed by removing one offending import edge at a
time: AST types moved into L.H.S. first, while instances that still needed GHC-only concepts such as `GhcPass`,
`SourceText`, source spans, parser annotations, names, identifiers, binary serialization, and pretty-printing
remained in GHC modules. Once the type moved but the instance stayed behind, those instances became deliberate
technical debt: they preserved behavior and kept each step reviewable, but left later cleanup work over the import
graph.
## Tech debt estimation
This analysis covers commits after
`fe2b79f4f21acf077738eb9ae9868c6b28afd1c4` and through
`809c867c9a64e34616b1be09b5aff62c6bba1ff2`.
The following counts are a scale indicator, not a precise count of final orphan instances.
They count added `instance`, `deriving instance`, and `type instance` declarations in the relevant compiler source diff.
Some added instances were support instances for local helper types, and some orphan debt was created by moving a data type while leaving pre-existing instance text in place.
| Commit | Decoupling focus | Added class/deriving instances | Added type instances | Added orphan pragmas |
| --- | --- | ---: | ---: | ---: |
| `06c2349c41e4` | `Language.Haskell.Syntax.Type` from `GHC.Utils.Panic` | 0 | 0 | 0 |
| `eac418bb2b1c` | Remove `Data` instance for `InstEnv` | 0 | 0 | 0 |
| `e920e0387c52` | Warnings out of `GHC.Unit.Module.Warnings` | 17 | 8 | 1 |
| `7b9c20f4c3c8` | `InlinePragma` out of `GHC.Types.Basic` | 26 | 5 | 1 |
| `631fa5ae212e` | Declaration/basic syntax out of `GHC.Types.Basic` | 15 | 3 | 2 |
| `cf60850a4bea` | Foreign-call syntax out of `GHC.Types.ForeignCall` | 40 | 10 | 1 |
| `d7cfea496a1f` | `SourceText` out of `GHC.Types.SourceText` | 37 | 10 | 0 |
| `a1f2558b1ac4` | Monomorphise GHC pass parameters | 0 | 0 | 0 |
| `809c867c9a64` | Documentation strings out of `GHC.Hs.Doc` | 15 | 8 | 3 |
The six material decoupling commits therefore introduced or exposed roughly 150 added class or deriving instance declarations and 44 added type-family instance declarations.
The exact orphan count is not identical to that raw line count: some added instances were not the TTG debt being measured, while some existing instances became orphaned when their data type moved into L.H.S.
The count is still useful because it shows the size of the cleanup surface created by the decoupling strategy.
## Why the orphan instances were necessary for the decoupling method
The method used by the TTG project was intentionally incremental. Each commit removed a specific L.H.S. dependency
on a GHC module and kept GHC building after that one edge was removed. That method has real benefits: the review
surface is constrained, regressions are easier to attribute, and the compiler remains in a working state after each
step.
However, Haskell's orphan-instance rule cuts across this style of refactoring.
An instance is non-orphan only when it is defined in a module that owns either the class/family or the type involved in the instance head.
During the TTG decoupling, ownership moved in only one direction:
- AST data types moved from GHC modules to `Language.Haskell.Syntax`.
- GHC-specific classes such as `Outputable`, `Binary`, and `Uniquable` remained in GHC modules.
- GHC-specific pass types, annotations, source spans, names, identifiers, and payloads remained in GHC modules.
Once a type moved to L.H.S., defining `Binary`, `Outputable`, `Data`, `NFData`, or pass-specific type-family instances in the old GHC module often became orphaned.
Moving those instances immediately into the type module was not acceptable, because that would have made L.H.S. depend on GHC internals. Moving them immediately into the class module was also often not possible, because low-level class modules such as `GHC.Utils.Binary` and
`GHC.Utils.Outputable` could not import the necessary pass and syntax modules without forming cycles.
In other words, the orphan instances were the local price paid to preserve all three of the following properties at once:
- L.H.S. stopped depending on the targeted GHC module.
- GHC's existing binary serialization, pretty-printing, equality, annotation, and source-preservation behavior was retained.
- The import graph was changed incrementally rather than through one large, high-risk module reorganization.
The type-family instances are particularly important.
TTG intentionally leaves extension fields and annotations open.
GHC must later provide equations such as `XInlinePragma GhcPs = SourceText` or `XCType (GhcPass p) = CTypeGhc`.
Those equations naturally belong near the GHC pass and payload definitions, not in the L.H.S. AST definitions.
Until the GHC pass definitions and payload modules were organized around that role, many of those equations were necessarily orphan-like from the module-system perspective.
## Effort required to remove the orphan debt
The cleanup effort falls into several categories of difficulty.
Based on the complexity of removing the orphan instances, only some of the categories will be undertaken.
### Low difficulty: Documentation cleanup
- **Assessment:** _Attempt to resolve_
A significant part of the cleanup is documentation rather than code motion.
During the incremental TTG work, orphan suppression comments were necessarily local and sometimes became stale as instances moved again. Because the remaining orphan instances are intentional architectural compromises, each `-Wno-orphans` suppression should say
which instances it covers.
### Low difficulty: leaf class instances
- **Assessment:** _Attempt to resolve_
Some instances are ordinary `Binary`, `Outputable`, or `Uniquable` instances for L.H.S. types whose implementations only require small leaf dependencies.
Once the class modules can import the relevant syntax type and helper payloads without forming a cycle, these instances can be moved into the class module and cease to be orphan instances.
This is the most mechanical part of the cleanup.
The main risks are preserving exact pretty-printing and binary encoding behavior, avoiding unrelated formatting churn, and keeping export APIs backward compatible.
### Medium difficulty: pass-specific class instances
- **Assessment:** > _Attempt to resolve_
Instances such as `Outputable (InlinePragma (GhcPass p))`, `Binary (CCallTarget (GhcPass p))`, or
`Outputable (HsDocString (GhcPass p))` require pass-specific functionality.
These instances often need `IsPass`, `ghcPass`, source spans, source text, or pass payload types.
Removing these orphans requires more than moving an instance declaration.
The dependency graph has to be arranged so that class modules can import the pass-specific definitions without importing large syntax modules that import the class module back.
This is where module splits likely necessary; a pass “internal” module can lower the dependency edge enough for the class module to own the instance.
### High difficulty: large AST pretty-printer instances
- **Assessment:** > _Deffer due to difficulty_
Many `Outputable` instances for syntax trees are not small leaf instances.
They rely on broad pretty-printing helpers, binder-aware printing, names, identifiers, and phase-specific context. These instances are harder to move without making `GHC.Utils.Outputable` depend on large parts of the compiler.
For these instances, the correct cleanup may be to split out lower-level pretty-printing primitives or pass/payload
definitions, not to move the whole AST printer into a utility module.
The goal would be to remove orphan status without turning foundational utility modules into high-level syntax modules.
### High difficulty: TTG type-family instances
- **Assessment:** > _Deffer due to difficulty_
The TTG type-family equations are different from ordinary type-class instances.
They encode the GHC instantiation of the L.H.S. syntax tree. Moving them into arbitrary class modules would be architecturally wrong, and moving them into L.H.S. would defeat the purpose of the decoupling.
The likely cleanup strategy for these is to create or use GHC-side modules that own the relevant pass type or payload definitions and are low enough in the import graph to be imported by users that need the equations.
This would probably look like an “internal” module defining the type-family instances in the **`GHC`** “namespace” for each module in the `**L.H.S`** namespace.
For example:
```
┌───▶ GHC.*
│ other GHC dependancies that should not
│ be imported by GHC.Utils.Outputable
GHC.Hs.Decls ──────────────┤
│
GHC.Utils.Outputable ───┐ │
│ │
▼ ▼
GHC.Hs.Decls.Internal
│
│ owns GHC-side TTG type-family instances
│ and imports the L.H.S. AST type owner
▼
Language.Haskell.Syntax.Decls
```
## Conclusion
The orphan instance technical debt in significant and warrants attention.
However, it is infeasible to remove _all_ orphan instances.
In many cases, the code is clearer and more maintainable by having the orphan type-family instances adjacent to the associated data-types.
In other instances, where the orphan instances do not improve code maintainability, they can effect compiler warning/inference and cause developer confusion while providing no technical benefit. In the latter cases, the orphan instances ought to be resolved.
See the assessments in the previous section for the orphan instances to be resolved.
issue