Elamur Research

Learning to Update Natural Language Comments Based on Code Changes

Paper · 2020 · Sheena Panthaplackel, Pengyu Nie, Milos Gligoric et al.

Summary

A change to a method can leave its documentation saying something that used to be true. If the method starts returning an angle in degrees, the useful revision may be a short phrase about the unit. The rest of the comment can still describe the same value in terms familiar to the project’s developers. This paper treats that situation as a distinct task. Given the old method, its existing comment and the revised method, the system suggests how to update the comment. The authors study Java’s Javadoc @return descriptions, which document the value a method gives back.

The system compares the method versions and marks which stretches of code were added, removed, replaced or retained. It reads that difference alongside the previous comment. Separate recurrent encoders represent the code changes and the comment, and a decoder consults both while writing instructions for the revision. It can copy words from either input. The instructions specify additions, deletions and replacements, with nearby words serving as anchors where needed. Applying the instructions automatically carries over the rest of the comment. Features such as matches to tokens in return statements help connect the inputs, and a final scoring pass favors candidate comments that read naturally for the revised method and stay close to the original wording.

The authors build their dataset from GitHub histories, looking for consecutive versions in which developers changed both the Java method and its return description. Filtering leaves 7,239 examples from 1,081 projects. The experiments assign different projects to training, validation and testing. The edit system performs better than rules and full-comment generators on measures that emphasize whether the required wording changes were made. In a study where Java readers chose among suggested revisions, they also selected the reranked edit system’s suggestions more often than the alternatives. A comparison with the same inputs and a different output target supports the decision to train on edit instructions, and removing the linguistic and lexical features weakens performance across the reported metrics.

Exact agreement with the developer’s revision remains uncommon, and several measures tell different stories about the same output. Copying the old comment earns a relatively high word-overlap score, for example, even when it leaves a stale description intact. Study participants chose none of the suggestions in 55% of the judgments, a response that covered both unnecessary updates and inadequate suggestions. Some correct revisions also required knowledge outside the displayed method. The authors release the implementation and data in the LearningToUpdateNLComments repository.

Deep dive: Learning to Update Natural Language Comments Based on Code Changes

Learning to Update Natural Language Comments Based on Code Changes uses edits to revise Java return comments while preserving wording that still applies. · about 36 minutes to read

The problem and its context

A comment can be partly out of date

Comments tell developers what to expect from code. The paper gives examples ranging from a description of functionality to the conditions under which code can be used and the guarantees it makes afterward. Those descriptions can matter to people who did not write the implementation, especially when many developers work on the same project. As functionality changes and code is reorganized, an old description can remain in place. The authors point to earlier work connecting these inconsistencies with time spent resolving confusion and, in some cases, with bugs.

An outdated description can contain both a useful explanation and a misleading detail. The paper illustrates this with getRotX in the Rajawali project. In the older version, the method passes back the result of getRotationX directly. In the newer version, it applies Math.toDegrees to that result. The revised return description specifies degrees while preserving its description of the angle. To make that revision, a system needs to identify what the new call changes, recognize that the change affects the value being documented, and decide where the unit belongs in the old sentence. Those decisions connect a small modification in the source to a small modification in the prose.

Preservation has a practical role in this setup. A comment can convey useful information that a short method body leaves implicit or expresses through project-specific names. The previous description gives an updater access to the wording a developer has already chosen for that information. The changed source supplies evidence for which part of the description may need attention. An updater therefore works with a different set of inputs from a system asked to explain a method by itself. The question is how to reconcile an existing account with a particular change in code and programming languages.

The authors start with a narrow documentation field. A Javadoc @return entry describes the output of a method and has a recognizable place in the documentation. Earlier work by the authors studied associations between entities in these descriptions and entities in the source. Here, the task adds a relationship across versions. The previous method and comment supply the starting point, and the current method supplies the evidence for revision. A developer’s revised description is available for training and evaluation. At prediction time it is the answer the system is trying to produce.

What existing tools could do

The paper describes prior rules that could flag certain kinds of inconsistency between comments and programs. Detection can tell a developer that a description deserves inspection. The task here asks for the wording of a possible repair. The authors also discuss related work that could revise outdated API names in documentation. That approach works on a particular kind of reference. A revision such as adding the unit of a return value calls for a broader capability, since the change in meaning can require words that are absent from the old description.

A different line of work used program analysis and heuristics to propagate comments among code elements. The idea was to find useful documentation elsewhere and transfer it to an element with an incomplete or defective comment. In this paper, the existing comment already belongs to the method that changed. The missing evidence is what happened between the two method versions and how that should affect the prose. A related comment might offer useful wording, but identifying the consequence of the change is still the core problem.

Automatic code summarization supplies another point of comparison. The authors describe systems that take a representation of code and produce a comment. Such a system can be applied to the newest method alone, and its training data can come from ordinary pairs of methods and comments. Work on comment generation included neural approaches to summarization. The attraction is that the newest code is enough to request a draft. The cost is that the generator starts without the old author’s description, including details that still apply. Comment generation is therefore a realistic competitor, especially if there are far more examples for training it.

Commit-message generation also learns from code changes. Its output describes what happened in a change, whereas a return comment describes what the method now returns. In the angle example, a commit message could discuss the introduction of a conversion. The revised return description can simply state the unit. The distinction affects which information belongs in the final prose. The paper also places its work alongside research that learns representations of code edits so they can be applied to new code. Here the learned representation has to support a decision about natural language.

Editing with evidence from another source

The paper draws a connection to work on simplification, style transfer and grammatical correction. Those tasks already supplied examples of systems that revise text by predicting edit actions. EditNTS uses explicit edits for simplification. Parallel Iterative Edit Models are cited in connection with local editing, and Delete, Retrieve, Generate is cited in connection with style transfer. The common ground is that an existing sentence can supply material for its revision. For comment maintenance, the main evidence for the necessary change comes from outside that sentence.

The authors identify fact-guided sentence modification as an especially close predecessor. In that setting, a new factual statement supplies evidence for updating an older statement. The corresponding evidence here is a change in a program, usually represented by a sequence longer than a sentence. A change in a return expression can make a particular word obsolete, demand a new qualification, or leave a description at the same level of abstraction fully adequate. Even a clear description of the code change only starts the work of deciding how to express the revised behavior.

