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 -- previously rejected by the compiler -- 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.
翻译:实现零成本特化始终是编程语言与编译器设计中的核心挑战。这通常需要在表达能力与类型系统可靠性之间进行权衡,因为条件编译与静态分发的交互极易导致不可预见的连贯性违规,并增加形式化模型的复杂性。本文提出元单态化特化这一新颖框架,该框架通过编译时元编程重新利用单态化机制来实现特化。我们的方法无需修改宿主编译器,而是生成元单态化的特质与实现,将特化约束直接编码到类型结构中,从而实现确定性、连贯的分发,且不存在实例重叠问题。我们形式化了该方法在一阶、基于谓词及高阶多态特化场景下的应用,并涵盖了包含生命周期参数的情况。基于仅使用现有宏设施的Rust实现,我们的评估表明,元单态化能够支持编译器此前拒绝的表达性特化模式,同时保持与标准优化流程的完全兼容。我们证明特化可以作为一个受控的元编程层来实现,为高性能抽象提供了一条实用且与语言无关的路径。对公开Rust代码库的全面研究进一步验证了我们的方法,揭示了大量可通过元单态化消除的变通方案,从而生成更符合语言习惯且更高效的代码。