NeurIPS 2026Coming to NeurIPS?Explore papers, orals & directions

Type-Constrained Code Generation with Language Models

Niels Mündler, Jingxuan He, Hao Wang, Koushik Sen, Dawn Song, Martin T. Vechev · DOI

Abstract

Large language models (LLMs) have achieved notable success in code generation. However, they still frequently produce uncompilable output because their next-token inference procedure does not model formal aspects of code. Although constrained decoding is a promising approach to alleviate this issue, it has only been applied to handle either domain-specific languages or syntactic features of general-purpose programming languages. However, LLMs frequently generate code with typing errors, which are beyond the domain of syntax and generally hard to adequately constrain. To address this challenge, we introduce a type-constrained decoding approach that leverages type systems to guide code generation. For this purpose, we develop novel prefix automata and a search over inhabitable types, forming a sound approach to enforce well-typedness on LLM-generated code. We formalize our approach on a foundational simply-typed language and extend it to TypeScript to demonstrate practicality. Our evaluation on the HumanEval and MBPP datasets shows that our approach reduces compilation errors by more than half and significantly increases functional correctness in code synthesis, translation, and repair tasks across LLMs of various sizes and model families.

Introduction

While Large Language Models (LLMs) are increasingly capable coders, they frequently produce "hallucinated" code that fails to compile due to subtle type errors. Current state-of-the-art models often generate code that looks correct but contains logic flaws stemming from basic type mismatches—such as passing a numeric value to a function expecting a string. While previous research has used "constrained decoding" to enforce programming language syntax (ensuring brackets match and keywords are used correctly), syntax only accounts for a small fraction of errors. In TypeScript, for instance, approximately 94% of compilation errors are type-related rather than syntactic.

The Challenge of Type Safety

Traditional constrained decoding relies on Context-Free Grammars (CFGs), but type systems are context-sensitive and far more complex. The challenge lies in determining, for every partial snippet of code the LLM writes, whether there exists any possible completion that would result in a well-typed program. As shown in the comparison below, syntax-only constraints are often insufficient to prevent invalid code.

Comparison of decoding constraints: type-aware decoding rejects completions that are syntactically valid but semantically incorrect.

Type-Constrained Decoding Approach

To address these challenges, this research introduces a two-tiered approach to enforce type safety during the "next-token" sampling process:

  1. Prefix Automata: A specialized non-deterministic automaton tracks the "type environment" (variables declared, function signatures, etc.) as code is generated. This automaton maintains a "prefix property," meaning it only allows the LLM to transition into states that can eventually reach a valid, well-typed conclusion.
  2. Type Reachability Search: To handle partial expressions, a sound search algorithm checks if a current partial input can be transformed into the required type via valid operations. For example, if a string is required but the LLM provides a number, the algorithm determines if a method like .toString() can bridge the gap. If no such path exists, the token is rejected.
A type reachability graph used to determine if a partial expression can eventually satisfy a required type through valid member access and function calls.

This system was formalized on a foundational simply-typed calculus ($L_B$) and scaled to a significant subset of TypeScript, handling complex features like arrays, loops, operator precedence, and polymorphic built-in members.

Experimental Results

The approach was evaluated using TypeScript versions of industry-standard benchmarks: HumanEval and MBPP. The researchers tested the method across three tasks: synthesis (writing code from scratch), translation (Python to TypeScript), and repair (fixing buggy code). The results across various models (Gemma 2, DeepSeek Coder, CodeLlama, Qwen2.5) were striking:

  • Error Reduction: Type-constrained decoding reduced compilation errors by 74.8% on HumanEval synthesis and 56.0% on MBPP.
  • Functional Correctness: The pass@1 rate (the probability that the first generated solution is correct) increased by an average of 3.5% to 5.5% for synthesis and translation.
  • Code Repair: The method was particularly effective at fixing broken code, improving repair success by 37% on average.
  • Efficiency: Despite the added complexity, the runtime overhead is low. Because LLMs are "mostly right," the first token sampled is valid 99.4% of the time, requiring minimal re-sampling.

Conclusion and Future Work

By shifting the focus from syntax to formal type systems, this approach addresses the "heavy lifting" of program correctness. While currently requiring significant manual effort to model a language's type system, the results demonstrate that even the largest models benefit from formal guardrails. Future work includes automating the creation of these completion engines and integrating them into proprietary LLM APIs that currently restrict access to token probability distributions.

Summary updated

BibTeX
@article{mundler2025type,
  author = {Niels Mündler and Jingxuan He and Hao Wang and Koushik Sen and Dawn Song and Martin T. Vechev},
  title = {{Type-Constrained Code Generation with Language Models}},
  journal = {Proc. ACM Program. Lang.},
  year = {2025},
  doi = {10.1145/3729274},
}
Figure