The paper frames its contribution as both a task and an approach to it. The task is to produce an updated comment from the old comment and the old and new method versions. The approach is to make the changes explicit at both ends of the learning problem. The input identifies what moved in the code, and the output identifies what must move in the comment. That framing gives the experiments a concrete question. If the existing prose and the code evidence are both available, does it help to make the system predict the revision as a sequence of actions?

The method, step by step

The inputs, the target and the prediction

Both versions of the method and the earlier comment serve as the method’s starting point. During training there is also a later comment written by a developer. The first comparison builds the code input from the two method versions. The second comparison, available during training, turns the earlier and later comments into the desired editing instructions. The system learns from these paired comparisons. At prediction time it receives the code comparison and the earlier comment, writes a candidate set of instructions, and applies those instructions to produce a readable comment.

From a Java method change to an updated comment

The steps in order.

From a Java method change to an updated commentStep 1: Tokenize both methods and the old comment1. Tokenize both methods and the old commentStep 2: Mark changed and retained spans in code2. Mark changed and retained spans in codeStep 3: Encode the code difference and comment separately3. Encode the code difference and comment separatelyStep 4: Decode candidate comment edits with copy support4. Decode candidate comment edits with copy supportStep 5: Apply each candidate to the old comment5. Apply each candidate to the old commentStep 6: Rerank the resulting comments6. Rerank the resulting comments

The task can be written as the following input and output relation.

(M_old, C_old, M_new) → C_new

M_old and M_new are the earlier and later versions of the same method. C_old is its existing comment. C_new is the developer’s updated comment when an example is used for training or testing, and the desired output when describing the task. The parentheses collect the inputs, the commas distinguish their roles, and the arrow indicates the requested prediction. The method’s intermediate code difference is M_edit. Its intermediate sequence of comment actions is C_edit. When discussing predictions, the paper uses a prime to distinguish the predicted actions C′_edit and their resulting comment C′_new from the developer-derived versions.

This intermediate output changes what the decoder is responsible for. In the Rajawali example, it needs to express the insertion about degrees and locate that insertion near the end of the sentence. The description of the angle can come through the original comment when the instructions are applied. A full-comment decoder would be scored as it produces all those words, both the ones it needs to carry forward and the ones that express the change. The authors reason that when the predecessor and successor comments are very similar, a learner given the full target can get much of that target right by copying. Predicting actions makes the changed portions the focus of training.

Turn the method versions into a readable difference

Before comparing the versions, the authors use javalang to split the Java source into tokens. They then divide names written in camel case or with underscores into smaller units. For instance, a camel-case identifier can contain a recognizable verb and noun inside a single Java token. The division makes those parts available for direct comparison with words in the comment. This process is a form of tokenization. The authors also divide comments at whitespace and punctuation, remove the leading Javadoc tag and HTML tags, and apply the same splitting of identifiers because identifiers can appear inside prose.

The paper uses Python’s difflib to align the old and new token sequences. Each part of the alignment is marked as Insert, Delete, Replace or Keep. An insertion records what appeared on the new side, a deletion records what was on the old side, and a Keep span records shared context. Replacement needs fields for both sides, since the new words or symbols are relevant evidence alongside the ones that disappeared. A single-span action uses the following general pattern.

<Action> span <ActionEnd>

The angle brackets mark special action tokens. Action stands for the operation being opened, and ActionEnd stands for its corresponding closing token. span stands for the contiguous sequence governed by that operation. In the code difference, the span contains code tokens after the preprocessing described above. A replacement has a different shape.

<ReplaceOld> old_span
<ReplaceNew> new_span
<ReplaceEnd>

<ReplaceOld> opens the portion containing old_span, the sequence being removed from its position. <ReplaceNew> opens new_span, the sequence taking its place. <ReplaceEnd> marks the end of the entire replacement. The underscores join the words used to name each placeholder. The line breaks make the fields visible here. The data representation is a token sequence containing the markers and their contents.

A difference over tokens can expose a small change inside a source line. In the conversion example, the new call wraps an expression that was already there. The changed tokens carry the information about the conversion, and the retained tokens show which return expression is being converted. A line-level difference could show the old and new lines as separate stretches of text. The paper’s token-level difference makes their common material explicit. The authors connect line-level differences to earlier work on commit messages and leave open an alternative that would represent changes to the structure of the parsed program.

The code difference is still a comparison of written forms. A Replace label tells the system that one stretch takes another’s place, but the significance of the replacement must be learned in context. In the angle example, the evidence includes the name of the new call and its position around the former return expression. It does not include a generated explanation of the conversion for the decoder to read. The decoder has to use the source evidence to choose its own words and determine which part of the comment they affect.

Write a compact target for the comment

The comment comparison starts from the same idea of marking changed spans. Its output has a different job. The code difference will be read as evidence, and the comment difference will be executed against a string of existing words. Any comment span that survives untouched can be copied during execution. The authors therefore drop ordinary Keep actions from the training target. They call the resulting target a condensed edit sequence. It contains the changes and any context needed to place them, while leaving most of the unchanged comment outside the sequence the decoder must produce.

With Keep spans removed, position becomes a problem. An instruction containing only the words to add can place them anywhere in the old comment. A deletion naming a repeated word can refer to several positions. The condensed format resolves this by borrowing adjacent unchanged words. The authors search for a stretch that occurs uniquely in the earlier comment. The borrowed words appear in both the old and new fields of the action, so matching the first field gives a location and writing the second field preserves the anchor.

For getRotX, the anchor is angle. The old field identifies that word, and the new field contains the same word followed by the phrase about degrees. Taken literally, the operation replaces its old field with its new field. At the level of the sentence, the effect is an insertion after the anchor. The previous description stays in place while the unit becomes explicit. Choosing an anchor from the original comment also makes it possible for the decoder to copy that word from an input.

When a word occurs repeatedly, the necessary anchor can include additional context. The appendix uses short symbol sequences to show why. In ABCB, the first B can be identified by the sequence AB. A change of that B to D then becomes a change from AB to AD, with A preserved in the two fields. When the earlier comment is ABCAB, the sequence AB is itself repeated. In the paper’s corresponding example, BC uniquely locates the first B, and replacing BC with DC preserves the following C. Here the letters stand for tokens and the strings list them in order.

