Achieving zero-cost specialization remains a fundamental challenge in programming language and compiler design. It often necessitates trade-offs between expressive power and type system soundness, as the interaction between conditional compilation and static dispatch can easily lead to unforeseen coherence violations and increased complexity in the formal model. This paper introduces meta-monomorphizing specializations, a novel framework that achieves specialization by repurposing monomorphization through compile-time metaprogramming. Instead of modifying the host compiler, our approach generates meta-monomorphized traits and implementations that encode specialization constraints directly into the type structure, enabling deterministic, coherent dispatch without overlapping instances. We formalize this method for first-order, predicate-based, and higher-ranked polymorphic specialization, also in presence of lifetime parameters. Our evaluation, based on a Rust implementation using only existing macro facilities, demonstrates that meta-monomorphization enables expressive specialization patterns while maintaining full compatibility with standard optimization pipelines. We show that specialization can be realized as a disciplined metaprogramming layer, offering a practical, language-agnostic path to high-performance abstraction. A comprehensive study of public Rust codebases further validates our approach, revealing numerous workarounds that meta-monomorphization can eliminate, leading to more idiomatic and efficient code. An empirical evaluation on 16 micro-benchmarks confirms that compile-time specialization matches or outperforms runtime TypeId-based dispatch, and demonstrates expressiveness gains on patterns -- such as lifetime-based dispatch, higher-ranked types, compound predicates, and wildcard matching -- that runtime dispatch structurally cannot express.
翻译:实现零开销特化仍然是编程语言与编译器设计中的根本性挑战。它通常需要在表达能力和类型系统可靠性之间做出权衡,因为条件编译与静态派发之间的相互作用容易导致难以预见的相干性冲突以及形式模型复杂度的增加。本文引入了元单态化特化这一新型框架,通过编译时元编程对单态化进行重新利用来实现特化。我们的方法无需修改宿主编译器,而是生成编码特化约束的元单态化特质和实现,直接将其嵌入类型结构,从而在无重叠实例的情况下实现确定性、相干性的派发。我们形式化了该方法在一阶、基于谓词以及高阶多态特化(包括生命周期参数存在时)中的应用。基于仅使用现有宏设施的Rust实现的评估表明,元单态化在维持与标准优化管道完全兼容的同时,能够实现富有表现力的特化模式。我们证明特化可以作为一门有纪律的元编程层来实现,为高性能抽象提供了一种实用且与语言无关的路径。对公开Rust代码库的全面研究进一步验证了我们的方法,揭示了元单态化可以消除的大量权宜做法,从而产生更地道且高效的代码。基于16个微基准的经验评估证实,编译时特化在性能上达到或超过运行时TypeId派发,并在生命周期派发、高阶类型、复合谓词以及通配符匹配等模式上展示了运行时派发在结构上无法实现的表现力增益。