Automated Correction for Syntax Errors in Programming Assignments using Recurrent Neural Networks
Paper · 2016 · Sahil Bhatia and Rishabh Singh
Summary
When Python flags a line in a student’s assignment, the message tells the student where the parser ran into trouble. It may take more work to find the mistake and decide what belongs there. A missing colon, an extra parenthesis, or an incorrectly indented statement can keep an otherwise promising attempt from running. In the authors’ data from the edX introductory programming course 6.00x, 34.78% of the submissions contained syntax errors. This was a gap in automated feedback. Systems such as AutoProf and Codewebs relied on the structured representation produced by parsing, and they could not start their usual analysis when the parser failed to produce that representation.
The authors’ alternative, SynFix, learns from other attempts at the same assignment. For each exercise, they train a recurrent neural network on submissions that Python can parse. A solution can be useful for training even if it returns the wrong answer. The network encounters the programs as sequences of tokens, the units of source code such as keywords, operators, and identifiers. Its task is to predict which token ordinarily comes next. The premise is that students working on the same problem use enough similar expressions and solution strategies for those predictions to suggest repairs.
When a new submission fails to parse, SynFix takes the tokens from the beginning of the function to a boundary near the reported error. The network predicts a continuation, and SynFix tries short portions of it as insertions or replacements. This can add a missing : or change = to == in a condition. The system also considers moving the boundary back by a token. If local edits fail, it can end the prefix at the previous line and generate a replacement for the entire suspect line. The parser checks the edited submission, so a likely continuation becomes a repair only when it meets the relevant syntax criterion.
Across the 14,203 submissions with syntax errors from the course’s five exercises, SynFix completely repaired 4501 (31.69%). It resolved the first error in a further 908 submissions (6.39%), where another error still prevented the program from parsing. Results varied considerably by assignment. The method produced repairs on exercises with only hundreds of parseable training attempts, while oddTuples had a large training collection and the lowest complete-repair rate. The authors’ inspection of that exercise found frequent indentation problems and approaches to the task that were missing from the training examples.
A complete repair in this experiment means that Python accepts the edited source. The suggestion may still change the meaning of the program or leave it liable to fail when run. The network uses preceding code to generate proposals, which can lead it to miss clues after the error. The procedure also targets one error per pass. The authors propose using surrounding code, checking behavior as well as syntax, and repeating the repair process. They leave open how to turn the resulting edits into instruction, especially when a student’s error reflects a misunderstanding of the language.
Deep dive: Automated Correction for Syntax Errors in Programming Assignments using Recurrent Neural Networks
SynFix learns from student Python submissions to suggest repairs for syntax errors and uses the parser to check whether a proposed edit works. · about 34 minutes to read
The problem and its context
The gap between an error message and a repair
A programming assignment can go wrong before its algorithm has a chance to run. Python first needs to recognize how the source is organized. It must identify expressions, statements, and blocks and determine which pieces belong together. A failure at this stage can be small in the source and decisive for everything that follows. An incorrectly written condition, for example, stops execution before any test can reveal whether the condition expresses the right idea.
The compiler can locate a point at which the input stops making sense and describe the difficulty. The authors emphasize how much hinges on the difference between that point and the location of the underlying mistake. By the time a parser rejects a token, it may have passed over the token that caused the problem. In the paper’s misspelled return example, the parser points to the following expression. A location is therefore an anchor for an investigation. The student still needs to work out which part of the surrounding source to change.
The authors were concerned with feedback at the scale of a massive open online course. An instructor or teaching assistant can often recognize what a beginner was trying to write, drawing on familiarity with the exercise and with other students’ attempts. Arranging that kind of individual review for a large course is expensive. As the paper describes it, peer grading spreads that work among students, who review submissions using a rubric. The potential drawbacks are delay and uneven accuracy. Someone learning the same material may have difficulty diagnosing the cause of an error, even with guidance about what to look for.
The course corpus gives the authors another way to use the work students have already done. A completed exercise does not have to be the instructor’s solution to give evidence about how a line is written. Examples gathered from many attempts reflect the choices students make while working under a common problem specification. The same operation, function call, or base-case pattern can recur in otherwise distinct programs. SynFix tries to make that recurring information available when a student’s own source is incomplete or malformed.
Why earlier feedback systems started elsewhere
An abstract syntax tree, or AST, represents the grammatical structure of source code. A condition and the statements it governs can be represented as related parts of a tree, even when they are on different lines. That organization is useful for comparing programs, reasoning about behavior, and searching for a fragment described by its role. It also defines a prerequisite. The approaches discussed by the authors expect a program for which the parser can supply an AST.
AutoProf, for instance, takes a teacher’s reference implementation and a set of rules for common errors. It uses constraints to search for a small change that makes a student’s program behave like the reference. The authors discuss it as a way to repair functional mistakes in code that can already be analyzed. Its objective is stronger than parser acceptance. Its reliance on program structure places syntax failures earlier in the process than the stage where AutoProf operates.
Codewebs approaches feedback as search. It indexes structured fragments from student solutions so that an instructor’s comments on a small set of submissions can be propagated to others with related code. The search can address a subtree, several subtrees, or a surrounding structural context. This use of a submission corpus anticipates one part of SynFix’s motivation. The representation differs in a consequential way. Codewebs needs tree structure to tell which submissions contain a comparable fragment. SynFix needs a token prefix that can be extracted even when the full program fails the parser.
The related work also includes feedback on performance based on values observed during program execution and clustering of submissions using the edit distance between their syntax trees. In the former, observations from tests help identify the student’s high-level strategy. In the latter, the tree gives the system a common basis for comparison. The paper describes another approach that learns representations from program preconditions and postconditions to propagate instructor feedback. In each case, the information that makes the analysis valuable becomes available once the submitted program can undergo the necessary structural or execution analysis.
The authors mention similar efforts to scale feedback in mathematics and short-answer grading. In those studies, a collection of responses helps find groups to which a grade or comment can be applied. The parallel is the reuse of work across many learners. In SynFix, an individual repair is constructed from a continuation of the student’s source. The system does not need to place the whole submission in a category and retrieve a comment already written for that category.
Learning how source code tends to continue
The paper draws its other line of inspiration from statistical studies of large source-code collections. Hindle and colleagues used an n-gram predictor, which estimates the next token from short recurring token sequences. As the authors describe that work, repetition in software gave even a predictor without type or parse information enough evidence to make useful suggestions for Java code completion. The immediate precedent for SynFix was the ability to predict plausible code from local context.
The paper distinguishes several ways earlier work enriched that idea. Nguyen and colleagues incorporated information about the roles and types of tokens, the relationships between them, and broader tendencies within a source file. Naturalize learned coding conventions from a project and used them to suggest names and formatting. It drew on the syntax tree when constructing the context for an identifier suggestion. The authors also cite work using large repositories to study source-code patterns, including Mining Idioms from Source Code.
Other systems described in the paper predict method or class names from their contents, or infer identifier names and type annotations from relationships in an input program. These examples help explain the attraction of prediction for syntax repair. There can be enough regularity in existing code to make a specific suggestion about an unfamiliar fragment. Some forms of evidence those systems use, such as a dependency representation of the input, are harder to obtain when source code fails to parse. SynFix restricts its input to a simpler representation so it can work at that stage.
The authors narrow the training corpus in a different way from repository-wide prediction. They treat the exercise as part of the problem definition. A student writing recursive exponentiation has a reason to produce expressions that a student extracting elements of a tuple would rarely use. Even tasks with the same expected result can elicit different continuations if one requires a recursive approach and the other an iterative approach. By training separately for each assignment, the authors aim to make the suggestions sensitive to those differences.
That choice depends on an empirical premise about the class. A large enrollment can generate many versions of the same general strategy, giving the predictor repeated exposure to related contexts. If the training submissions instead omit an approach used by a student with a syntax error, the assignment label alone supplies little help. The paper’s experiment tests the task-specific premise through actual repair outcomes, where learned regularities must lead to edits that Python can accept.
The method, step by step
What the system learns from a submission
SynFix has a training phase and a repair phase. During training, the parser determines which programs can serve as examples. During repair, it reports an error location and checks what happens when SynFix changes the source. The recurrent network has a separate role. It supplies guesses about the next few tokens based on the observed ones. The system combines those responsibilities so that the component drawing on student submissions proposes edits and the component implementing Python’s syntax evaluates the resulting code.
From assignment submissions to a syntax repair
The steps in order.
A training example begins as a submission that Python can parse. The authors accept it on that basis, even when the exercise’s functional requirements are unmet. An incorrect algorithm can still provide examples of statements with colons in the right places, calls with properly formed arguments, and expressions with appropriately placed operators. The training corpus supplies examples of how code is written around such positions.
Tokenization turns the source into ordered units. A name such as exp, an operator such as ==, and punctuation such as : can each be represented by a token. Layout is also relevant. Newlines provide boundaries for the line replacement procedure, and indentation can itself be the material supplied by an edit. The token stream preserves material the network can use for both small expressions and the layout of a statement within a block.
The vocabulary is the set of distinct tokens used to encode these sequences. Source code lets students invent names, so a vocabulary can contain many entries seen in very few attempts. During preprocessing, the authors use a frequency cutoff and relabel tokens below it as IDENT. Infrequent variable and method names are their examples. A token seen frequently enough keeps its individual vocabulary entry. The threshold used for the main experiments was 4. This preprocessing gives the network a common representation for contexts that differ only in rare tokens.
Each input token is represented as a one-hot vector, a list of values as long as the training vocabulary. Its own entry is 1 and all other entries are 0. When the network multiplies such a vector by its input weights, the active entry selects the weights associated with that token. The paper describes learned embedding lookup as another way to represent input words in sequence tasks, while specifying one-hot input for this system.
Every training sequence supplies its own next-token targets. The same sequence is shifted left by 1 to obtain the expected output, so that the token at a position in the input is paired with the token that follows it in the source. The input at each step during training is drawn from the program. For example, when the training sequence reaches the end of a conventional condition, the target may be :. Across contexts, the network learns which vocabulary items tend to follow the current token and the earlier sequence.
The objective is cross-entropy between the observed target and the network’s predicted distribution. In this setup, with one observed next token, minimizing the loss amounts to minimizing the negative log likelihood of that token. A prediction earns a smaller penalty when it gives the observed token more probability. The training criterion does not require a program with a known mistake and a labeled repair. Its supervision is simply the ordering already present in the parseable submissions.
How the network carries earlier information forward
The paper explains recurrence through a network with a single hidden layer. A hidden layer is a collection of internal values that the network computes on the way from input to output. At any step, those values constitute a hidden state. The state is updated with both the current input and the state from the preceding step. As a result, seeing the same input token after different pieces of code can produce different states and different predictions.
sₜ = f(W × xₜ + V × sₜ₋₁)
Here t is the current position in an input sequence of length L. The subscript t−1 refers to the preceding position. The vector xₜ represents the current token and has I input entries. The vectors sₜ and sₜ₋₁ hold the current and previous hidden states, each with H entries for the H hidden units. The matrix W holds the weights from the input to the hidden layer, with H rows and I columns. The matrix V holds the weights from the previous hidden state to the new one, with H rows and H columns. The sign × denotes matrix-vector multiplication, and + adds the resulting vectors. The function f applies a nonlinear activation to the combined values. The paper names hyperbolic tangent and sigmoid as examples. The equality defines the new state.
oₜ = softmax(U × sₜ)
The vector oₜ gives the output probabilities at position t. The matrix U holds the weights from the hidden state sₜ to the output units, and × again denotes matrix-vector multiplication. The function softmax turns the resulting scores into probabilities that sum to one. Each output unit corresponds to a possible next token. The operation needs an output row of U for each such unit and a column for each hidden unit. The paper gives U an input-sized row count in its general description while separately allowing the number of output units to differ from the input size. In the token prediction task, the input and output vocabularies are the same. The equality defines the output vector after normalization.
The paper also writes the weighted sums for individual units. The following notation uses matrix entries consistent with the direction of multiplication in the two vector equations.
aₕ,ₜ = ∑ᵢ₌₁ᴵ Wₕ,ᵢ × xᵢ,ₜ + ∑ₕ′₌₁ᴴ Vₕ,ₕ′ × sₕ′,ₜ₋₁
The value aₕ,ₜ is the score for hidden unit h at position t before applying f. The first ∑ adds the contributions of input entries indexed by i, from 1 through I. The weight Wₕ,ᵢ joins input entry i to hidden unit h, and xᵢ,ₜ is that input entry at position t. The second ∑ adds the contributions of previous hidden entries indexed by h′, from 1 through H. The weight Vₕ,ₕ′ joins the previous hidden unit h′ to the current hidden unit h, and sₕ′,ₜ₋₁ is that previous value. The sign × multiplies each value by its weight, + combines the two sums, and the equality gives the resulting score.
aₖ,ₜ = ∑ₕ₌₁ᴴ Uₖ,ₕ × f(aₕ,ₜ)
The value aₖ,ₜ is the score for output unit k at position t before softmax. Here k indexes an output unit. The ∑ adds the contributions of hidden units h from 1 through H. The element Uₖ,ₕ gives the weight from hidden unit h to output unit k. The expression f(aₕ,ₜ) is the activation of hidden unit h after applying the nonlinear function f to its score aₕ,ₜ. The sign × denotes scalar multiplication, and the equality defines the output score that participates in normalization.
The same weights are used at every sequence position. Back-propagation through time is how the authors train those shared weights. The recurrent computation can be viewed as a succession of steps, with each hidden state passed to the next. A weight that changes an early state can affect predictions at later positions as well as the immediate output. The gradient calculation follows those dependencies backward through the succession of states. It thus accounts for both the direct effect of the weights at a step and their effect through the states that follow.
The authors also try long short-term memory networks, or LSTMs. These are recurrent networks with units that regulate how information is stored, retained, and exposed to subsequent processing. The reason to test them is that an ordinary recurrent network can, in principle, carry earlier context forward, yet can have difficulty learning to connect positions that are far apart. LSTMs were designed to help with that difficulty. The paper tests the two kinds of network through the same repair task. The equations above explain the simple recurrent calculation, and the experiment varies which recurrent architecture supplies the token predictions.
How training becomes a continuation
At repair time, the network reads the available prefix and produces output probabilities at its end. It then uses a predicted token as the next input to continue the sequence. The following prediction therefore depends on the original prefix and on the choice the network just made. Training exposes it to observed continuations from student source. During generation it processes its own proposed continuation after the prefix runs out.
This distinction matters even if the actual edit is short. Suppose the predicted continuation begins with a comparison operator, then gives a value, then a colon. The comparison operator can be useful by itself. Later tokens are guesses conditioned on that operator, and the original line may already contain the right value and colon. SynFix separates the continuation it generated from the portion it ultimately uses. The parser evaluates the splice into the submission each time.
In the algorithm, P denotes the program and M denotes the trained sequence predictor. Tokenizing P yields T, the sequence of its tokens. The parser reports an error type and loc, the location used to form a prefix and identify where to try the local edit. The paper considers Python syntax and indentation errors. Its pseudocode uses a fixed prediction length called k, a different use of that letter from the output-unit index in the equations. The search considers progressively longer initial portions of the predicted continuation, up to that prediction length. The paper’s slice notation takes the start index as inclusive and the end index as exclusive. Its accompanying explanation describes the search in terms of candidate token counts.
The prefix begins at the start of the submitted function or program represented in the token stream. The reported location gives a natural boundary because code earlier in the sequence can help explain what ought to come next. The experiments also use Offset-1, which moves the prefix boundary one token earlier than the reported error token. This can help when the token immediately preceding the reported point has already pushed the prefix away from a plausible program continuation. The compact pseudocode shows the main offset and the previous-line fallback. The examples and the evaluation additionally describe the earlier boundary.
Testing an insertion and a replacement
SynFix tries a short insertion, checks the resulting program, and then tries a replacement of that length if the insertion fails. An insertion preserves the existing tokens at the edit site and pushes them after the new material. A replacement uses the prediction in place of original tokens at that site. The algorithm repeats those choices at increasing lengths. In the pseudocode, the first candidate for which parsing returns no error is accepted, and the program and the tokens used in the edit are returned.
The paper’s conditional example shows why both transformations matter. The student writes if exp = 0: in the recursive exponentiation exercise. In the example, the prefix ends after exp. The illustrative prediction length is 3, and the proposed continuation contains ==, 0, and : in that order. SynFix first tries the operator alone. An insertion gives if exp == = 0:, which Python still rejects. Replacing the original = with == gives if exp == 0:, which passes the syntax check in this example. The rest of the predicted continuation can be dropped because the source already supplies it.
Insertions fit other examples in the paper. If a closing parenthesis is absent, the right prediction can supply it without changing the expression inside the parentheses. A colon can complete a conditional header. A continuation can also finish part of an expression, as when exp- becomes exp-1. A replacement handles the different case where the original tokens occupy the right general location but include material that has to go. The paper mentions mismatched extra parentheses among the errors that replacement can address.
Indentation follows the same basic search. Because the proposed sequence can contain an indentation token, SynFix can try that token where the parser reports a problem. One example in the paper inserts a tab before return. The repaired line then allows the parser to reach a later indentation problem. That illustrates why returning a fully parseable program and making local progress are separate evaluation outcomes.
Trying short edits first reflects a preference about feedback. The authors want to preserve as much of the original program as they can while clearing the syntax error. The procedure expresses that preference through candidate order. It tests the beginning of the predicted sequence at selected boundaries. A successful edit is therefore small relative to the candidates tried before it. The algorithm has no search over every possible edit of the same length and makes no claim of finding a globally minimal repair.
Replacing the line when the location is misleading
If local edits fail, SynFix ends the prefix at the last token of the preceding line. Everything on the reported line is withheld from the prediction. The network then continues from that earlier context, and the algorithm takes the generated portion through a newline as a candidate replacement for the reported line. It puts that candidate into the original program and parses the result. If this final attempt fails the full check, the pseudocode returns the empty result, denoted by φ.
The paper illustrates the procedure with the malformed statement retrun exp. Python points to exp, while the mistyped keyword comes earlier. Starting prediction from a prefix that already includes retrun keeps the typo among the tokens that shape the continuation. The examples of insertion and replacement considered at the reported point fail to solve the problem. With the whole line omitted, the network proposes return base, and the resulting program passes the syntax check in the example.
That repair reveals the difference between generating a line and correcting a word. The generated line supplies a correctly written keyword and changes the expression returned by the function. The parser can judge the new statement’s place in the surrounding block and its grammatical form. The acceptance decision supplies no evidence that base was the expression the student intended. Moving the boundary back gives the network a cleaner prefix at the cost of discarding potentially useful evidence about what the student was trying to say.
The following code still participates in the final parse check. A suggested line must fit the program as a whole for SynFix to return a complete repair. The following code does not guide the recurrent network while it selects the continuation. This division explains how SynFix can use the whole program to rule out some edits while overlooking an obvious clue about which legal edit would make the most sense.
Experiments and results
The assignments and the data split
The evaluation uses Python submissions from the edX Introduction to Programming course, identified in the paper as 6.00x. The total is 40,835 attempts. The data split is defined by parser outcome within each assignment. The 26,632 attempts that parse supply the training sequences. The 14,203 with syntax errors supply the repair test cases. Thus the training and test partitions serve different roles. The researchers learn how tokens are used in parseable attempts and then measure whether that information can repair the source of an unparseable attempt.
Two exercises share a functional goal. recurPower asks students to raise a base to an integer exponent using recursion, where the function calls itself on a smaller instance of the problem. Its 10,247 attempts include 8176 that parse and 2071 that fail the syntax check. iterPower asks for an iterative solution to the same calculation. Its 11,855 attempts include 9194 parseable examples and 2661 syntax-error cases. The reported shares of attempts with syntax errors are 20.21% for recurPower and 22.45% for iterPower. The two training corpora are kept separate in spite of the common calculation.
oddTuples asks for a new tuple containing every other element of an input tuple. It has 17,057 attempts, of which 8233 are parseable and 8824 have syntax errors. The syntax-error share is 51.73%. The remaining two exercises concern polynomials. evalPoly asks students to evaluate a polynomial at a point using a list of coefficients. It has 1148 attempts, with 824 parseable and 324 failing, for a syntax-error share of 28.22%. compDeriv asks for the coefficient representation of the derivative of a polynomial. Of its 528 attempts, 205 parse and 323 fail, giving a syntax-error share of 61.18%.
The authors collected the data while submissions for the polynomial exercises were still open. Those exercises consequently provide examples of training with a smaller collection of attempts. They also differ in their assignment requirements and in how frequently the submitted code fails to parse. The contrast with the exercises that have thousands of training submissions is a comparison among tasks as they appeared in the course data. It does not vary training-set size independently.
The amount of tokenized source differs across assignments as well. The parseable recurPower attempts yield 338,958 tokens, and iterPower yields 358,849. The training token count for oddTuples is 385,264. The smaller evalPoly and compDeriv corpora yield 55,370 and 18,557 tokens, respectively. Vocabulary sizes vary for reasons beyond corpus size. For example, the initial recurPower vocabulary contains 191 distinct tokens, compared with 795 for iterPower. After the authors apply their frequency cutoff, those training vocabularies contain 117 and 526 entries, respectively.
Training settings and the repair measure
For the main training procedure, the authors report a learning rate of 0. 002, with 10 as the training sequence length and 50 as the batch size. Training sequence length concerns the amount of ordered input in a training sequence. It is distinct from the prediction length used to build a repair candidate. The batch size controls how many training examples are grouped for a weight update. The authors use batch gradient descent with RMSProp at a decay rate of 0.97, and clip gradients at a threshold of 5 to limit large updates.
The networks underwent up to 40 epochs of training, with each epoch consisting of one pass through the training data. The authors report an average training time of 1.5 hours for a network across the assignment runs. Their experiments used a 1. A 4 GHz Intel Core i5 processor and 4 GB of RAM. That timing describes the training procedure on the reported hardware. The paper evaluates repair coverage through the number of submissions helped, without linking that coverage to a measured repair response time for a student.
The main results use LSTM-(2,128). In the authors’ naming scheme the first entry is the number of hidden layers and the second is the number of units in each such layer. Each test attempt can land in the completely repaired group, the partially repaired group, or the remaining group. For a complete repair, the edited program passes the syntax check. For a partial repair, the first error is resolved and an error on a later line still blocks parsing. The paper calls this second category Fixed (Other) in its main result table.
This outcome measure follows the practical task SynFix was designed to perform. The authors are interested in whether a prediction can lead to a usable change in source that failed to parse. A token prediction can be wrong in several positions and still produce a useful edit if the first predicted token fixes a missing operator. Conversely, a plausible series of tokens can fail as a repair if it collides with code already present. The reported rates measure the effect of trying predicted tokens in the program. They should be read as submission-level coverage for the specified outcomes.
Complete and partial repairs
Across all tested assignments, 4501 of the 14,203 syntax-error submissions passed the parser after an edit, which the authors report as 31.69%. Another 908 fall in the partial category, or 6.39% of the same test partition. The remaining 61.92% did not receive a repair that qualified for either of those results. A program in the fully repaired group had entered the evaluation unable to parse, so passing gives a concrete change in what the student can do next. It is then possible to proceed to checks that require syntactically valid input.
Complete syntax repair by SynFix on the edX assignment test sets
The iterative exponentiation assignment had the highest complete-repair rate, and the tuple assignment had the lowest.
The numbers
| System or setting | complete repair % |
|---|---|
| recurPower | 51.23 |
| iterPower (this paper) | 60 |
| oddTuples | 17.85 |
| evalPoly | 40.43 |
| compDeriv | 41.79 |
On recurPower, 1061 of the 2071 syntax-error submissions were completely repaired. The system found a partial repair for 281, or 13.57% of that assignment’s test cases. On iterPower, there were 1599 complete repairs among 2661 test attempts. The 276 partial repairs amount to 10.37% of that test set. Though the tasks compute the same mathematical result, the figures describe separate assignment-specific predictors and separate populations of errors.
oddTuples yielded 1575 complete repairs and 303 partial ones. Its partial-repair share was 3.43%. The complete count can look close to that of iterPower until the different numbers of failed submissions are taken into account. The tuple assignment accounts for a large part of the pool requiring repair, and its comparatively low coverage carries substantial weight in the pooled rate. The aggregated result counts submissions across the course exercises, so each assignment’s influence depends on how many attempts it contributes.
In evalPoly, SynFix completely repaired 131 of the 324 syntax-error submissions. It partially repaired 38, or 11.73% of those test cases. In compDeriv, 135 of the 323 test submissions were completely repaired and 10, or 3.09%, were partially repaired. Together with the training counts, these outcomes establish that the technique sometimes makes useful predictions from a few hundred parseable attempts in this setting. The result is particularly relevant to the authors’ training design, since the two exercises do not borrow training examples from the larger assignments.
The authors investigated why the tuple exercise lagged behind. Their manual inspection identified many indentation errors, as well as student strategies that were absent from the training set. The observation is consistent with the proposed mechanism. Even a well-formed local expression may provide weak evidence about which block a student intended, and an unfamiliar strategy can put the network in a context for which it has few relevant examples. The inspection does not assign a separate effect size to either explanation.
Neural network baselines
The baseline comparison holds the repair task to recurPower, using its 2071 syntax-error submissions. The authors change the recurrent architecture that generates the proposed continuation and evaluate how frequently SynFix can use the proposal to repair a program. The configurations in their numerical table vary network type, layer count, and hidden width. These are comparisons within the same general repair approach. A parser-only repair system, an earlier feedback tool, and an unrestricted search are outside the comparison.
Complete repairs on the recurPower syntax-error test set by recurrent network
The simple recurrent network with the smaller single hidden layer produced the most complete repairs.
The numbers
| System or setting | completely repaired submissions |
|---|---|
| RNN-(1,128) (this paper) | 1078 |
| RNN-(2,128) | 1062 |
| RNN-(2,256) | 990 |
| LSTM-(1,128) | 1028 |
| LSTM-(2,128) | 1061 |
| LSTM-(2,256) | 1045 |
The RNN-(1,128) configuration also led when the two qualifying repair outcomes were counted together, with 1365 completely or partially repaired submissions. It produced 287 partial repairs. The main LSTM-(2,128) configuration produced 281 partial repairs and 1342 submissions in the combined categories on the same exercise. The RNN-(2,256) configuration had 302 partial repairs, alongside the lowest complete-repair count in the chart. Looking at both kinds of result shows how a configuration can yield more edits that let parsing advance while producing fewer programs that parse in full.
The paper’s prose list of configurations differs from its numerical table. The prose names LSTM-(1,256) among the baselines, while the table reports outcomes for RNN-(2,256). The chart follows the architecture labels paired with the actual repair counts. The authors’ overall multi-assignment result still comes from LSTM-(2,128). The baseline win by a simpler network applies to recurPower, the task on which all the reported architectures were compared.
What the ablations show
Moving the prefix boundary and changing the edit
The most direct investigation of the repair procedure separates the choices that SynFix combines. The authors compare predictions made at the reported offset, predictions starting one token earlier, and the previous-line fallback. For the local boundaries, they measure insertion and replacement separately. Each count describes what that choice can accomplish. The same submission can be amenable to more than one choice, so these are overlapping outcomes.
For complete repairs pooled across the test submissions, the exact-offset insertion setting found 94 cases, and exact-offset replacement found 90. With Offset-1, insertion found 1690 complete repairs, and replacement found 2371. Moving the prefix boundary back made a large difference under both edit operations. One interpretation is that the parser’s location is most informative when used to identify a neighborhood. The earlier boundary gives the predictor a chance to complete the sequence before it has already read a token implicated in the failure. The comparison shows the practical effect of the boundary on this corpus. It leaves the precise reason for each successful edit to be established from the individual program.
Replacement has its clearest advantage at the earlier boundary, where the reported complete-repair count is higher than for insertion. The exact-offset results order the operations the other way, and the paper reports that each choice has some cases it fixes uniquely. The effect follows from the kind of error a transformation can express. Missing material is frequently repaired by keeping the source as it is and adding the missing token. If an existing operator makes the statement ill-formed, keeping that operator can defeat a perfectly good prediction. The earlier boundary comparison is evidence for having both operations available.
PrevLine, the setting that generates a replacement line from the preceding code, yields 3637 complete repairs across the syntax-error test set when assessed as a choice. It has the highest complete-repair count of the settings in that breakdown. It can succeed when a mistake lies earlier on the line than the parser reports or when several tokens constitute the malformed fragment. Replacing the line gives the search more room to find an acceptable result. The same freedom allows a greater change to meaning, as the misspelled return example shows.
The authors still place line replacement after the local attempts. Their choice of order favors retaining the student’s expression when a smaller edit is adequate. The comparison measures parser acceptance for each option and supplies no direct test of whether the ranking preserves intent. It does explain why line replacement can contribute useful coverage in a combined system even though the authors prefer a local edit when one is available.
The distinction between an individual choice and the combined system also affects the partial counts. For recurPower, replacement at Offset-1 can resolve the first error while leaving a later error in 310 attempts. The assignment’s final partial outcome is 281. The paper explains that some attempts with a partial repair from an individual setting are completely repaired by another setting, so the main results count them in the complete group. A setting’s figures record its own success, while the combined figures classify programs by the outcome reported for the system.
The authors also describe weaker candidates among submissions with no qualifying overall repair. They estimate that the previous-line setting could provide some feedback for about 28% of the submissions in the remaining 61.92%. For these cases, the predicted line can remove the reported problem on the original line while the resulting program still fails to parse. A replacement can itself introduce an error. The paper excludes this group from its partial-repair count and suggests that the lines might nonetheless give students a clue. That possibility was not tested as a learning outcome.
Choosing what the vocabulary preserves
The vocabulary experiment varies the frequency cutoff while keeping the assignment and recurrent architecture fixed. It uses RNN-(1,128) on recurPower. The initial vocabulary has 191 entries under every setting. With a threshold of 1, the training vocabulary also has 191 entries. At 4, it has 117. At 8, it has 86. The increasing cutoff places more rare items in the shared IDENT category, giving the network fewer separate forms to learn.
Complete repairs on the recurPower test set by training vocabulary threshold
Grouping rare tokens helped, and the intermediate cutoff produced the most complete repairs.
The numbers
| System or setting | completely repaired submissions |
|---|---|
| Threshold 1 | 904 |
| Threshold 4 (this paper) | 1078 |
| Threshold 8 | 1068 |
The paper reports 307 partial repairs at threshold 1, 287 at 4, and 277 at 8. As in the architecture comparison, partial repairs count programs in which a later line still prevents complete success. The threshold with the most partial repairs gives the fewest complete repairs. The strongest complete count and the authors’ explanation for it concern how the preprocessing handles rare tokens in the prefix.
At the least aggressive cutoff, an unusual variable name can have its own entry while contributing very few training examples. A prefix containing that name then carries a distinction about which the network has had little opportunity to learn. Mapping rare names to a shared token lets it draw on occurrences of that category in other contexts. The improvement in the complete-repair count from the first to the intermediate setting supports the value of grouping for this exercise.
A higher cutoff can also remove useful distinctions. The authors hypothesize that some of the tokens grouped at 8 retain information that helps specify the appropriate continuation. The complete-repair result at 8 is below that at 4, which is consistent with the hypothesis. The experiment establishes the ordering of the tested settings on recurPower. It does not identify individual tokens responsible for it or determine a single best threshold for the other assignments.
Testing greater recurrent capacity
The architecture results put the motivation for LSTM in perspective. Its capacity for retaining earlier information is relevant to code in which a useful clue may occur far back in the prefix. On the tested exponentiation exercise, the simpler RNN-(1,128) yielded the strongest complete and combined repair counts. The procedure asks the network for continuations near a diagnosed error, and success can hinge on a very local relationship, such as the operator expected after a variable in a condition. In this setting, the architecture with the more elaborate mechanism for retaining context did not establish an advantage.
Increasing depth or width also failed to give a consistent improvement. The authors suggest that larger configurations may fit peculiarities of the training sequences and generalize less well to the erroneous submissions. This is their proposed account of the observed ordering. The comparison reports downstream repair counts, so it does not measure overfitting directly. Grammatical edit coverage also depends on what happens when the continuation is turned into candidate insertions and replacements. The experiment could show which network helped this search more often, without identifying exactly which property of its predictions made the difference.
The task differences offer a separate kind of analysis. The oddTuples inspection concerns which strategies and errors occur in the corpus, whereas the architecture and threshold comparisons change part of the machinery on a fixed assignment. Those kinds of evidence answer different questions. The controlled settings reveal that preprocessing and candidate construction affect the reported coverage. The inspection helps explain why a system built around recurring examples can still struggle on a task with abundant parseable code.
Limitations
Limits identified by the authors
SynFix addresses one reported error in a pass. In the paper’s multiple-error example, inserting an indentation token before a return statement fixes the immediate problem, after which Python reports another indentation error farther down. The change can help a student make progress, but the program stays outside the complete-repair category. The authors propose calling SynFix again on the updated source, using the next parser error to guide a new repair. They do not report how frequently that repeated process would reach a fully parseable program or how earlier edits would influence later proposals.
The predictor uses the prefix before the error. The authors give a recursive exponentiation example in which the code following the faulty condition says return base. That line supports the interpretation that the condition should test exp == 1. The prefix-based suggestion is exp == 0. Either comparison is grammatically possible, and the difference matters for how the recursion behaves. The example isolates a type of evidence the parser can see when checking the full program but the predictor cannot use to choose its completion.
A bidirectional recurrent network is the authors’ proposed way to incorporate context from both directions. It could use code before and after the edit location while predicting what belongs there. In the paper, this is a direction for investigation, with questions about training and improvement in coverage still open. The example demonstrates a case where later context is informative. It does not establish that a bidirectional approach would recover the student’s intended condition generally.
The authors explicitly limit their acceptance criterion to syntax. Consider the malformed call recurPower(base,exp-=1). One top prediction gives recurPower(base,exp-11). The revised call is grammatically acceptable, yet it changes the reduction of the exponent and fails to express the intended computation. This example goes beyond the worry that a program might happen to return the wrong value in spite of a good local edit. Here, the act of repairing the syntax supplies part of the incorrect computation. The authors suggest checking meaning as part of repair and asking for alternative sequences when a candidate fails that additional check.
The final stated limit concerns the difference between providing an edit and teaching the student. A missing delimiter can be a typing slip whose correction is clear once someone points it out. A statement such as return = exp may reflect a belief that return is a variable, and an assignment inside a call argument can reflect confusion about what forms an expression. A parser-accepted replacement may let the student continue while leaving the relevant distinction unexplained. The authors propose distinguishing simple slips from errors that indicate a misconception, then designing feedback appropriate to each. Their study tests repair behavior. It provides no measurement of how students understand or respond to the changes.
Limits of the evaluation design
The empirical scope is a set of Python exercises from the same introductory course. Training and testing are separated by parseability within each exercise. This supports a claim about whether patterns from parseable attempts at an assignment can help other attempts at that assignment. It leaves cross-assignment transfer, use in another course, and use in a different programming language untested. The assignment-specific training choice is central to the method, so generalization to a new setting would require evidence about how well the new training corpus represents the programs in which repairs are needed.
The unit of analysis is the submission. The headline percentages therefore concern attempts with syntax errors. A claim about the share of learners helped would require linking outcomes to learners and accounting for repeated attempts. Likewise, a result for the share of syntax errors repaired would require counting individual errors, including later ones in submissions where the parser stops at the earliest failure. The reported experiment measures the availability of repairs at the program level after applying the procedure to the first reported problem.
Different assignments bring different code, training volumes, and error distributions. The polynomial results are encouraging evidence about smaller observed corpora. They do not establish a training-data requirement, because the authors did not repeatedly reduce the training set for a fixed task and retest the same faulty submissions. The low score on oddTuples, in spite of a large amount of training source, shows why training volume alone is incomplete as an explanation. Data quantity can help only insofar as the included examples provide evidence for the contexts and strategies encountered during repair.
The comparison with other feedback work establishes the representational gap motivating SynFix. The empirical baselines test neural architecture choices within SynFix, and the edit breakdown tests its own repair settings. The design gives no direct estimate of whether learning is necessary for the easiest repairs. A missing colon, for example, is both an opportunity for a learned continuation and a kind of error that could be addressed by a specifically designed rule. The paper does not benchmark such a rule-based alternative on the same test attempts. It establishes the observed coverage of learning plus search and parsing, while leaving component-level comparisons to other repair approaches open.
There is also a boundary between what the pseudocode specifies and what the reported categories imply. The compact algorithm accepts an edit when the program parses, otherwise proceeding through its search and eventual failure return. The evaluation separately credits local progress when an error remains on another line. It also analyzes an additional prefix boundary whose integration is described in the prose and results. Those descriptions establish the choices and outcomes that were measured. A reader reproducing the study would still need implementation details for such cases as how qualifying partial repairs are retained when none of the candidates parses completely.
Finally, no gold edit establishes what each student meant to write. Parser acceptance is a clear criterion for a complete syntax repair, and the paper gives specific examples where that criterion and intended behavior diverge. Even a program that passes a later functional check could implement a different strategy from the one the student was attempting. The strongest claim supported here is that SynFix can propose an edit that takes many submissions past a particular obstacle, with documented cases where a legal edit is a poor account of the intended program. Whether the edit is the best feedback for that student is a question the experiment leaves open.
What came after
The subsequent citation is a survey that places machine learning for source code in the broader study of regularities in programming. Its connection to SynFix is through that shared subject. Bhatia and Singh use repeated patterns in code to propose what should appear around a syntax error, turning a principle already used for code completion and style suggestions into a repair procedure for student submissions. In the later work, the documented relationship is the citation itself. An extension of SynFix, a replication of its results, or a head-to-head evaluation is not established by that relationship. A Survey of Machine Learning for Big Code and Naturalness
Cite
Cite as Sahil Bhatia and Rishabh Singh. 2016. Automated Correction for Syntax Errors in Programming Assignments using Recurrent Neural Networks. arXiv:1603.06129.
@misc{bhatia2016automated,
title = {{Automated Correction for Syntax Errors in Programming Assignments using Recurrent Neural Networks}},
author = {Sahil Bhatia and Rishabh Singh},
year = {2016},
doi = {10.48550/arxiv.1603.06129},
eprint = {1603.06129},
archivePrefix = {arXiv},
url = {https://doi.org/10.48550/arxiv.1603.06129}
}This page in Markdown https://md.research.elamur.ai/free/en/papers/bhatia-2016-automated-correction-syntax-errors-programming/