The formats distinguish whether the anchor comes before or after the changed material. The following pattern describes the two-field family. The labels shown are placeholders for the lexicon’s concrete special tokens.

<OperationOldSide> matched_span
<OperationNewSide> written_span
<OperationEnd>

Operation stands for Insert, Replace or Delete in the anchored cases. Side stands for the marker suffix KeepBefore or KeepAfter. Old marks the field that has to match the existing comment, and New marks the field to write in its place. matched_span and written_span are the old and revised stretches of tokens. The matching stretch includes enough unchanged context to anchor the edit. The written stretch includes that same context. End closes the named operation, and the angle brackets distinguish the markers from the text they govern.

The search tries unchanged context before the edit and uses following context when the preceding words cannot supply a unique match. An insertion at the beginning of a comment illustrates why following context is needed even when there is no repetition. For a replacement, a unique old span already identifies a position, so it can use the ordinary replacement format. For a deletion, a unique span can simply be marked with <Delete> and <DeleteEnd>. A repeated deletion target can use the before or after variants. Its old field carries the anchor and the material to remove, while its new field carries only the anchor. All comment insertions need an anchor in this representation.

The different action labels let the training target say what the shared words are doing. A new-field token can be a word newly introduced into the comment or a word retained to locate the action. An anchored insertion retains all of its old field, while an anchored deletion retains only the unchanged portion. The concrete case can still be applied as a replacement of one identified span with another. This gives the parser a common way to handle several operations and gives the decoder markers that distinguish the kinds of revisions it is learning to write.

Encode the old wording and the changed code

The system reads M_edit and C_old in separate recurrent encoders. Each is a two-layer bidirectional gated recurrent unit, or GRU. A GRU builds a sequence of hidden states as it reads tokens. Those states carry forward a learned account of the sequence, with gates controlling how information from earlier positions contributes. In a bidirectional encoder, reading in both directions lets the representation at a position depend on material on either side. The GRU design comes from work on recurrent encoder–decoder systems. Learning Phrase Representations using RNN Encoder–Decoder for Statistical Machine Translation

The separate encoders give the decoder a way to look at the structure of the source change and the wording of the comment independently. The system joins their final states into the starting state of a recurrent decoder. It also retains the states at individual input positions. These position-specific states matter because the decoder will need different evidence as it goes. Selecting a passage of the old comment calls for close attention to the old wording. Producing the replacement can call for close attention to an inserted identifier or another changed part of the method.

At each decoding step, the system computes attention over each encoder separately. In this setting, attention lets the decoder use its current state to weight input positions and obtain a context vector. The system thus obtains one context from the comment and one from the code difference, then concatenates them and uses them in the attention calculation for the decoder. The two lookups let the current step draw information from both sequences. In the angle example, old wording near the end of the comment and new source tokens naming the conversion are evidence for different parts of the same revision. Effective Approaches to Attention-based Neural Machine Translation

The decoder produces the action markers and the words between them as a single sequence. Depending on its progress through an action, the next symbol can open an edit, contribute to a span, or close the edit. A copy mechanism gives it access to tokens in the old comment and the code difference. This is useful when an action needs to repeat an exact anchor or refer to a term introduced on the new side of the code comparison. The ability to choose a word from a source position complements the ability to generate words. Pointer Networks

Give the encoders direct clues about relevance

The authors augment the input embeddings with features intended to help the encoders recognize useful patterns. An embedding represents a token with a learned vector. The added features encode categories and matches explicitly. They are joined to the embeddings and passed through a linear layer before encoding. The resulting representation supplies both the token’s learned identity and clues about its role in the current example. The features reflect an earlier study of links between return comments and source-code entities.

On the code side, features distinguish edit markers, Java keywords and operators. A code token inside a span is also associated with its operation, including whether it belongs to the old or the new side of a replacement. This matters in longer spans. The end markers can be far from a particular interior token, and a direct signal gives that token its status at the input. A match against the earlier comment indicates that the same word occurs in both source and prose. Such overlap can help the system find a relevant region even before it learns what the code change means.

On the comment side, the system marks whether a word matches code that has been inserted, deleted or replaced. It also records whether the word recurs in the comment, whether it is a stop word and which grammatical category it belongs to. Recurrence is relevant to placement because a common string may need a larger anchor. Grammatical categories distinguish, for instance, a word acting as a verb from a noun used to name the object being returned. The feature for grammatical category comes from part-of-speech tagging.

Some information is shared across both inputs. Once an identifier has been split, the system marks that its pieces came from a larger token and records their order inside it. The authors also indicate whether an input token matches material in a return statement found only in the old method, only in the new method, or in both. They do the same for tokens in the method’s declared return type. A feature tying a word to a return statement gives it a different role from a word occurring elsewhere in the same method. The representation is designed around the documentation field being revised.

These features make different aspects of the evidence accessible. A comment word can match an identifier on the old side, which may help find text whose basis has changed. A token in the new return expression can suggest wording for an insertion. A repeated word can signal a need for more context in the locator. The encoder and decoder still have to combine those signals with the rest of the example. The same match can be useful in one comment and incidental in another, depending on what the prose actually says about the returned value.

Apply the instructions and score the resulting prose

The predicted actions have to be converted to a comment before they can be displayed or evaluated. The parser traverses the earlier comment and the predicted instructions from left to right. The paper calls the traversal pointers P_old and P_edit. The first follows C_old, and the second follows C′_edit. The parser copies tokens from the old comment until it reaches the next edit location. It then applies the corresponding action and advances past the affected span when appropriate. The process continues through the remaining actions and the remaining comment, yielding C′_new.

These parser pointers and the decoder’s learned copy mechanism do different work. The decoder uses its copy mechanism to write an action whose words can come from the inputs. The parser uses its pointers to execute the completed action and recover all the material the decoder was free to omit. The practical benefit of the condensed format appears at this stage. The final prose can retain a long stretch of the old description even though that stretch was absent from the predicted instructions. A correctly written anchor fixes where the localized change belongs.

At inference, beam search keeps several promising partial action sequences as decoding proceeds. The paper uses a beam width of 20. The system can then compare several completed candidates, each initially scored by how it was produced. The authors add a scoring pass after parsing because an action sequence can look plausible as an edit while yielding awkward or unsuitable prose. The additional scores examine the result as a complete comment, where both the newly written and the preserved text are present.

