How to Stop Generic Type Explosion in Rust
Contents
There is a popular tendency in the Rust ecosystem, often treated as a mark of clever design: stuffing all state and syntax structure into generic type parameters.
Many type-heavy designs get carried away with this kind of "compile-time magic," wrapping another layer of generics around the return type on every method call. It feels neat until a compiler error dumps dozens of lines of nested type signatures, or the compiler outright refuses to build just because you tried to append a filter dynamically inside an if branch.
In the previous post, we opened a generic <Ctx> slot on our core traits to hand third-party type extensibility back to the user. That solved the orphan rule, but it immediately introduces another hazard: generics in Rust are contagious. Once a low-level trait takes a generic parameter, the outer structs that hold or pass it around are usually forced to carry that parameter too. Without clear boundaries, a local type marker will creep up the call chain and drag the entire library into a mire of heavy generics.
Cutting off generic contagion does not take more elaborate type gymnastics. It takes a clear view of your type-safety boundaries: where a generic parameter needs to appear, and the exact instant it must disappear.
How Generics Spiral Out of Control
Let's start with a familiar engineering scenario.
Suppose we are writing a compile-time checked rule matcher, such as a route filter or query builder. Carrying over the design from the last post, we have a value conversion trait ToVal<Ctx> parameterized by a context marker Ctx, a trait Compatible<T> that checks type compatibility, and a strongly typed field definition Field<T>:
pub trait ToVal<Ctx = ()> {
fn to_val(&self) -> Value;
}
pub trait Compatible<T> {}
pub struct Field<T> {
pub name: &'static str,
_marker: PhantomData<T>,
}Now we want to express a comparison rule like age.gt(18). The most intuitive approach is to define a Rule struct that verifies the input value V is compatible with the field type T, and then stores the field, operator, and value:
pub struct Rule<T, V, Ctx> {
pub field: Field<T>,
pub op: &'static str,
pub val: V,
_marker: PhantomData<Ctx>,
}
impl<T> Field<T> {
pub fn gt<V, Ctx>(self, val: V) -> Rule<T, V, Ctx>
where
V: Compatible<T> + ToVal<Ctx> {
Rule { field: self, op: ">", val, _marker: PhantomData }
}
}Taken alone, this step looks harmless. The trouble starts when users need to combine rules across different fields.
Suppose a user writes two rules: age.gt(18) and name.eq("alice"). The first has the type Rule<i32, i32, Ctx>, while the second has the type Rule<String, &str, Ctx>. In Rust, these are two completely different, heterogeneous types. They cannot live in the same Vec.
To combine heterogeneous rules inside a single Matcher builder, you are usually forced to introduce a recursive generic container like And<L, R> to bind them together at the type level:
pub struct And<L, R>(pub L, pub R);
pub struct Matcher<R> {
pub rule: R,
}
impl<R> Matcher<R> {
pub fn and<T, V, Ctx>(self, next: Rule<T, V, Ctx>) -> Matcher<And<R, Rule<T, V, Ctx>>> {
Matcher { rule: And(self.rule, next) }
}
}Look closely at the return type of .and(): Matcher<And<R, Rule<T, V, Ctx>>>.
With just two rules, the type signature is already nesting inward. Worse, every subsequent method call appends the static types of its current arguments straight onto the outer container's type signature.
In the current Rust ecosystem, plenty of libraries that rely heavily on recursive generic modeling, such as certain parser combinators, web routing trees, or compile-time checked ORMs, go all the way down this road. They don't just pack every syntax node into generics; they encode the entire trajectory of a method chain into the builder's return type.
This design looks fine in a simple demo, but the moment you put it into a real production project, you hit two dead ends:
1. Control Flow and Function Abstraction Hit a Wall
Because each .and() call returns a brand-new Rust type, you cannot even write a basic if branch:
let mut matcher = Matcher::new();
if let Some(min_age) = req.min_age {
// ❌ Compile error: expected `Matcher<()>`, found `Matcher<And<(), Rule<i32, i32, AppCtx>>>`
matcher = matcher.and(age.gt(min_age));
}The matcher variable does not have the same type before and after entering the if branch. For the same reason, you cannot stack conditions dynamically in a for loop, nor can you pass matcher to a regular helper function fn apply_filter(m: ???) -> ???. A matcher with seven or eight rules expands into a generic tree nested more than a dozen levels deep, which is impossible to write out by hand.
In the end, these libraries are forced to provide an .into_boxed() escape hatch to box the statically dispatched generic tree back into a dynamically dispatched trait object (Box<dyn Trait>). As a result, you still pay the compile-time cost of generic inference for the first half of the chain, and then take on the runtime cost of vtable dispatch anyway.
2. Monomorphization Bloat in the Compiler Backend
Rust handles generics through monomorphization: every distinct combination of generic parameters generates a separate copy of function machine code in the LLVM backend.
In the type-accumulating design above, Matcher eventually has to call .compile() or .eval() to execute the syntax tree. Because every rule chain produces a unique Matcher<And<And<...>>> type, LLVM is forced to duplicate the entire underlying processing pipeline hundreds of times and compile it from scratch over and over, even though every copy is doing the exact same tree traversal and rendering work. Once a project pulls in a library like this, incremental compile times quickly spiral out of control. Change a single line in a filter condition, and the linker stalls.
Generics Belong Only at the Type-Safety Boundary
How does ordinary static type checking end up in this state?
Many heavily generic designs fall into a common misconception: assuming that strict compile-time checking requires keeping the user's raw T and V types attached to the struct all the way to the final step.
Keeping T and V on the Rule struct is what turns age > 18 and name == "alice" into heterogeneous types. Because they are heterogeneous, the design is forced to invent the recursive And<L, R> container. And once you step onto that path, the type gymnastics never stop.
To fix this, let's step back and trace age.gt(18) from creation to execution, to see the exact moments when those generic parameters actually do real work:
- The first boundary (the instant
age.gt(18)is called). We need the compiler to verify that the input valueVis compatible with the field typeT(V: Compatible<T>), and thatVcan be converted into an internal value under the current contextCtx(V: ToVal<Ctx>). Once a comparison expression is formed, it produces a boolean condition; downstream logical combinations never care whether the inner comparison was between integers or strings. The instant execution steps inside the function body,TandVhave fulfilled their purpose. - The second boundary (the instant
matcher.and(rule)is called). We need the compiler to verify that the context onRule<Ctx>matches the context on the outerMatcher<Ctx>, preventing users from accidentally passing anRpcCtxrule into anAppCtxbuilder. Once it crosses this threshold,Ctxhas fulfilled its purpose too. - Inside the syntax tree (AST). Once those checks pass, the call is already completely valid in terms of static semantics. From that point on,
age > 18andname == "alice"look identical to the underlying engine. Both are plain data nodes holding a field name, an operator, and an intermediateValue, waiting to be traversed together at the end.
The root cause of generic explosion lies right here: conflating compile-time contract validation with runtime data storage, and letting generic parameters that were only meant to check tickets at the door stay inside your internal data structures and refuse to leave.
Once you see this distinction, the way out is clear. A clean type system design is "strict at the boundary, flat on the inside, and discarded on entry": at the public API boundary, use generics and trait bounds to guard the door; the moment data crosses that boundary and passes inspection, erase the generic parameters that have done their job and collapse the structure into a homogeneous plain type.
Breaking the Chain with an Erase Protocol
Following the two boundaries we just drew, let's redesign the code around a two-stage collapse.
First is the age.gt(val) boundary. We leave the where bounds on the method signature untouched. Instead of storing T and V in the struct, however, we call ToVal::<Ctx>::to_val(&val) to convert the data right as the check passes, erasing T and V on the spot:
// Homogeneous internal AST node with no T, V, or Ctx parameters
pub enum ExprNode {
Gt(&'static str, Value),
Eq(&'static str, Value),
}
// Public rule type: T and V are erased, leaving only the phantom context marker Ctx
pub struct Rule<Ctx = ()> {
pub(crate) node: ExprNode,
_marker: PhantomData<Ctx>,
}
impl<T> Field<T> {
// Strict outside: validate compatibility between V and T along with context Ctx at the signature boundary
pub fn gt<V, Ctx>(self, val: V) -> Rule<Ctx>
where
V: Compatible<T> + ToVal<Ctx> {
// Flat inside: convert straight into a homogeneous ExprNode upon entry, where T and V disappear
Rule {
node: ExprNode::Gt(self.name, ToVal::<Ctx>::to_val(&val)),
_marker: PhantomData,
}
}
}This step does not give up a single compile-time check, yet the previously heterogeneous age.gt(18) and name.eq("alice") now share a homogeneous return type: Rule<Ctx>. Since the types are now homogeneous, we no longer need the recursive And<L, R> container to stitch heterogeneous nodes together in the type system. Every rule can go straight into the same Vec.
Next is the second boundary: matcher.and(rule).
The only reason we kept <Ctx> on Rule<Ctx> was to verify context consistency when entering Matcher<Ctx>. Once that check passes, <Ctx> must disappear immediately as well. To do that, we define a minimal internal erasure trait, Erase:
pub trait Erase {
type Erased;
fn erase(self) -> Self::Erased;
}
impl<Ctx> Erase for Rule<Ctx> {
// Regardless of the outer Ctx, collapse it in place to Rule<()>
type Erased = Rule<()>;
#[inline(always)]
fn erase(self) -> Self::Erased {
Rule { node: self.node, _marker: PhantomData }
}
}Why collapse Rule<Ctx> in place into Rule<()> instead of unwrapping the inner ExprNode directly? Because in a real, complex DSL, many syntax nodes are not thin wrappers around an enum. They are structs carrying multiple domain fields directly, such as an Ordering<Ctx> holding an expression, sort direction, and nulls policy, or a Projection<Ctx> carrying alias metadata. Collapsing <Ctx> to () in place via Erase lets a single struct serve as both the strongly typed public facade with compile-time contracts (Rule<Ctx>) and the untyped internal AST data node (Rule<()>). That way, we don't have to maintain redundant outer and inner struct definitions for every syntax concept, and we can perform uniform batch erasure when accepting composite arguments like tuples.
Now we split Matcher into a public facade and an internal core:
// Internal core AST: all generic markers are zeroed out to (), decoupled from domain types and Ctx
pub struct RuleTree {
pub rules: Vec<Rule<()>>,
}
// Public facade: retains only a fixed-width <Ctx = ()> marker
pub struct Matcher<Ctx = ()> {
pub(crate) tree: RuleTree,
_marker: PhantomData<Ctx>,
}
impl<Ctx> Matcher<Ctx> {
// Second boundary check: the incoming Rule<Ctx> must match the current Matcher<Ctx>'s context
pub fn and(mut self, rule: Rule<Ctx>) -> Self {
// Erase on entry: strip Ctx and store in the homogeneous internal syntax tree
self.tree.rules.push(rule.erase());
self
}
pub fn compile(&self) -> String {
// Delegate directly to the non-generic underlying engine
self.tree.render()
}
}With this refactoring, both of our earlier problems disappear:
- Type width stays constant.
.and()simply returnsSelf. Whether you append conditions dynamically inside anifbranch or stack a hundred rules in aforloop, the type ofmatcherremains a flatMatcher<Ctx>from start to finish. You can store it in a struct or pass it as an argument to any helper function whenever you like. - Zero monomorphization bloat in the underlying engine. Look at
.compile(): the actual heavy lifting inself.tree.render()is defined on the non-genericRuleTree. No matter how many differentCtxtypes your application defines, or how many intricate rule combinations you assemble, the underlying rendering pipeline is compiled by LLVM once across the entire binary, and only once.
Doesn't replacing the stack-allocated recursive And<L, R> structure with a Vec add a heap allocation? In almost every rule matching, routing, or database querying scenario, the syntax tree is about to perform string rendering or cross a network or disk I/O boundary. Sacrificing control flow and flushing the CPU instruction cache (I-Cache) with hundreds of monomorphized machine-code copies just to save a few dozen bytes of Vec allocation during construction gets the engineering priorities backward.
Lazy Error Sealing
When converting data and erasing types on the spot at the entry boundary, one practical engineering detail still needs to be addressed.
In the earlier examples, we assumed to_val() could never fail. In real production code, however, type conversion can fail at any time: narrowing a large integer can overflow, or serializing a custom type can return an error. As a result, ToVal must return Result<Value, Error>:
pub trait ToVal<Ctx = ()> {
fn to_val(&self) -> Result<Value, Error>;
}This creates a dilemma: if we insist on running the conversion immediately at the age.gt(18) entry boundary, does age.gt(18) have to return Result<Rule<Ctx>, Error>?
Once every basic expression returns a Result, users combining rules will be buried under a wall of question marks: matcher.and(age.gt(18)?)?.and(name.eq("alice")?)?, ruining the ergonomics of the DSL. Yet if we defer the conversion until the final .compile() call just to avoid ?, we have to store the raw type V inside the AST all the way through, falling right back into the generic explosion trap. How do we erase the type V on the spot at the entry point without letting ? pollute the call chain?
The solution comes down to a single sentence: if an error occurs at the boundary while building the AST, make the error itself an AST node.
We only need to add a dedicated Error variant to our ExprNode enum:
pub enum ExprNode {
Gt(&'static str, Value),
Eq(&'static str, Value),
// Lazily seal conversion errors produced at the boundary inside the syntax tree
Error(Box<Error>),
}
impl<T> Field<T> {
pub fn gt<V, Ctx>(self, val: V) -> Rule<Ctx>
where
V: Compatible<T> + ToVal<Ctx> {
// Convert on the spot: build a Gt node on success, or seal in place into an Error node on failure
let node = match ToVal::<Ctx>::to_val(&val) {
Ok(v) => ExprNode::Gt(self.name, v),
Err(e) => ExprNode::Error(Box::new(e)),
};
Rule { node, _marker: PhantomData }
}
}When a user calls age.gt(val) at the boundary, ToVal::<Ctx>::to_val(&val) still executes immediately:
- If conversion succeeds (
Ok(v)), it builds a normalExprNode::Gt(self.name, v). - If conversion fails (
Err(e)), it does not interrupt the method chain; instead, it packs the error intoExprNode::Error(Box::new(e))and returnsRule<Ctx>as usual. Wrapping the error inBox<Error>keeps a largeErrortype from inflating the stack size of the entireExprNodeenum on the normal path.
Later, after the user finishes writing a clean chain of rules and calls matcher.compile() (which returns Result<String, Error>) to trigger the underlying RuleTree::render(), the renderer simply returns the sealed error as soon as its traversal hits an ExprNode::Error node.
How This Architecture Lands in Kova
The Matcher above only dealt with simple comparisons. When placed inside a complex real-world system, does this "strict outside, flat inside, two-stage collapse" architecture still hold up?
Across the entire Rust ecosystem, the hardest-hit victim of generic explosion is the SQL query builder. A routine SELECT query intertwines table models, arithmetic and comparison operations across dozens of field types, aggregate and window functions, multi-table JOINs, grouping and ordering, subqueries, and custom codec contexts. That is why traditional compile-time type-safe ORMs routinely balloon into nested generic signatures hundreds of lines long.
When designing the Rust ORM framework Kova, I set a strict rule: no matter how complex the SQL syntax tree gets, domain model types and codec context generics are never allowed to cross the builder boundary.
In Kova, every argument passing from user code into the underlying SQL syntax tree goes through the same two-stage collapse:
- The first collapse happens the instant an expression is constructed. When you write
User::age.gt(18)orUser::name.like("alice%"), the compiler strictly checks the column type, operational capabilities (for example, only numeric columns can be summed, and only text columns allow regex matching), and operand compatibility right at the method entry. As soon as the check passes, the argument is immediately encoded viaEncodeinto a unified internalOperandNode(if encoding fails, the error is lazily sealed intoOperandNode::Error). The concrete field typesi32and&strare erased on the spot, leaving only a homogeneous condition nodeCondition<'a, DB, X>carrying the context marker<X>. - The second collapse happens the instant a node enters the query builder. When condition (
Condition), ordering (Ordering), or projection (Projection) nodes are passed into theSelectbuilder, the compiler verifies that<X>on the node matches the context of the current clientClient<X>. Once it crosses the method boundary, Kova's internalEraseXprotocol strips off the remaining<X>marker as well. When a composite tuple like(User::balance.desc(), User::id.asc())is passed in,into_args_erased()erases the entire batch of nodes right at the entry point:
pub trait EraseX {
type Erased;
fn erase_x(self) -> Self::Erased;
}
impl<'a, T, D: Dispatch, S, X> Select<'a, T, D, S, X>
where
T: Model<Postgres, X> {
// Strict boundary check: the incoming Condition must carry the same context X as the current Select
pub fn filter(mut self, cond: Condition<'a, Postgres, X>) -> Select<'a, T, D, Normal, X> {
// Erase on entry: collapse X to () in place the instant it enters the internal syntax tree
self.statement.r#where(cond.erase_x());
self.into_state()
}
pub fn order_by<A, M>(mut self, cols: A) -> Select<'a, T, D, Normal, X>
where
A: IntoArg<Ordering<'a, Postgres, X>, M> {
// Batch erase on entry: collapse a single node or heterogeneous tuple into Vec<Ordering<'a, Postgres, ()>>
self.statement.order_by(cols.into_args_erased());
self.into_state()
}
}After these two boundary checkpoints, if you open Kova's kernel (kova-kernel) and inspect SelectStatement, which actually holds the entire SQL syntax tree, you will find that this full-featured SQL AST contains no primary table model <T>, not a single domain field type, and no codec context <X>:
pub struct SelectStatement<'a, DB: Database> {
pub(crate) with: WithClause<'a, DB>,
pub(crate) from: TableClause<'a, DB>,
pub(crate) distinct: DistinctClause,
pub(crate) projection: ProjectionClause<'a, DB>,
pub(crate) join: JoinClause<'a, DB>,
pub(crate) r#where: WhereClause<'a, DB>,
pub(crate) group_by: GroupByClause<'a, DB>,
pub(crate) having: HavingClause<'a, DB>,
pub(crate) order_by: OrderByClause<'a, DB>,
pub(crate) pagination: PaginationClause,
pub(crate) locking: LockingClause<DB>,
pub(crate) combine: CombineClause<'a, DB>,
}Meanwhile, the outer Select<'a, T, D, S, X> builder retains only a few constant-width type parameters: the primary table model T, finite state-machine slots D/S (where S only constrains table alias placement at the start and remains unchanged after entering the regular Normal state), and the context X. No matter how many methods you chain or how many table joins you add, the builder's type width never grows and never nests inward.
In day-to-day development, the most tangible benefit of this internal-external decoupling is that it hands control flow back to the developer. Building queries dynamically across arbitrary branches in Kova feels no different from mutating an ordinary Rust struct:
let mut query = client.select::<User>().distinct();
if let Some(name) = search_name {
query = query.filter(User::name.like(format!("%{name}%")));
}
if only_vip {
query = query.order_by(User::balance.desc());
}
let users = query.limit(20).load().await?;There are no unwriteable function signatures, and no need to compromise by calling .into_boxed() just to fit a query into an if branch. And in the compiler backend, no matter how many queries you write across your project, the entire SQL rendering engine is compiled only once in the final binary.
Much of the rigidity and slow compilation we experience with certain Rust libraries does not happen because Rust's type system is too strict, but because the library design blurs the boundary between static validation and return-type signatures. When you pile an open-ended, growing syntax tree straight into a return type, you are offloading the library's internal state-tracking work onto the caller's function signatures, if/else branches, and repeated monomorphization passes in the LLVM backend. Keeping generic bounds at the API entry points where errors need to be caught, and erasing them promptly once inside, is how you preserve both compile-time safety and a flat, responsive development experience.
With generic containment and erasure solved, building a truly ergonomic DSL faces its next challenge: how do you say goodbye to prelude::* and require zero trait imports from the user, while still letting different expression nodes automatically expose their own domain-specific methods and even transition capabilities at compile time across nested function calls? We will cover that in the next post.
The architecture discussed in this series comes from Kova, a compile-time type-safe Rust ORM with deep native support for PostgreSQL and SQLite, no query macros, no trait imports, and flat builder types. See the GitHub repository for the full implementation.