Learning to Update Natural Language Comments Based on Code Changes (2020)

Abstract: We formulate the novel task of automatically updating an existing natural language comment based on changes in the body of code it accompanies. We propose an approach that learns to correlate changes across two distinct language representations, to generate a sequence of edits that are applied to the existing comment to reflect the source code modifications. We train and evaluate our model using a dataset that we collected from commit histories of open-source software projects, with each example consisting of a concurrent update to a method and its corresponding comment. We compare our approach against multiple baselines using both automatic metrics and human evaluation. Results reflect the challenge of this task and that our model outperforms baselines with respect to making edits.

## introduction software developers include natural language comments alongside source code as a way to document various aspects of the code such as functionality, use cases, pre-conditions, and post-conditions. with the growing popularity of open-source software that is widely used and jointly developed, the need for efficient communication among developers about code details has increased. consequently, comments have assumed a vital role in the development cycle. with developers regularly refactoring and iteratively incorporating new functionality, source code is constantly evolving; however, the accompanying comments are not always updated to reflect the code changes @xcite . inconsistency between code and comments can not only lead time-wasting confusion in tight project schedules @xcite but can also result in bugs @xcite . to address this problem, we propose an approach that can automatically suggest comment updates when the associated methods are changed. prior work explored rule-based approaches for detecting inconsistencies for a limited set of cases; however, they do not present ways to automatically fix these inconsistencies @xcite . recent work in automatic comment generation aims to generate a comment given a code representation @xcite @xcite ; although these techniques could be used to produce a completely new comment that corresponds to the most recent version of the code, this could potentially discard salient content from the existing comment that should be retained. to the best of our knowledge, we are the first to formulate the task of automatically updating an existing comment when the corresponding body of code is modified. this task is intended to align with how developers edit a comment when they introduce changes in the corresponding method. rather than deleting it and starting from scratch, they would likely only modify the specific parts relevant to the code updates. for example, figure 1 shows the getrotx method being modified to have the return value parsed into degrees. within the same commit, the corresponding comment is revised to indicate this, without imposing changes on parts of the comment that pertain to other aspects of the return value. we replicate this process through a novel approach which is designed to correlate edits across two distinct language representations: source code and natural language comments. namely, our model is trained to generate a sequence of edit actions, which are to be applied to the existing comment, by conditioning on learned representations of the code edits and existing comment. we additionally incorporate linguistic and lexical features to guide the model in determining where edits should be made in the existing comment. furthermore, we develop an output reranking scheme that aims to produce edited comments that are fluent, preserve content that should not be changed, and maintain stylistic properties of the existing comment. we train and evaluate our system on a corpus constructed from open-source java projects on github, by mining their commit histories and extracting examples from consecutive commits in which there was a change to both the code within a method as well as the corresponding javadoc comment, specifically, the @return javadoc tag. these comments, which have been previously studied for learning associations between comment and code entities @xcite , follow a well-defined structure and describe characteristics of the output of a method. for this reason, as an initial step, we focus on @return comments in this work. our evaluation consists of several automatic metrics that are used to evaluate language generation tasks as well as tasks that relate to editing natural language text. we also conduct human evaluation, and assess whether human judgments correlate with the automatic metrics. the main contributions of this work include (1) the task of automatically updating an existing comment based on source code changes and (2) a novel approach for learning to relate edits between source code and natural language that outperforms multiple baselines on several automatic metrics and human evaluation. our implementation and data are publicly available. 1 2 task given a method, its corresponding comment, and an updated version of the method, the task is to update the comment so that it is consistent with the code in the new method. for the example in figure 1 , we want to generate "@return double the roll euler angle in degrees." based on the changes between the two versions of the method and the existing comment "@return double the roll euler angle." concretely, given (m old , c old ) and m new , 1 https://github.com/panthap2/ learningtoupdatenlcomments where m old and m new denote the old and new versions of the method, and c old signifies the previous version of the comment, the task is to produce c new , the updated version of the comment. ## edit model overview we design a system that examines source code changes and how they relate to the existing comment in order to produce an updated comment that reflects the code modifications. since c old and c new are closely related, training a model to directly generate c new risks having it learn to just copy c old . to explicitly inform the model of edits, we define the target output as a sequence of edit actions, c edit , to indicate how the existing comment should be revised (e.g., for c @xmath0, c @xmath1. furthermore, in order to better correlate these edits with changes in the code, we unify m old and m new into a single diff sequence that explicitly identifies code edits, m edit . we discuss in more detail how m edit and the training c edit are constructed in §4. figure 2 shows a high-level overview of our system. we design an encoder-decoder architecture consisting of three components: a two-layer, bidirectional gru @xcite that encodes the code changes (m edit ), another two-layer, bidirectional gru that encodes the existing comment (c old ), and a gru that is trained to decode a sequence of edit actions (c edit ). 2 we concatenate the final states of the two encoders to form a vector that summarizes the content in m edit and c old , and use this vector as the initial state of the decoder. the decoder essentially has three subtasks: (1) identify edit locations in c old ; (2) determine parts of m edit that pertain to making these edits; and (3) apply updates in the given locations based on the relevant code changes. we rely on an attention mechanism @xcite over the hidden states of the two encoders to accomplish the first two goals. at every decoding step, rather than aligning the current decoder state with all the encoder hidden states jointly, we align it with the hidden states of the two encoders separately. we concatenate the two resulting context vectors to form a unified context vector that is used in the final step of computing attention, ensuring that we incorporate pertinent content from both input sequences. consequently, the resulting attention vector carries information relating to the current decoder state as well as knowledge aggregated from relevant portions of c old and m edit . using this information, the decoder performs the third subtask, which requires reasoning across language representations. specifically, it must determine how the source code changes that are relevant to the current decoding step should manifest as natural language updates to the relevant portions of c old . at each step, it decides whether it should begin a new edit action by generating an edit start keyword, continue the present action by generating a comment token, or terminate the present action by generating an end-edit keyword. because actions relating to deletions will include tokens in c old , and actions relating to insertions are likely to include tokens in m edit , we equip the decoder with a pointer network @xcite to accommodate copying tokens from c old and m edit . the decoder generates a sequence of edit actions, which will have to be parsed into a comment ( §4.4). ## representing edits here we define the edit lexicon that is used to construct the input code edit sequence, m edit , and the target comment edit sequence, c edit . ## features we extract linguistic and lexical features for tokens in m edit and c edit , many of which were shown to improve learning associations between @return comment and source code entities in our prior work @xcite . we incorporate these features into the network as one-hot vectors that are concatenated to m edit and c edit embeddings and then passed through a linear layer. these vectors are provided as inputs to the two encoders. all sequences are subtokenized, e.g., @xmath2, case. features specific to m edit : we aim to take advantage of common patterns among different types of code tokens by incorporating features that identify certain categories: edit keywords, java keywords, and operators. if a token is not an edit keyword, we have indicator features for whether it is part of a insert, delete, replacenew, replaceold, or keep span. we believe this will be particularly helpful for longer spans since edit keywords only appear at either the beginning or end of a span. finally, we include a feature to indicate whether the token matches a token in c old . this is intended to help the model identify locations in m edit that may be relevant to editing c old . features specific to c old : we include whether a token matches a code token that is inserted, deleted, or replaced in m edit . these help align parts of c old with code edits, assisting the model in determining where edits should be made. in order to exploit common patterns for different types of tokens, we incorporate features that identify whether the token appears more than once in c old or is a stop word, and its part-of-speech. ## reranking reranking allows the incorporation of additional priors that are difficult to back-propagate, by re-scoring candidate sequences during beam search @xcite @xcite . we incorporate two heuristics to rescore the candidates: 1) generation likelihood and 2) similarity to c old . these heuristics are computed after parsing the candidate edit sequences ( §4.4). generation likelihood. since the edit model is trained on edit actions only, it does not globally score the resulting comment in terms of aspects such as fluency and overall suitability for the updated method. to this end, we make use of a pretrained comment generation model ( §8.2) that is trained on a substantial amount of data for generating c new given only m new . we compute the length-normalized probability of this model generating the parsed candidate comment, c' new , (i.e., ## data we extracted examples from popular, open-source java projects using github's commit history. we extract pairs of the form (method, comment) for the same method across two consecutive commits where there is a simultaneous change to both the code and comment. this creates somewhat noisy data for the task of comment update; appendix b describes filtering techniques to reduce this noise. we first tokenize m old and m new using the javalang foot_4 library. we subtokenize based on camelcase and snake_case, as in previous work @xcite @xcite . we then form m edit from the subtokenized forms of m old and m new . we tokenize c old and c new by splitting by space and punctuation. we remove html tags and the "@return" that precedes all comments, and also subtokenize tokens since code tokens may appear in comments as well. the gold edit action sequence, c edit , is computed from these processed forms of c old and c new . to avoid having examples that closely resemble one another in training and test, the projects in the training, test, and validation sets are disjoint, similar to @xcite . ## experimental method we evaluate our approach against multiple rulebased baselines and comment generation models. ## error analysis we find that our model performs poorly in cases requiring external knowledge and more context than that provided by the given method. for instance, correctly updating the comment shown in figure 3 requires knowing that get returns the item in the first position if no argument is provided. our model does not have access to this information, and it fails to generate a reasonable update: "@return complex in given position." on the other hand, the reranked generation model produces "@return the complex value" which is arguably reasonable for the given context. this suggests that incorporating more code context could be beneficial for both models. furthermore, we find that our model tends to make more mistakes when it must reason about a large amount of code change between m old and m new , and we found that in many such cases, the output of the reranked generation model was better. this suggests that when there are substantial code changes, m new effectively becomes a new method, and generating a comment from scratch may be more appropriate. ensembling generation with our system through a regression model that predicts the extent of editing that is needed may lead to a more generalizable approach that can accommodate such cases. sample outputs are given in appendix c. ## ablations we empirically study the effect of training the network to encode explicit code edits and decode explicit comment edits. as discussed in section 3, the edit model consists of two encoders, one that encodes c old and another that encodes the code representation, m edit . we conduct experiments in which the code representation instead consists of either (1) m new or (2) both m old and m new (encoded separately and hidden states concatenated). additionally, rather than having the decoder generate comment edits in the form c edit , we introduce experiments in which it directly generates c new , with no intermediate edit sequence. for this, we use only the underlying architecture of the edit model (without features or reranking). the performance for various combinations of input code and target comment representations are shown in by comparing performance across combinations consisting of the same input code representation and varying target comment representations, the importance of training the decoder to generate a sequence of edit actions rather than the full updated comment is very evident. furthermore, comparing across varying code representations under the c edit target comment representation, it is clear that explicitly encoding the code changes, as m edit , leads to significant improvements across most metrics. we further ablate the features introduced in §5. as shown in ## conclusion we have addressed the novel task of automatically updating an existing programming comment based on changes to the related code. we designed a new approach for this task which aims to correlate cross-modal edits in order to generate a sequence of edit actions specifying how the comment should be updated. we find that our model outperforms multiple rule-based baselines and comment generation models, with respect to several automatic metrics and human evaluation.