One score comes from a separately trained comment generator. Given the new method, it assigns a probability to the candidate comment. The authors normalize the probability by comment length so candidates can be compared using a score on a per-token scale.

G = P(C′_new | M_new)^(1/N)

G is the normalized generation score. P is the probability assigned by the comment generator, C′_new is the parsed candidate and M_new is the revised method. The vertical bar indicates that the probability is conditional on that method. N is the number of tokens in the candidate comment. The caret marks exponentiation, and 1/N is the reciprocal of the token count. This score favors comments that the generator regards as plausible descriptions of the updated method and consistent with the style it learned from training comments.

The other additional score measures similarity to the old comment. The authors use METEOR for this comparison. A candidate can gain from preserving much of the old text, while the generator’s score can favor wording appropriate to the new source. The original beam score still contributes the largest weight. The weights were tuned on the validation data.

R = 0.5 × B + 0.3 × G + 0.2 × S

R is the final reranking score, B is the original beam score for the candidate instructions, and G is the length-normalized generation score of the parsed comment. S is the METEOR similarity of that comment to C_old. The multiplication signs apply the respective weights, and the plus signs add the weighted terms. The score combines evidence about the proposed action sequence, the suitability of the complete prose for the new method, and the extent to which the old wording survives.

Learn from revisions that developers made

Mining a training example requires finding the same method in consecutive commits, with both a source change and a change to its @return description. The authors filter out cases in which neither the return type nor a return statement changed. They keep method names stable as a way to match versions, screen out apparent spelling or formatting revisions and other stylistic changes, and remove duplicates. The duplicate removal responds to concerns raised in earlier work on evaluation of learned code systems. The Adverse Effects of Code Duplication in Machine Learning Models of Code

The cleaned examples give the paper separate training, validation and test projects. The training vocabulary admits words seen at least twice in the training data and includes the designated edit markers. The authors report a code vocabulary of 5,945 and a comment vocabulary of 3,642. The comment generator is trained separately on method and return-comment pairs. Its learned embedding vectors initialize the corresponding embeddings in the edit system. Its sequence probabilities are used again during reranking. Those are distinct uses of the larger corpus, one during initialization and one when choosing among completed candidates.

The hidden dimensions are 64 for the encoders and 128 for the decoder, and both types of embeddings, for code and for comments, are 64-dimensional. Training uses Adam with an initial learning rate of 0.001, a batch size of 100 and dropout of 0.6. The training objective is negative log likelihood, which penalizes assigning low probability to the desired output sequence. In the editing system that sequence consists of the developer-derived actions. The authors stop training when validation loss has gone ten consecutive epochs without decreasing. They use the same reported parameter settings for the edit system and the generator.

Experiments and results

A test of revisions across projects

The final revision corpus contains 7,239 examples from 1,081 projects. Of the corpus examples, 833 came from differences used in the authors’ earlier work on linking return comments to code. Each example gives the experiment a previous comment, both source versions and a developer’s revision. The 736 examples in the test split also supply the pairs of new method and revised comment on which the generator is evaluated. All systems are consequently assessed against the same new comments, even though the inputs used to make their predictions differ.

The project split matters because a random split over individual examples could place very similar examples on both sides of the evaluation. The authors hold out whole projects for testing and use disjoint projects for validation as well. They also keep the projects used to train the generator separate from the test projects. This evaluates whether the systems can apply their learned associations and rules to held-out projects drawn from the same collection process. Removing duplicates serves the related purpose of reducing repeated material in the corpus itself.

The generation baseline has a training advantage in volume. The authors collect 103,473 pairs of Java methods and @return descriptions for it. Those pairs require only a code snapshot with an accompanying comment. An editing example requires a usable correspondence between code and comment before and after a change, as well as a meaningful relationship between the changes on both sides. The difference in collection requirements explains why a generator is an attractive alternative. It can learn from more instances without needing developers to have revised the code and prose together.

What the alternatives predict

The simplest baseline copies the old comment. It establishes how much of the evaluation can be satisfied by retaining the wording the developer already had. The return-type rule makes a specific update when the declared type changes and the previous type occurs in the comment. In that case, it substitutes the new type and keeps surrounding words. Otherwise the old comment can pass through. The null-handling variant also looks for addition of null in a return statement or an if statement. The authors added this check after seeing cases where a change began to handle null input or produce a null result.

The neural generator reads the new method and produces a full comment. Like the updater, it uses a bidirectional recurrent encoder and an attention-based recurrent decoder with copying. Its code input is the newest method, and its training target is the comment accompanying that method. The shared architectural choices keep this comparison focused on a practical difference between the approaches. The full generator gets a larger training collection, while the updater gets fuller evidence about the individual revision and an output format that concentrates on it.

For the reranked generator, the old comment becomes available when selecting among candidates. This allows a new-method description that resembles the earlier wording to move up the list. The generator itself still learned to produce comments from methods alone, and its initial candidate list comes from that process. Validation tuning gave equal weight to the beam score and to the METEOR similarity with the old comment.

R_gen = 0.5 × B_gen + 0.5 × S

R_gen is the rerank score for a candidate produced by the full-comment generator. B_gen is the candidate’s original beam score, and S is its METEOR similarity to the old comment. The multiplication signs apply the two weights of 0.5, and the plus sign combines the scores. Compared with the updater’s reranking, this variant starts from candidates that already are comments. The ranking step asks which of those comments best balances generation evidence and closeness to the previous description.

What the automatic scores reward

Exact match is the percentage of test examples on which the final prediction is identical to the reference comment. It gives a clear test of whether the complete revision was recovered. It also imposes a strict requirement when several wordings can document the same value. METEOR and average sentence-level BLEU-4 provide less strict comparisons with the reference. The latter rewards overlap in sequences of words and is familiar from work on language generation. The underlying measure is the BLEU score.

The authors also choose metrics that examine how text changes relative to its source. SARI scores the sequences of words that an output adds, deletes and keeps, with credit tied to the changes and retained material in the reference. The paper describes the version used as averaging F1 scores across those actions. F1 combines precision and recall, so the comparison considers both whether the predicted action choices are appropriate and whether they cover the relevant material. The measure originated in text simplification. Optimizing Statistical Machine Translation for Text Simplification

