HackerPapers

arXiv:2504.09246cs.LG

Type-Constrained Code Generation with Language Models

Niels Mündler, Jingxuan He, Hao Wang, Koushik Sen, Dawn Song, Martin Vechev

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, including state-of-the-art open-weight models with more than 30B parameters. The results demonstrate the generality and effectiveness of our approach in constraining LLM code generation with formal rules of type systems.

arXiv comments
Journal reference
DOI
doi:10.1145/3729274
Subjects
cs.LGMachine Learning cs.PLProgramming Languages

On Hacker News

Linked by 2 identifiable commenters in 2 comments across 2 threads, from Jun 2025 to Aug 2025. Found in 1 HN submission from May 2025 to May 2025. Open submission discussions.

Comments linking this paper, per year.

Discussed in comments2 threads

    • There are researches backing some sort of "typed language is better for LLM". Like https://arxiv.org/abs/2504.09246, Type-Constrained Code Generation with Language Models, where LLM's output is constrainted by type checkers. Also https://arxiv.org/abs/2406.03283, Enhancing…

      herrington_dView on HNParent context

  1. Implementing Logic Programming 1 comment
    • This paper appeared at PLDI '25: https://arxiv.org/abs/2504.09246 Discussed on HN at the time: https://news.ycombinator.com/item?id=43978357

      ashton314View on HNParent context

Submitted to Hacker News

Connected through shared HN threads, not inferred similarity or a recommendation.