# Can Large Language Models Transform Natural Language Intent into Formal Method Postconditions?

LLMs can turn informal code comments into checkable method postconditions

Madeline Endres, Sarah Fakhoury, Saikat Chakraborty, Shuvendu K. Lahiri · arXiv · 2023-10-3

- **Problem** Code comments can drift away from the implementation they describe, and existing tools cover only narrow cases, mostly in Java. Natural language is too ambiguous to check against code directly.
- **Method** nl2postcond prompts an LLM to write executable postconditions from a method's comment. Instead of whole-function assertions, the simple prompt asks for one aspect of the function.
- **Results** With GPT-4 and the simple prompt, 77% of EvalPlus postconditions were test-set correct, compared to 0.63 accept@1 for the base prompt. On Defects4J, the postconditions caught 64 real historical bugs.

![Figure 3: Prompt template for generating postconditions from natural language via chat models (including changes needed for thesimple and no reference variatio…](https://refivu.com/papers/cfece4bb-1558-4163-9369-9dfea374f585/figures/figure-008d8fffc6066f21dface8dc6ea46814.png?thumb=512)

**Fig. 3** . Prompt template for generating postconditions from natural language via chat models (including changes needed for thesimple and no reference variations). We found that the bold text greatly improved the quality of the postconditions: without it, the model tended to return point-based tests or code blocks with side effects. While modified here slightly for clarity, our full prompts are included in our replication package.

[Original paper](https://arxiv.org/abs/2310.01831v2) · [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/) · Madeline Endres, Sarah Fakhoury, Saikat Chakraborty, Shuvendu K. Lahiri · Can Large Language Models Transform Natural Language Intent into Formal Method Postconditions? · Original paper figure · Extracted the figure area from page 6 of the original PDF.

## Why comments and code drift apart unchecked

Informal intent in comments and docstrings can drift away from the implementation it describes. That weak association can leave bugs hidden, and it gets worse when users generate code straight from natural language. Reliably turning informal descriptions into formal specifications could catch such bugs before production. Other methods can only produce a restricted class of specifications, such as those about nullness or exceptions.

Most of these approaches are also customized for one language, such as Java.

Neural modeling for specification generation has been hard, because large code corpora pairing natural language intent with specifications are missing. LLMs were never trained on structured data that matches natural language intent to specifications. GPT-4 still shows emergent abilities on tasks it was not explicitly trained for, which motivates the authors' exploration.

The authors define a postcondition as an assertion relating the input and output states of a method, holding after any successful execution. They call this approach nl2postcond, which translates natural language method-level comments into postconditions.

A HumanEval example shows the problem: a docstring asks for a function that removes numbers with duplicates from a list. The docstring is ambiguous, because it does not say whether all copies of a duplicated element should be removed. Postconditions can make each possible intent checkable, so the programmer can confirm which one the code should meet.

## Asking an LLM for a postcondition from a comment

The model receives a method's natural-language comment and must return a postcondition, which the authors call nl2postcond. A postcondition is an assertion relating the method's input and output states, and it holds after any successful execution. Because the output is an assertion in the target language, the approach stays programming language-agnostic.

The prompt asks for symbolic, directly executable, side-effect-free expressions rather than point-wise tests. The prompt also encourages expressions that are syntactically and semantically valid. Figure 1 shows why this matters: the docstring for remove\_duplicates is ambiguous about whether all copies or one copy are removed.

The authors vary the prompt along two axes, whether the reference code is included and how complex the postcondition is. The base prompt tends to produce complex postconditions that strive for a fully functional implementation, and these are more likely to be incorrect. The simple prompt asks the model to capture one aspect of the function instead of the whole function.

Figure 4 contrasts a base postcondition that fails with a simple postcondition that checks for spaces in the return value, both generated with GPT-4 for HumanEval problem 12. Crossing the two axes gives four prompts: base or simple, each with or without the reference solution r.

Correctness is judged by test-set correctness, which checks whether the reference implementation satisfies a candidate postcondition on the test inputs. Completeness is measured with a bug-completeness score, the share of code mutants that the correct postconditions kill. The authors propose LLM-sampled mutants instead of operator-based mutants, because fixed mutation operators stay close to the reference implementation.

For the mutant pool, GPT-3.5 at temperature 0.9 generates 200 solutions per problem, and the authors keep only those that fail the test suite. They add 200 more buggy codes by instructing GPT-3.5 to include an error, and they retain only distinct buggy codes. The number of unique buggy codes per problem ranges from 4 to 233, with a median of 55.

## EvalPlus correctness and the effect of prompt choices

The EvalPlus benchmark contains 164 Python problems, each with a docstring, a reference implementation and validation tests. Its test suite averages 775 tests per problem, which extends the original HumanEval tests with a more extensive suite. For each problem, the authors generated 10 postconditions for each of the 4 prompt variants and each model, at a temperature of 0.7.

Across all variants, models and EvalPlus problems, this produced 19,680 postconditions. The four prompts cross two choices: whether the reference code r is included, and whether the base or simple prompt is used.

The simple prompt asks the model for a postcondition about one aspect of a function instead of the whole function. The authors added this variant because the base prompt often pushed LLMs toward complex postconditions that strive for a full implementation. Those complex postconditions were more likely to be incorrect, so the simple prompt targets narrower and safer assertions.

The best setting was GPT-4 with the simple prompt and no reference code, where 77% of postconditions were test-set correct. That setting produced a test-set-correct postcondition for 96% of problems, which is 158 of 164. Table 1 shows accept@1 of 0.77 for GPT-4 simple without reference code, compared to 0.63 for GPT-4 base without reference code.

![Table 1: Test-set correctness on EvalPlus for three models (GPT-3.5,GPT-4, andStarChat), differing prompt complexities (base vs.simple), and including or omitt…](https://refivu.com/papers/cfece4bb-1558-4163-9369-9dfea374f585/figures/figure-e06cceabcf7cd89b9ea33e79c0770f50.png?thumb=512)

**Table 1** . Test-set correctness on EvalPlus for three models (GPT-3.5,GPT-4, andStarChat), differing prompt complexities (base vs.simple), and including or omitting the reference solution in the prompt. Darker highlighted cells are more correct. Bolded values are the largest for a specific model.

[Original paper](https://arxiv.org/abs/2310.01831v2) · [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/)

Across prompts, GPT-4 reached accept@1 between 0.63 and 0.77, which made it the most likely model to produce correct postconditions. GPT-3.5 reached accept@1 between 0.46 and 0.56, while StarChat stayed the least correct at 0.21 to 0.25. The accept@k metric accounts for the stochasticity of model output, so the authors report it instead of a single sample.

Adding the reference code made no clear difference overall for these models. For GPT-4 with the base prompt, reference code raised accept@1 from 0.63 to 0.71, while the simple prompt moved only from 0.77 to 0.76. The authors report that high-level trends stayed the same across the temperatures they tried, so they reported 0.7 only.

## Which postcondition types kill more mutants

The authors first asked what the postconditions actually check, so they built coding categories for postcondition structure. The first two authors developed the categories and jointly labeled 230 postconditions, which came from GPT-4 with the simple prompt and no reference solution. The first author then labeled 670 more, for 900 labeled postconditions from 139 EvalPlus problems.

Many postconditions are not single checks; an LLM often joins several distinct properties with logical && operators. About 33% of the LLM-generated postconditions are conjoined in this way, so the categories count atomic parts separately.

The nine atomic categories cover type, format, arithmetic, container, element, implication and null checks. Type Checks use isinstance on the return value, while Arithmetic Equality ties part of the return value to another expression. Their average bug-completeness is 0.14 on natural bugs and 0.27 on all bugs, so they kill few mutants. Arithmetic Equality reaches 0.82 on natural bugs and 0.89 on all bugs, and it kills 89% of all bugs on average.

The authors saw no significant relation between postcondition type and correctness, but the completeness gaps were large. They suggest the Type Check result follows from the type hints in the EvalPlus stubs, which leaves type-mismatch bugs rare. The authors partly explain StarChat's lower completeness this way, because its correct postconditions were mostly atomic Type Checks.

Only 16% of GPT-4 postconditions were atomic Type Checks alone, and most of its Type Checks sat inside conjoined statements.

## Catching real bugs in Defects4J

Defects4J 2.0 provides 835 real bugs from 17 Java projects, and the authors kept only the 525 that reproduce when compiled for Java 8. Those 525 bugs modify 840 functions, and the authors generated postconditions for each modified function. A postcondition counts as test-set-correct only if it passes every trigger and regression test on the fixed version.

A postcondition is bug-discriminating when it passes all tests on the fixed function and fails at least one trigger or regression test on the buggy function. Because Defects4J changes between buggy and fixed versions are limited to the bug fix, the authors treat such a postcondition as tied to the bug.

Real functions are tightly coupled with project code, so the authors add class and type context to the prompt. Without file-level context, the LLMs rarely produced postconditions that also compiled. The natural language comes only from the buggy function's own comments, which in practice is mainly its JavaDoc, with no code summarization or external documentation.

The authors used the simple prompt because it gave more correct postconditions than the base prompt, in two variants with and without the buggy function body. Across two models and two variants, with 10 postconditions per function, the study evaluates 33,600 postconditions.

GPT-4 reaches accept@1 of up to 0.39 and accept@10 of up to 0.75, while StarChat reaches 0.12 and 0.56. Adding the buggy code to the prompt raises GPT-4 accept@1 from 0.32 to 0.39 in the test-set correct columns of Table 4. The authors hypothesize that the buggy code helps because the comments are not fully descriptive and the programs are more complex.

On EvalPlus the authors saw no such difference when they added the reference code, so the effect is specific to Defects4J.

![Table 4: Table containing our Defects4J results for postconditions generated for 840 methods across 525 historical bugs. We report the likelihood of generated…](https://refivu.com/papers/cfece4bb-1558-4163-9369-9dfea374f585/figures/figure-5b8e7f3d7712e34030fae6bd3cffa353.png?thumb=512)

**Table 4** . Table containing our Defects4J results for postconditions generated for 840 methods across 525 historical bugs. We report the likelihood of generated postconditions to compile, and the likelihood that they pass all tests when instrumenting the fixed function (test-set correct columns). # distinguishable bugs is the number of bugs for which at least one generated postcondition was discriminating (see Section 4.1.2).

[Original paper](https://arxiv.org/abs/2310.01831v2) · [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/)

GPT-4 generated bug-discriminating postconditions for up to 47 of 525 bugs, which is 9%. StarChat distinguished up to 25 bugs, so it caught fewer bugs than GPT-4. Across all prompt variants and both models, the authors found a bug-discriminating postcondition for 70 buggy methods from 64 bugs. Those 64 bugs make up 12.2% of the bugs considered.

The Math-9 revert example from the introduction is one of these bugs, and both GPT-4 postconditions detect it.

## How TOGA and Daikon compare with nl2postcond

The authors compare nl2postcond against TOGA, a neural method that generates test oracles for a focal method. They ran TOGA with EvoSuite test prefixes on 57 bugs, the set reported by TOGA's own authors. Of those 57 bugs, 15 were excluded from the nl2postcond evaluation because of Java limitations. Daikon appears only in a qualitative example, because neither TOGA nor Daikon supports Python.

The comparison therefore focuses on Defects4J, where each technique must produce tests or postconditions that distinguish historical bugs.

The authors reproduced TOGA's experimental setup from a released docker image, so each bug came with its EvoSuite test prefix and oracle. The two approaches answer different questions, since TOGA produces assertions for one test prefix while nl2postcond infers postconditions for all inputs.

In the Compress 11 case, TOGA catches the bug by simulating a small file and catching the resulting exception. A Daikon postcondition also distinguishes Compress 11, because the buggy function changes the class name of the input stream. nl2postcond does not catch this bug, so Compress 11 favors the two baselines over nl2postcond. Some algebraic specifications span several method calls, such as s.pop(s.push(5)) == 5, so a single postcondition needs auxiliary ghost variables.

Test oracles usually assert equalities on one input, whereas method postconditions can use arbitrary Boolean expressions over all outputs.

Prior work on specification inference mostly uses static analysis or dynamic analysis of existing code, while this approach infers desired behavior from natural language.

## Where the conclusions stop

The authors treat LLMs as black boxes, so they can't fully explain why the generated postconditions look the way they do. That opacity limits interpretability, and it raises questions about whether the results generalize. Because the AI landscape changes quickly, the reported results may become obsolete soon. EvalPlus and Defects4J are included in The Stack, the dataset used to train StarChat.

Both benchmarks may also have appeared in the training data of GPT-3.5 and GPT-4, which is a risk to internal validity. The authors argue that the target task partly mitigates this, because postconditions are not artifacts of either dataset.

OpenAI models are closed and are often updated or deprecated, which threatens replicability. The authors release all postconditions generated by the closed-access models to offset this.

The Defects4J evaluation covers only 525 bugs, so the findings may not extend to arbitrary bugs. The postcondition taxonomy is representative only of the programs in EvalPlus.

Completeness depends on a set of generated code mutants, which can never cover all possible bugs in a function. Even so, the completeness measure stays bounded by the range and quality of the mutants. The conclusion therefore claims feasibility and promise, not complete coverage of intent.

## Paper info

- **Authors**: Madeline Endres, Sarah Fakhoury, Saikat Chakraborty, Shuvendu K. Lahiri
- **Venue**: arXiv · Preprint
- **First published**: 2023-10-3
- **Added**: 2026-11-6
- **Updated**: 2024-4-15
- **Version**: v2
- **arXiv**: 2310.01831
- **Category**: cs.SE · cs.AI · cs.PL
- **Original paper terms**: [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/)
- **What we show**: Paper info, commentary and permitted figures from the original paper

[Original paper ↗](https://arxiv.org/abs/2310.01831v2) · [PDF ↗](https://arxiv.org/pdf/2310.01831v2)

AI commentary is a separate explanation from the original paper and may contain errors. The original paper and figures follow each source's terms of use and any rights noted separately.

## Abstract

Informal natural language that describes code functionality, such as code comments or function documentation, may contain substantial information about a programs intent. However, there is typically no guarantee that a programs implementation and natural language documentation are aligned. In the case of a conflict, leveraging information in code-adjacent natural language has the potential to enhance fault localization, debugging, and code trustworthiness. In practice, however, this information is often underutilized due to the inherent ambiguity of natural language which makes natural language intent challenging to check programmatically. The emergent abilities of Large Language Models (LLMs) have the potential to facilitate the translation of natural language intent to programmatically checkable assertions. However, it is unclear if LLMs can correctly translate informal natural language specifications into formal specifications that match programmer intent. Additionally, it is unclear if such translation could be useful in practice. In this paper, we describe nl2postcond, the problem of leveraging LLMs for transforming informal natural language to formal method postconditions, expressed as program assertions. We introduce and validate metrics to measure and compare different nl2postcond approaches, using the correctness and discriminative power of generated postconditions. We then use qualitative and quantitative methods to assess the quality of nl2postcond postconditions, finding that they are generally correct and able to discriminate incorrect code. Finally, we find that nl2postcond via LLMs has the potential to be helpful in practice; nl2postcond generated postconditions were able to catch 64 real-world historical bugs from Defects4J.

## Quote from the paper

Madeline Endres, Sarah Fakhoury, Saikat Chakraborty, Shuvendu K. Lahiri (2023). Can Large Language Models Transform Natural Language Intent into Formal Method Postconditions?. arXiv:2310.01831v2. https://arxiv.org/abs/2310.01831v2

**BibTeX**

```
@misc{endres2023large,
  title = {{Can Large Language Models Transform Natural Language Intent into Formal Method Postconditions?}},
  author = {Madeline Endres and Sarah Fakhoury and Saikat Chakraborty and Shuvendu K. Lahiri},
  year = {2023},
  eprint = {2310.01831},
  archivePrefix = {arXiv},
  url = {https://arxiv.org/abs/2310.01831v2}
}
```

## Other paper commentary

- [Evaluating the Ripple Effects of Knowledge Editing in Language Models](https://refivu.com/en/papers/b5a70e67-045a-47b7-96d8-dbc886057a9e-evaluating-the-ripple-effects-of-knowledge-editing-in.md)
- [Safety Guardrails for LLM-Enabled Robots](https://refivu.com/en/papers/c1fe3394-f384-4a56-aef5-471e70d0ad0d-safety-guardrails-for-llm-enabled-robots.md)
- [Prompting Is Programming: A Query Language for Large Language Models](https://refivu.com/en/papers/688fcde1-89d3-44fe-b9ec-673455f09c78-prompting-is-programming-a-query-language-for-large.md)
- [Sentence-BERT: Sentence Embeddings using Siamese BERT-Networks](https://refivu.com/en/papers/805208af-12ea-4b4b-b1a8-6db7601b1c37-sentence-bert-sentence-embeddings-using-siamese-bert.md)
- [Generative Spoken Dialogue Language Modeling](https://refivu.com/en/papers/be19b5cf-8acb-438c-a9c6-9a9ddd759fc3-generative-spoken-dialogue-language-modeling.md)
- [Decision-Oriented Dialogue for Human-AI Collaboration](https://refivu.com/en/papers/1d9fad4b-76a3-40b2-b7c6-3b42b2a8ddc5-decision-oriented-dialogue-for-human-ai-collaboration.md)
- [Feature Completion for Occluded Person Re-Identification](https://refivu.com/en/papers/a75a797b-335d-4d23-a90d-3fa4caea8e1c-feature-completion-for-occluded-person-re-identification.md)
- [Learning Robust Autonomous Navigation and Locomotion for Wheeled-Legged Robots](https://refivu.com/en/papers/d721c896-f444-49d4-9962-484aef58a0b3-learning-robust-autonomous-navigation-and-locomotion-for.md)
- [BinsFormer: Revisiting Adaptive Bins for Monocular Depth Estimation](https://refivu.com/en/papers/7fc81cb2-3782-4326-9ffa-5af4ea6fe25b-binsformer-revisiting-adaptive-bins-for-monocular-depth.md)
- [Unifying Flow, Stereo and Depth Estimation](https://refivu.com/en/papers/a17a6b8c-5864-4598-9183-8a1c09180428-unifying-flow-stereo-and-depth-estimation.md)
- [Moving Object Segmentation in 3D LiDAR Data: A Learning-based Approach Exploiting Sequential Data](https://refivu.com/en/papers/36e15bd6-0697-40e1-86f7-8a11dca9344b-moving-object-segmentation-in-3d-lidar-data-a.md)

## Terms in this paper

- [GPT-4](https://refivu.com/en/terms/1e2d0d2cdc44-gpt-4)
- [HumanEval](https://refivu.com/en/terms/3c3dbcadfdda-humaneval)
- [GPT-3.5](https://refivu.com/en/terms/30414fb33dba-gpt-3-5)
- [prompt template](https://refivu.com/en/terms/a6ed550cd87c-prompt-template)

---

AI-written text can contain mistakes. [Refivu](https://refivu.com/en/papers/cfece4bb-1558-4163-9369-9dfea374f585-can-large-language-models-transform-natural-language-intent)