GLEU also uses the source sentence and gives extra importance to sequences that have been changed correctly. This addresses a problem that arises when the reference inherits much of the source. A candidate can overlap heavily with the final comment by reproducing its starting point. The edit-sensitive metrics use that starting point as evidence about what kind of agreement was achieved. The paper reports automatic results for learned systems averaged across three random initializations and uses bootstrap tests to assess statistical significance.

The full generator improves when its predictions are reranked against the previous comment, yet generation remains weaker than the alternatives across the automatic metrics in the reported comparison. The authors connect that result to the difference in context. The generator has many more training examples, but the new method alone shapes its candidate list. A candidate that would preserve the useful old wording while making the needed local change has to appear in that list before similarity can reward it. The updater learns to work with that old wording from the start.

Among the edit systems, reranking improves performance significantly on most automatic measures while slightly lowering SARI. Both edit configurations achieve statistically significant advantages over the other systems on SARI. The edit approach also fares better on exact match and GLEU in the comparisons the authors emphasize. BLEU-4 gives a different ranking. Two rule baselines score slightly above the best edit system on that metric, and the paper reports that those differences are statistically indistinguishable. Copying alone reaches a BLEU-4 score of 46.218 on the revision test set.

The rates of unchanged predictions show what the BLEU-4 comparison can conceal. The return-type baseline repeats the old comment on 74.73% of the test examples, and the variant with null handling repeats it on 65.76%. The reranked updater repeats it on 9.33%. Since the test references come from commits where the return comment was revised, these rates show how often the systems leave the input as it was in a collection built around observed changes. They are measures of the systems’ willingness to act in this setting. Whether each action was appropriate is a separate question for the edit scores and the human judgments.

Unchanged predictions on the Java comment-update test set

The reranked edit system leaves the prior comment untouched much less often than either rule baseline.

Unchanged predictions on the Java comment-update test setReturn type substitution: 74.73Return type substitution74.73Return type substitution with null handling: 65.76Return type substitution with nullhandling65.76Reranked edit system (this paper): 9.33Reranked edit system (this paper)9.33
The numbers
System or settingPredictions identical to the old comment %
Return type substitution74.73
Return type substitution with null handling65.76
Reranked edit system (this paper)9.33

The same test evidence explains why exact match and BLEU-4 can coexist with very different impressions of an updater. A baseline that predicts no change can recover many of the right words because the developer retained them too. Even a method that typically takes action can still miss exact match if it chooses a suitable alternative expression or makes an additional wording change. The paper’s editing measures look more directly at the words that moved, and the human study takes up the question of whether a proposed revision makes sense given the code.

How readers judged the suggestions

The human evaluation imitates a situation in which an editor or development environment offers comment revisions after a code change. Participants see the old comment and the difference between the method versions in GitHub’s diff interface. They choose the most suitable comment from the offered suggestions. They can select more than one when those options are equally good, and they can choose None if the old comment needs no update or if all the displayed revisions are poor. This makes the evaluation a choice about an actual suggestion in context.

Candidates come from the return-type rule with null handling, the reranked generator and the reranked edit system. Their presentation order is randomized. Identical predictions are shown once, and if a participant selects the shared suggestion, all systems that produced it receive credit. A prediction identical to the old comment is omitted. The researchers exclude 6 test examples on which all three systems produced the old comment, since there would be no proposed revision to show on those examples. Accordingly, the measure combines whether a system offers a changed candidate with whether readers consider that candidate suitable.

The participants are nine students, described as 8 graduate and 1 undergraduate, and one full-time developer. All have 2+ years of Java experience. Each example is judged by two readers, making it possible to evaluate agreement despite the option to select several suggestions. The study includes 500 judgments over 250 distinct test examples. Agreement measured with Krippendorff’s alpha using MASI distance is 0.64. MASI is used here because a response can be a set of chosen suggestions. Measuring Agreement on Set-valued Items

The reranked updater’s suggestions are picked more frequently than those of either alternative by statistically significant margins. Written explanations from two annotators give an example of why a plausible new comment might lose. Some suggestions drop relevant content that was present in the old description, an issue the authors frequently associate with the generation approach in those explanations. Since the old comment was visible, readers could assess whether a concise new description had kept the information they wanted as well as whether it read sensibly in isolation.

None was chosen in 55% of the human judgments. Inspecting a sample, the authors found many cases in which the old description still seemed adequate. Others illustrate the remaining difficulty of proposing a good revision. The response option groups these situations together, so its rate describes how frequently the displayed choices failed to yield a selected update. It cannot on its own establish how often updates were necessary. The preference for the reranked edit system and the frequency of None can both hold in the same experiment, because the former compares alternatives and the latter reflects their usefulness across the judged instances.

What the ablations show

Make the same evidence support different outputs

The main generator comparison changes several things at once. It changes how much training data is available, what is visible at generation time and what kind of output is predicted. The authors therefore run a separate set of comparisons inside the updater’s architecture. They switch off the added features and reranking for these experiments, and they keep the earlier comment available. They then vary the code representation and whether the decoder is trained on the full revised comment or on the condensed actions.

The alternative code inputs are the new method alone, the old and new methods encoded independently, and the explicit code difference. In the separate-version setup, the hidden states from the code versions are concatenated. This gives the learner access to both versions while leaving comparisons between their contents implicit. The difference representation aligns the versions in advance and gives local labels to the changes. The setup allows a question that the larger generator comparison cannot isolate. Given access to the same preceding comment and the same code representation, what happens when the target is changed from full prose to edits?

The authors report that the comparisons favor predicting edits. With the code input fixed, the difference in output target changes what the system is trained to recover. In the full-comment condition, it must produce all the retained words along with the changes. In the edit condition, the parser supplies the ordinary retained material, and a predicted sequence records changed spans and their anchors. The controlled results support this way of allocating work within the tested architecture. They give evidence for the edit target even after taking away the extra features and final scoring pass.

A complementary comparison fixes the edit target and varies the code input. Explicitly giving the decoder an encoded difference improves most metrics significantly compared with the alternative method representations. That matters because separately encoded old and new code already includes the material on both sides of the change. The difference adds a representation of how that material lines up, so the system can attend to marked changes and the surrounding context. In combination, the experiments support making both sides of the cross-language relationship explicit. The code difference supplies evidence about what changed, and the comment actions specify how the prose responds.

Remove the features or change the final choice

The paper also removes the linguistic and lexical features as a group. With those features, performance improves across all the reported automatic metrics. The group includes direct matches between code and prose, matches specific to the method’s return type and statements, grammatical information about comment words, and clues about the role of subtokens and edit spans. The result establishes that the group helps under the paper’s setup. Its design leaves the relative contribution of individual features open. A test removing return-statement matches alone would answer a different question from removing the entire group.

Reranking provides a separate comparison because it changes the choice among completed candidates. Its modest loss on SARI alongside gains on most other automatic measures shows that changing the final score can shift the kinds of revisions selected. The reranker combines the original score with the probability of the complete comment under the generator and with similarity to the earlier comment. SARI asks how well additions, deletions and retentions correspond to the reference. A candidate favored by the overall scoring combination can therefore earn a worse score for those operations. The reported result concerns the combined reranker and leaves the individual effects of its two additional terms unresolved.

The authors mention an attempted alternative that trained the comment generator jointly with the editor. Performance deteriorated in that attempt. The result is relevant to the chosen use of the generator, which contributes learned embeddings and then scores completed prose. The paper gives the direction of the joint-training result without establishing which part of the joint setup caused it. The score comparison for reranking is more specific because it contrasts the edit system’s predictions with and without the final selection step.

Where the kind of error changes

The qualitative analysis shows an instance where correct revision depends on a method outside the immediate input. In the Eclipse January project, getComplex stops taking an index and begins calling get without an argument. The revised comment identifies the returned item as the one in the first position. To derive that fact from the implementation, a reader needs to know what the no-argument get does. The changed call reveals that the explicit index is gone. Its default behavior remains outside the source available to the updater.

In that case, the edit prediction changes the wording while preserving a reference to a specified position. The reranked generator offers a broader description of the complex value that avoids the unsupported detail, which the authors judge plausible in context. The reference revision is more informative because it specifies the first position. The example separates a successful editing mechanism from adequate evidence for the edit. A decoder can locate a portion of the old comment, write a grammatical change and still fail to capture the new behavior.

The authors also observe more failures when the new method differs substantially from the old one. In many of the cases they inspected, the reranked generator produced the better description. The old wording can provide a strong starting point for a localized revision, while a broad code change weakens the assumption that much of that wording remains useful. This observation suggests why the aggregate advantage of editing can coexist with cases where whole-comment generation is preferable. The paper offers a qualitative account and proposes estimating the required extent of editing as a way to choose how much to preserve.

Limitations

Limits identified by the authors

The authors scope the reported experiments to Java Javadoc @return comments. Their feature design, filtering and rule baselines all take advantage of that choice. A return description has a recognizable topic and can frequently be related to a particular statement or declared type. Comments about how to use a method, its preconditions, or another aspect of behavior may depend on different evidence. The experiments establish the performance of the approach on the selected return-comment task. Extensions to those other kinds of documentation remain open.

The authors also identify missing source context as a cause of errors. A method can pass through the result of another call whose behavior is defined elsewhere. The updater can observe a change in that call while lacking the information needed to explain its consequences. The getComplex example has exactly this structure. The newly omitted argument is visible, but the default selection rule lives outside the method. A richer code representation or an expanded context could supply different evidence. The paper leaves the use of changes to abstract syntax trees, as well as tree- and graph-based encoders, for future investigation.

The extraction rules trade coverage for cleaner examples. Using stable method names helps match method versions, and the authors recognize that this excludes revisions where the method name changes with the code and comment. Requiring a return statement or return type change makes it more likely that the source difference is relevant to the target documentation. Some relevant behavioral changes can occur elsewhere, and some changes that meet the rule still leave the meaning of the old comment intact. The paper proposes learned filtering as a future way to handle the relationships needed for a clean example.

The authors see a related issue when people use the suggestions. A developer may change the implementation while the old comment remains an adequate description. The dataset contains some of those cases despite the filtering, and the None responses expose them in the study. The authors propose deciding whether an update is needed before offering wording. A different proposal addresses large changes, which may make the old comment a poor starting point. The authors suggest combining editing with generation using an estimate of how extensive the revision should be. These proposals follow from the observed failure cases.

Limits that follow from the experimental design

A historical revision gives the task a reference, and it also gives it a particular view of what counts as an update. The sampled examples contain concurrent changes to source and comment. This is a way to obtain examples of how developers actually wrote revisions, but the timing of the changes is only evidence of a relationship. It can miss cases where a code change made a comment stale and the maintainer never corrected it. It can also include edits in which the developer made a discretionary clarification while touching code that the previous comment already described adequately. A test conditioned on co-edits therefore differs from a test across all code changes a tool would encounter.

A single recorded revision also makes exact match a narrow measure of success. The reference captures an observed choice of wording. Another comment can express the same guarantee while differing in word order or detail. The overlap metrics provide other views of the output, and the human judgments give readers room to endorse equivalent options. Neither part of the design establishes all the meanings permitted by the source. The return description still has to be understood in context, particularly where source details are only recoverable from other methods.

The human study evaluates suggestions under specific presentation rules. Participants see a code diff and the old comment, and they choose from a list with repeated outputs collapsed and unchanged outputs removed. That design gives the systems a shared setting and respects the fact that a developer can reject the list. It measures selection under those conditions. A deployment study would need other observations to establish how much review time is saved, how frequently suggestions are accepted in ongoing work, or how reliably the system recognizes when to stay silent. The None option combines rejection of low-quality wording with the decision that no revision is warranted, which limits comparisons about that latter decision alone.

The comparison with full-comment generation also has a specific scope. More training pairs are available for the generator, and it has fewer inputs when producing candidates. Reranking gives it access to the old comment only after generation. The representation experiments are closer controls because they preserve the old-comment input and vary the kind of target or code representation. Together these experiments establish benefits for the tested architectures, representations and corpus. Comparisons with other ways of giving a full-comment generator access to project context, or with a system that verifies the meaning of its output against code behavior, remain open.

Finally, anchor uniqueness solves a placement problem, while the accuracy of a proposed change depends on the evidence behind it. A unique old span allows the parser to find the intended site for a well-formed action. The reranker can favor a plausible description and reward similarity to the old one. Those properties concern the form and selection of a suggestion. The study assesses semantic suitability through readers and through examples of errors, with the information available in the immediate method shaping what the updater can infer. When the code omits the decisive fact, a well-located edit can still require developer judgment.

What came after

No later study is documented here as extending or evaluating the approach.

Cite

Cite as Sheena Panthaplackel, Pengyu Nie, Milos Gligoric, Junyi Jessy Li and Raymond Mooney. 2020. Learning to Update Natural Language Comments Based on Code Changes. Proceedings of the 58th Annual Meeting of the Association for Computational Linguistics.

The paper itself, not this page. BibTeX from the library's record of the work. DOI 10.18653/v1/2020.acl-main.168 · arXiv 2004.12169

@inproceedings{panthaplackel2020learning,
  title = {{Learning to Update Natural Language Comments Based on Code Changes}},
  author = {Sheena Panthaplackel, Pengyu Nie, Milos Gligoric, Junyi Jessy Li and Raymond Mooney},
  booktitle = {Proceedings of the 58th Annual Meeting of the Association for Computational Linguistics},
  year = {2020},
  doi = {10.18653/v1/2020.acl-main.168},
  eprint = {2004.12169},
  archivePrefix = {arXiv},
  url = {https://doi.org/10.18653/v1/2020.acl-main.168}
}

↑ back to top

This page in Markdown https://md.research.elamur.ai/free/en/papers/panthaplackel-2020-learning-update-natural-language-comments/

References

43 references, from the paper's own bibliography.

  1. Miltiadis Allamanis. 2019. The adverse effects of code duplication in machine learning models of code. In SPLASH, Onward!, pages 143–153. our card
  2. Miltiadis Allamanis, Hao Peng, and Charles Sutton. 2016. A convolutional attention network for extreme summarization of source code. In International Conference on Machine Learning, pages 2091–2100. our card
  3. Uri Alon, Shaked Brody, Omer Levy, and Eran Yahav. 2019. code2seq: Generating sequences from structured representations of code. In International Conference on Learning Representations. our card
  4. Fernando Alva-Manchego, Louis Martin, Carolina Scarton, and Lucia Specia. 2019. EASSE: Easier automatic sentence simplification evaluation. In Conference on Empirical Methods in Natural Language Processing and International Joint Conference on Natural Language Processing: System Demonstrations, pages 49–54. our card
  5. Abhijeet Awasthi, Sunita Sarawagi, Rasna Goyal, Sabyasachi Ghosh, and Vihari Piratla. 2019. Parallel iterative edit models for local sequence transduction. In Conference on Empirical Methods in Natural Language Processing and International Joint Conference on Natural Language Processing, pages 4251–4261. our card
  6. Satanjeev Banerjee and Alon Lavie. 2005. Meteor: An automatic metric for MT evaluation with improved correlation with human judgments. In Workshop on Intrinsic and Extrinsic Evaluation Measures for Machine Translation and/or Summarization, pages 65–72. our card
  7. Taylor Berg-Kirkpatrick, David Burkett, and Dan Klein. 2012. An empirical investigation of statistical significance in NLP. In Joint Conference on Empirical Methods in Natural Language Processing and Computational Natural Language Learning, pages 995–1005. OpenAlex ↗ · Scholar ↗
  8. Kyunghyun Cho, Bart van Merriënboer, Caglar Gulcehre, Dzmitry Bahdanau, Fethi Bougares, Holger Schwenk, and Yoshua Bengio. 2014. Learning phrase representations using RNN encoder–decoder for statistical machine translation. In Conference on Empirical Methods in Natural Language Processing, pages 1724–1734. our card
  9. Yue Dong, Zichao Li, Mehdi Rezagholizadeh, and Jackie Chi Kit Cheung. 2019. EditNTS: An neural programmer-interpreter model for sentence simplification through explicit editing. In Annual Meeting of the Association for Computational Linguistics, pages 3393–3402. our card
  10. Patrick Fernandes, Miltiadis Allamanis, and Marc Brockschmidt. 2019. Structured neural summarization. In International Conference on Learning Representations. OpenAlex ↗ · Scholar ↗
  11. Kelvin Guu, Tatsunori B Hashimoto, Yonatan Oren, and Percy Liang. 2018. Generating sentences by editing prototypes. Transactions of the Association for Computational Linguistics, 6:437–450. our card
  12. Xing Hu, Ge Li, Xin Xia, David Lo, and Zhi Jin. 2018. Deep code comment generation. In International Conference on Program Comprehension, pages 200–210. OpenAlex ↗ · Scholar ↗
  13. Srinivasan Iyer, Ioannis Konstas, Alvin Cheung, and Luke Zettlemoyer. 2016. Summarizing source code using a neural attention model. In Annual Meeting of the Association for Computational Linguistics, pages 2073–2083. OpenAlex ↗ · Scholar ↗
  14. Siyuan Jiang, Ameer Armaly, and Collin McMillan. 2017. Automatically generating commit messages from diffs using neural machine translation. In International Conference on Automated Software Engineering, pages 135–146. OpenAlex ↗ · Scholar ↗
  15. Wei-Jen Ko, Greg Durrett, and Junyi Jessy Li. 2019. Linguistically-informed specificity and semantic plausibility for dialogue generation. In North American Chapter of the Association for Computational Linguistics: Human Language Technologies, pages 3456–3466. OpenAlex ↗ · Scholar ↗
  16. Klaus Krippendorff. 2011. Computing Krippendorff's alpha reliability. Technical report, University of Pennsylvania. OpenAlex ↗ · Scholar ↗
  17. Reno Kriz, João Sedoc, Marianna Apidianaki, Carolina Zheng, Gaurav Kumar, Eleni Miltsakaki, and Chris Callison-Burch. 2019. Complexity-weighted loss and diverse reranking for sentence simplification. In North American Chapter of the Association for Computational Linguistics: Human Language Technologies, pages 3137–3147. OpenAlex ↗ · Scholar ↗
  18. Seonah Lee, Rongxin Wu, S.C. Cheung, and Sungwon Kang. 2019. Automatic detection and update suggestion for outdated API names in documentation. Transactions on Software Engineering. OpenAlex ↗ · Scholar ↗
  19. Juncen Li, Robin Jia, He He, and Percy Liang. 2018. Delete, retrieve, generate: a simple approach to sentiment and style transfer. In North American Chapter of the Association for Computational Linguistics: Human Language Technologies, pages 1865–1874. our card
  20. Junyi Jessy Li and Ani Nenkova. 2015. Fast and accurate prediction of sentence specificity. In AAAI Conference on Artificial Intelligence, pages 2281–2287. OpenAlex ↗ · Scholar ↗
  21. Yuding Liang and Kenny Q. Zhu. 2018. Automatic generation of text descriptive comments for code blocks. In AAAI Conference on Artificial Intelligence, pages 5229–5236. OpenAlex ↗ · Scholar ↗
  22. Chia-Wei Liu, Ryan Lowe, Iulian Serban, Mike Noseworthy, Laurent Charlin, and Joelle Pineau. 2016. How NOT to evaluate your dialogue system: An empirical study of unsupervised evaluation metrics for dialogue response generation. In Conference on Empirical Methods in Natural Language Processing, pages 2122–2132. our card
  23. Pablo Loyola, Edison Marrese-Taylor, and Yutaka Matsuo. 2017. A neural architecture for generating natural language descriptions from source code changes. In Annual Meeting of the Association for Computational Linguistics, pages 287–292. OpenAlex ↗ · Scholar ↗
  24. Thang Luong, Hieu Pham, and Christopher D. Manning. 2015. Effective approaches to attention-based neural machine translation. In Conference on Empirical Methods in Natural Language Processing, pages 1412–1421. our card
  25. Dana Movshovitz-Attias and William W. Cohen. 2013. Natural language models for predicting programming comments. In Annual Meeting of the Association for Computational Linguistics, pages 35–40. OpenAlex ↗ · Scholar ↗
  26. Courtney Napoles, Keisuke Sakaguchi, Matt Post, and Joel Tetreault. 2015. Ground truth for grammatical error correction metrics. In Annual Meeting of the Association for Computational Linguistics and the International Joint Conference on Natural Language Processing, pages 588–593. OpenAlex ↗ · Scholar ↗
  27. Graham Neubig, Makoto Morishita, and Satoshi Nakamura. 2015. Neural reranking improves subjective quality of machine translation: NAIST at WAT2015. In Workshop on Asian Translation, pages 35–41. OpenAlex ↗ · Scholar ↗
  28. Sheena Panthaplackel, Milos Gligoric, Raymond J. Mooney, and Junyi Jessy Li. 2020. Associating natural language comment and source code entities. In AAAI Conference on Artificial Intelligence. OpenAlex ↗ · Scholar ↗
  29. Kishore Papineni, Salim Roukos, Todd Ward, and Wei-Jing Zhu. 2002. BLEU: a method for automatic evaluation of machine translation. In Annual Meeting of the Association for Computational Linguistics, pages 311–318. our card
  30. Rebecca Passonneau. 2006. Measuring agreement on set-valued items (MASI) for semantic and pragmatic annotation. In International Conference on Language Resources and Evaluation. our card
  31. Inderjot Kaur Ratol and Martin P. Robillard. 2017. Detecting fragile comments. International Conference on Automated Software Engineering, pages 112–122. OpenAlex ↗ · Scholar ↗
  32. Darsh J. Shah, Tal Schuster, and Regina Barzilay. 2020. Automatic fact-guided sentence modification. In AAAI Conference on Artificial Intelligence. OpenAlex ↗ · Scholar ↗
  33. Richard Shin, Illia Polosukhin, and Dawn Song. 2018. Towards specification-directed program repair. In International Conference on Learning Representations Workshop. OpenAlex ↗ · Scholar ↗
  34. Akhilesh Sudhakar, Bhargav Upadhyay, and Arjun Maheswaran. 2019. “Transforming” delete, retrieve, generate approach for controlled text style transfer. In Conference on Empirical Methods in Natural Language Processing and the International Joint Conference on Natural Language Processing, pages 3267–3277. our card
  35. Lin Tan, Ding Yuan, Gopal Krishna, and Yuanyuan Zhou. 2007. /*iComment: Bugs or bad comments?*/. In Symposium on Operating Systems Principles, pages 145–158. OpenAlex ↗ · Scholar ↗
  36. Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N Gomez, Łukasz Kaiser, and Illia Polosukhin. 2017. Attention is all you need. In Advances in Neural Information Processing Systems, pages 5998–6008. our card
  37. Oriol Vinyals, Meire Fortunato, and Navdeep Jaitly. 2015. Pointer networks. In Advances in Neural Information Processing Systems, pages 2692–2700. OpenAlex ↗ · Scholar ↗
  38. Shengbin Xu, Yuan Yao, Feng Xu, Tianxiao Gu, Hanghang Tong, and Jian Lu. 2019. Commit message generation for source code changes. In International Joint Conference on Artificial Intelligence, pages 3975–3981. OpenAlex ↗ · Scholar ↗
  39. Wei Xu, Courtney Napoles, Ellie Pavlick, Quanze Chen, and Chris Callison-Burch. 2016. Optimizing statistical machine translation for text simplification. Transactions of the Association for Computational Linguistics, 4:401–415. our card
  40. Ziyu Yao, Daniel S. Weld, Wei-Peng Chen, and Huan Sun. 2018. StaQC: A systematically mined question-code dataset from Stack Overflow. In International Conference on World Wide Web, pages 1693–1703. OpenAlex ↗ · Scholar ↗
  41. Pengcheng Yin, Bowen Deng, Edgar Chen, Bogdan Vasilescu, and Graham Neubig. 2018. Learning to mine aligned code and natural language pairs from Stack Overflow. In International Conference on Mining Software Repositories, pages 476–486. our card
  42. Pengcheng Yin, Graham Neubig, Miltiadis Allamanis, Marc Brockschmidt, and Alexander L. Gaunt. 2019. Learning to represent edits. In International Conference on Learning Representations. OpenAlex ↗ · Scholar ↗
  43. Juan Zhai, Xiangzhe Xu, Yu Shi, Guanhong Tao, Minxue Pan, Shiqing Ma, Lei Xu, Weifeng Zhang, Lin Tan, and Xiangyu Zhang. 2020. CPC: Automatically classifying and propagating natural language comments via program analysis. In International Conference on Software Engineering. OpenAlex ↗ · Scholar ↗