Paper:
A Syntactic Neural Model for General-Purpose Code Generation
We consider the problem of parsing natural language descriptions into source code written in a general-purpose programming language like Python. Existing datadriven methods treat this problem as a language generation task without considering the underlying syntax of the target programming language. Informed by previous work in semantic parsing, in this paper we propose a novel neural architecture powered by a grammar model to explicitly capture the target syntax as prior knowledge. Experiments find this an effective way to scale up to generation of complex programs from natural language descriptions, achieving state-of-the-art results that well outperform previous code generation and semantic parsing approaches.
1 Introduction
Every programmer has experienced the situation where they know what they want to do, but do not have the ability to turn it into a concrete implementation. For example, a Python programmer may want to “sort my list in descending order,” but not be able to come up with the proper syntax sorted(my list, reverse=True) to realize his intention. To resolve this impasse, it is common for programmers to search the web in natural language (NL), find an answer, and modify it into the desired form (Brandt et al., 2009, 2010). However, this is time-consuming, and thus the software engineering literature is ripe with methods to directly generate code from NL descriptions, mostly with hand-engineered methods highly tailored to specific programming languages (Balzer, 1985; Little and Miller, 2009; Gvero and Kuncak, 2015).
In parallel, the NLP community has developed methods for data-driven semantic parsing, which attempt to map NL to structured logical forms executable by computers. These logical forms can be general-purpose meaning representations (Clark and Curran, 2007; Banarescu et al., 2013), formalisms for querying knowledge bases (Tang and Mooney, 2001; Zettlemoyer and Collins, 2005; Berant et al., 2013) and instructions for robots or personal assistants (Artzi and Zettlemoyer, 2013; Quirk et al., 2015), among others. While these methods have the advantage of being learnable from data, compared to the programming languages (PLs) in use by programmers, the domainspecific languages targeted by these works have a schema and syntax that is relatively simple.
Recently, Ling et al. (2016) have proposed a data-driven code generation method for high-level, general-purpose PLs like Python and Java. This work treats code generation as a sequence-tosequence modeling problem, and introduce methods to generate words from character-level models, and copy variable names from input descriptions. However, unlike most work in semantic parsing, it does not consider the fact that code has to be well-defined programs in the target syntax.
In this work, we propose a data-driven syntaxbased neural network model tailored for generation of general-purpose PLs like Python. In order to capture the strong underlying syntax of the PL, we define a model that transduces an NL statement into an Abstract Syntax Tree (AST; Fig. 1(a), § 2) for the target PL. ASTs can be deterministically generated for all well-formed programs using standard parsers provided by the PL, and thus give us a way to obtain syntax information with minimal engineering. Once we generate an AST, we can use deterministic generation tools to convert the AST into surface code. We hypothesize that such a structured approach has two benefits.
2
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
Production Rule Role Explanation Call 7→ expr[func] expr*[args] keyword*[keywords] Function Call . func: the function to be invoked . args: arguments list . keywords: keyword arguments list If 7→ expr[test] stmt*[body] stmt*[orelse] If Statement . test: condition expression . body: statements inside the If clause . orelse: elif or else statements For 7→ expr[target] expr*[iter] stmt*[body] For Loop . target: iteration variable . iter: enumerable to iterate over . body: loop body . orelse: else statementsstmt*[orelse] FunctionDef 7→ identifier[name] arguments*[args] Function Def. . name: function name . args: function arguments
. body: function bodystmt*[body]
Table 1: Example production rules for common Python statements (Python Software Foundation, 2016)
First, we hypothesize that structure can be used to constrain our hypothesis space, ensuring generation of well-formed code. To this end, we propose a syntax-driven neural code generation model. The backbone of our approach is a grammar model (§ 3) which formalizes the generation story of a derivation AST into sequential application of actions that either apply production rules (§ 3.1), or emit terminal tokens (§ 3.2). The underlying syntax is therefore encoded in the grammar model a priori as the set of possible actions. Our approach frees the model from recovering the underlying grammar from limited training data, and instead enables the system to focus on learning the compositionality among existing grammar rules. Xiao et al. (2016) have noted that this imposition of structure on neural models is useful for semantic parsing, and we expect this to be even more important for general-purpose PLs where the syntax trees are larger and more complex.
Second, we hypothesize that structural information helps to model information flow within the network, which naturally reflects the recursive structure of PLs. To test this, we extend a standard recurrent neural network (RNN) decoder to allow for additional neural connections which reflect the recursive structure of an AST (§ 4.2). As an example, when expanding the node ? in Fig. 1(a), we make use of the information from both its parent and left sibling (the dashed rectangle). This enables us to locally pass information of relevant code segments via neural network connections, resulting in more confident predictions.
Experiments (§ 5) on two Python code generation tasks show 11.7% and 9.3% absolute improvements in accuracy against the state-of-the-art system (Ling et al., 2016). Our model also gives competitive performance on a standard semantic parsing benchmark.
2 The Code Generation Problem
Given an NL description x, our task is to generate the code snippet c in a modern PL based on the in-
tent of x. We attack this problem by first generating the underlying AST. We define a probabilistic grammar model of generating an AST y given x: p(y|x). The best-possible AST ŷ is then given by
ŷ = argmax y
p(y|x). (1)
ŷ is then deterministically converted to the corresponding surface code c.1 While this paper uses examples from Python code, our method is PLagnostic.
Before detailing our approach, we first present a brief introduction of the Python AST and its underlying grammar. The Python abstract grammar contains a set of production rules, and an AST is generated by applying several production rules composed of a head node and multiple child nodes. For instance, the first rule in Tab. 1 is used to generate the function call sorted(·) in Fig. 1(a). It consists of a head node of type Call, and three child nodes of type expr, expr* and keyword*, respectively. Labels of each node are noted within brackets. In an AST, non-terminal nodes sketch the general structure of the target code, while terminal nodes can be categorized into two types: operation terminals and variable terminals. Operation terminals correspond to basic arithmetic operations like AddOp.Variable terminal nodes store values for variables and constants of built-in data types2. For instance, all terminal nodes in Fig. 1(a) are variable terminal nodes.
3 Grammar Model
Before detailing our neural code generation method, we first introduce the grammar model at its core. Our probabilistic grammar model defines the generative story of a derivation AST. We factorize the generation process of an AST into sequential application of actions of two types:
• APPLYRULE[r] applies a production rule r to the current derivation tree;
1We use astor library to convert ASTs into Python code. 2bool, float, int, str.
3
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
Expr
root
expr[value]
Call
expr*[args] keyword*[keywords]
Name
str(sorted)
expr[func]
expr
Name
str(my_list)
keyword
str(reverse) expr[value]
Name
str(True)
( _ , = )
⋆
t1
t2
t3
t4
t5
t6
t7
t8
t9
t10
t11
t12
t14
root ↦ Expr
Expr ↦ expr[value]
expr ↦ Call
expr ↦ Name
Name ↦ str
[sorted]
[</n>]
expr* ↦ expr
expr ↦ Name
Name ↦ str
[my_list]
keyword* ↦ keyword
Call ↦ expr[func]  expr*[args]  keyword*[keywords]
Action Flow Parent Feeding
ti Apply Rule
ti Generate Token
ti GenToken with Copyt13 [</n>]
t1
t2
t3
t4
t5
t6t7t8
t4
t9
t10
t11 t12 t13
t4
t14
t15 t16 t17 t16
t18
t19 t20 t21
t0
(a) (b)
_ Input: Code:
. . .
Figure 1: (a) the Abstract Syntax Tree (AST) for the given example code. Dashed nodes denote terminals. Nodes are labeled with time steps during which they are generated. (b) the action sequence (up to t14) used to generate the AST in (a)
• GENTOKEN[v] populates a variable terminal node by appending a terminal token v.
Fig. 1(b) shows the generation process of the target AST in Fig. 1(a). Each node in Fig. 1(b) indicates an action. Action nodes are connected by solid arrows which depict the chronological order of the action flow. The generation proceeds in depth-first, left-to-right order (dotted arrows represent parent feeding, explained in § 4.2.1).
Formally, under our grammar model, the probability of generating an AST y is factorized as:
p(y|x) = T∏ t=1 p(at|x, a<t), (2)
where at is the action taken at time step t, and a<t is the sequence of actions before t. We will explain how to compute Eq. (2) in § 4. Put simply, the generation process begins from a root node at t0, and proceeds by the model choosing APPLYRULE actions to generate the overall program structure from a closed set of grammar rules, then at leaves of the tree corresponding to variable terminals, the model switches to GENTOKEN actions to generate variables or constants from the open set. We describe this process in detail below.
3.1 APPLYRULE Actions
APPLYRULE actions generate program structure, expanding the current node (the frontier node at time step t: nft) in a depth-first, left-to-right traversal of the tree. Given a fixed set of production rules, APPLYRULE chooses a rule r from the subset that has a head matching the type of nft , and uses r to expand nft by appending all child nodes specified by the selected production. As an
example, in Fig. 1(b), the rule Call 7→ expr. . . expands the frontier node Call at time step t4, and its three child nodes expr, expr* and keyword* are added to the derivation.
APPLYRULE actions grow the derivation AST by appending nodes. When a variable terminal node (e.g., str) is added to the derivation and becomes the frontier node, the grammar model then switches to GENTOKEN actions to populate the variable terminal with tokens.
Unary Closure Sometimes, generating an AST requires applying a chain of unary productions. For instance, it takes three time steps (t9 − t11) to generate the sub-structure expr* 7→ expr 7→ Name 7→ str in Fig. 1(a). This can be effectively reduced to one step of APPLYRULE action by taking the closure of the chain of unary productions and merging them into a single rule: expr* 7→∗ str. Unary closures reduce the number of actions needed, but would potentially increase the size of the grammar. In our experiments we tested our model both with and without unary closures (§ 5).
3.2 GENTOKEN Actions
Once we reach a frontier node nft that corresponds to a variable type (e.g., str), GENTOKEN actions are used to fill this node with values. For generalpurpose PLs like Python, variables and constants have values with one or multiple tokens. For instance, a node that stores the name of a function (e.g., sorted) has a single token, while a node that denotes a string constant (e.g., a=‘hello world’) could have multiple tokens. Our model copes with both scenarios by firing GENTOKEN actions at one or more time steps. At each time
4
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
step, GENTOKEN appends one terminal token to the current frontier variable node. A special </n> token is used to “close” the node. The grammar model then proceeds to the new frontier node.
Terminal tokens can be generated from a predefined vocabulary, or be directly copied from the input NL. This is motivated by the observation that the input description often contains out-ofvocabulary (OOV) variable names or literal values that are directly used in the target code. For instance, in our running example the variable name my list can be directly copied from the the input at t12. We give implementation details in § 4.2.2.
4 Estimating Action Probabilities
We estimate action probabilities in Eq. (2) using attentional neural encoder-decoder models with an information flow structured by the syntax trees.
4.1 Encoder
For an NL description x consisting of n words {wi}ni=1, the encoder computes a context sensitive embedding hi for each wi using a bidirectional Long Short-Term Memory (LSTM) network (Hochreiter and Schmidhuber, 1997), similar to the setting in (Bahdanau et al., 2014). See supplementary materials for detailed equations.
4.2 Decoder
The decoder uses a RNN to model the sequential generation process of an AST defined as Eq. (2). Each action step in the grammar model naturally grounds to a time step in the decoder RNN. Therefore, the action sequence in Fig. 1(b) can be interpreted as unrolling RNN time steps, with solid arrows indicating RNN connections. The RNN maintains an internal state to track the generation process (§ 4.2.1), which will then be used to compute action probabilities p(at|x, a<t) (§ 4.2.2).
4.2.1 Tracking Generation States
Our implementation of the decoder resembles a vanilla LSTM, with additional neural connections (parent feeding, Fig. 1(b)) to reflect the topological structure of an AST. The decoder’s internal hidden state at time step t, st, is given by:
st = fLSTM([at−1 : ct : pt : nft ], st−1), (3) where fLSTM(·) is the LSTM update function. [:] denotes vector concatenation. st will then be used to compute action probabilities p(at|x, a<t) in Eq. (2). Here, at−1 is the embedding of the previous action. ct is a context vector retrieved from
input encodings {hi} via soft attention. pt is a vector that encodes the information of the parent action. nft denotes the node type embedding of the current frontier node nft
3. Intuitively, feeding the decoder the information of nft helps the model to keep track of the frontier node to expand. Action Embedding at We maintain two action embedding matrices, WR and WG. Each row in WR (WG) corresponds to an embedding vector for an action APPLYRULE[r] (GENTOKEN[v]). Context Vector ct The decoder RNN uses soft attention to retrieve a context vector ct from the input encodings {hi} pertain to the prediction of the current action. We follow Bahdanau et al. (2014) and use a Deep Neural Network (DNN) with a single hidden layer to compute attention weights. Parent Feeding pt Our decoder RNN uses additional neural connections to directly pass information from parent actions. For instance, when computing s9, the information from its parent action step t4 will be used. Formally, we define the parent action step pt as the time step at which the frontier node nft is generated. As an example, for t9, its parent action step p9 is t4, since nf9 is the node ?, which is generated at t4 by the APPLYRULE[Call7→. . .] action.
We model parent information pt from two sources: (1) the hidden state of parent action spt , and (2) the embedding of parent action apt . pt is the concatenation. The parent feeding schema enables the model to utilize the information of parent code segments to make more confident predictions. Similar approaches of injecting parent information were also explored in the SEQ2TREE model in Dong and Lapata (2016)4.
3We maintain an embedding for each node type. 4SEQ2TREE generates tree-structured outputs by condi-
5
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
4.2.2 Calculating Action Probabilities
In this section we explain how action probabilities p(at|x, a<t) are computed based on st. APPLYRULE The probability of applying rule r as the current action at is given by a softmax5:
p(at = APPLYRULE[r]|x, a<t) = softmax(WR · g(st))ᵀ · e(r) (4)
where g(·) is a non-linearity tanh(W ·st+b), and e(r) the one-hot vector for rule r. GENTOKEN As in § 3.2, a token v can be generated from a predefined vocabulary or copied from the input, defined as the marginal probability:
p(at = GENTOKEN[v]|x, a<t) = p(gen|x, a<t)p(v|gen, x, a<t) + p(copy|x, a<t)p(v|copy, x, a<t).
The selection probabilities p(gen|·) and p(copy|·) are given by softmax(WS · st). The probability of generating v from the vocabulary, p(v|gen, x, a<t), is defined similarly as Eq. (4), except that we use the embedding matrix of GENTOKEN, WG. To model the copy probability, we follow recent advances in modeling copying mechanism in neural networks (Gu et al., 2016; Jia and Liang, 2016; Ling et al., 2016), and use a pointer network (Vinyals et al., 2015) to compute the probability of copying the i-th word from the input by attending to input representations {hi}:
p(wi|copy, x, a<t) = exp(ω(hi, st, ct))∑n
i′=1 exp(ω(hi′ , st, ct)) ,
where ω(·) is a DNN with a single hidden layer.
4.3 Training and Inference
Given a dataset of pairs of NL descriptions xi and code snippets ci, we parse ci into its AST yi and decompose yi into a sequence of oracle actions under the grammar model. The model is then optimized by maximizing the log-likelihood of the oracle action sequence. At inference time, we use beam search to approximate the best AST ŷ in Eq. (1). See supplementary materials for the pseudo-code of the inference algorithm.
5 Experimental Evaluation
5.1 Datasets and Metrics
HEARTHSTONE (HS) dataset (Ling et al., 2016) is a collection of Python classes that implement
tioning on the hidden states of parent non-terminals, while our parent feeding uses the states of parent actions.
5We do not show bias terms for all softmax equations.
cards for the card game HearthStone. Each card comes with a set of fields (e.g., name, cost, and description), which we concatenate to create the input sequence. This dataset is relatively difficult: input descriptions are short, while the target code is in complex class structures, with each AST having 137 nodes on average. DJANGO dataset (Oda et al., 2015) is a collection of lines of code from the Django web framework, each with a manually annotated NL description. Compared with the HS dataset where card implementations are somewhat homogenous, examples in DJANGO are more diverse, spanning a wide variety of real-world use cases like string manipulation, IO operations, and exception handling. IFTTT dataset (Quirk et al., 2015) is a domainspecific benchmark that provides an interesting side comparison. Different from HS and DJANGO which are in a general-purpose PL, programs in IFTTT are written in a domain-specific language used by the IFTTT task automation App. Users of the App write simple instructions (e.g., If Instagram.AnyNewPhotoByYou Then Dropbox.AddFileFromURL) with NL descriptions (e.g., “Autosave your Instagram photos to Dropbox”). Each statement inside the If or Then clause consists of a channel (e.g., Dropbox) and a function (e.g., AddFileFromURL)6. This simple structure results in much more concise ASTs (7 nodes on average). Because all examples are created by ordinary Apps users, the dataset is highly noisy, with input NL very loosely con-
6Like Beltagy and Quirk (2016), we strip function parameters since they are mostly specific to users.
6
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
nected to target ASTs. The authors thus provide a high-quality filtered test set, where each example is verified by at least three annotators. We use this set for evaluation. Also note IFTTT’s grammar has more productions (Tab. 2), but this does not imply that its grammar is more complex. This is because for HS and DJANGO terminal tokens are generated by GENTOKEN actions, but for IFTTT, all the code is generated directly by APPLYRULE actions. Metrics As is standard in semantic parsing, we measure accuracy, the fraction of correctly generated examples. However, because generating an exact match for complex code structures is nontrivial, we follow Ling et al. (2016), and use tokenlevel BLEU-4 with as a secondary metric, defined as the averaged smoothed BLEU (Lin and Och, 2004) scores over all examples.
5.2 Setup
Preprocessing All input descriptions are tokenized using NLTK. We perform simple canonicalization for DJANGO, such as replacing quoted strings in the inputs with place holders. See supplementary materials for details. We extract unary closures whose frequency is larger than a threshold k (k = 30 for HS and 50 for DJANGO). Configuration The size of all embeddings is 128, except for node type embeddings, which is 64. The dimensions of RNN states and hidden layers are 256 and 50, respectively. Since our datasets are relatively small for a data-hungry neural model, we impose strong regularization using recurrent dropouts (Gal and Ghahramani, 2016), together with standard dropout layers added to the inputs and outputs of the decoder RNN. We validate the dropout probability from {0, 0.2, 0.3, 0.4}. For decoding, we use a beam size of 15.
5.3 Results
Evaluation results for Python code generation tasks are listed in Tab. 3. Numbers for our systems are averaged over three runs. We compare primarily with two approaches: (1) Latent Predictor Network (LPN), a state-of-the-art sequenceto-sequence code generation model (Ling et al., 2016), and (2) SEQ2TREE, a neural semantic parsing model (Dong and Lapata, 2016). SEQ2TREE generates trees one node at a time, and the target grammar is not explicitly modeled a priori, but implicitly learned from data. We test both the original SEQ2TREE model released by the authors and our revised one (SEQ2TREE–UNK) that uses unknown word replacement to handle rare
words (Luong et al., 2015). For completeness, we also compare with a strong neural machine translation (NMT) system (Neubig, 2015) using a standard encoder-decoder architecture with attention and unknown word replacement, and include numbers from other baselines used in Ling et al. (2016). On the HS dataset, which has relatively large ASTs, we use unary closure for our model and SEQ2TREE, and for DJANGO we do not.
System Comparison As in Tab. 3, our model registers 11.7% and 9.3% absolute improvements over LPN in accuracy on HS and DJANGO. This boost in performance strongly indicates the importance of modeling grammar in code generation. For the baselines, we find LPN outperforms others in most cases. We also note that SEQ2TREE achieves a decent accuracy of 13.6% on HS, which is due to the effect of unknown word replacement, since we only achieved 1.5% without it. A closer comparison with SEQ2TREE is insightful for understanding the advantage of our syntax-driven approach, since both SEQ2TREE and our system output ASTs: (1) SEQ2TREE predicts one node each time step, and requires additional “dummy” nodes to mark the boundary of a subtree. The sheer number of nodes in target ASTs makes the prediction process error-prone. In contrast, the APPLYRULE actions of our grammar model allows for generating multiple nodes at a single time step. Empirically, we found that in HS, SEQ2TREE takes more than 300 time steps on average to generate a target AST, while our model takes only 170 steps. (2) SEQ2TREE does not directly use productions in the grammar, which possibly leads to grammat-
7
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
0 10 20 30 40 50 Reference AST Size (# nodes)
0.0
0.2
0.4
0.6
0.8
1.0
P e rf
o rm
a n ce
BLEU acc
Figure 3: Performance w.r.t reference AST size on DJANGO
50 100 150 200 250 Reference AST Size (# nodes)
0.0
0.2
0.4
0.6
0.8
1.0
P e rf
o rm
a n ce
BLEU acc
Figure 4: Performance w.r.t reference AST size on HS
ically incorrect ASTs and thus empty code outputs. We observe that the ratio of grammatically incorrect ASTs predicted by SEQ2TREE on HS and DJANGO are 21.2% and 10.9%, respectively, while our system guarantees grammaticality. Ablation Study We also ablated our bestperforming models to analyze the contribution of each component. “–frontier embed.” removes the frontier node embedding nft from the decoder RNN inputs (Eq. (3)). This yields worse results on DJANGO while gives slight improvements in accuracy on HS. This is probably because that the grammar of HS has fewer node types, and thus the RNN is able to keep track of nft without depending on its embedding. Next, “–parent feed.” removes the parent feeding mechanism. The accuracy drops significantly on HS, with a marginal deterioration on DJANGO. This result is interesting because it suggests that parent feeding is more important when the ASTs are larger, which will be the case when handling more complicated code generation tasks like HS. Finally, removing the pointer network (“–copy terminals”) in GENTOKEN actions gives poor results, indicating that it is important to directly copy variable names and values from the input.
The results with and without unary closure demonstrate that, interestingly, it is effective on HS but not on DJANGO. We conjecture that this is because on HS it significantly reduces the number of actions from 173 to 142 (c.f., Tab. 2), with the number of productions in the grammar remaining unchanged. In contrast, DJANGO has a broader domain, and thus unary closure results in more productions in the grammar (237 for DJANGO vs. 100 for HS), increasing sparsity. Performance by the size of AST We further investigate our model’s performance w.r.t. the size
of the gold-standard ASTs in Figs. 3 and 4. Not surprisingly, the performance drops when the size of the reference ASTs increases. Additionally, on the HS dataset, the BLEU score still remains at around 50 even when the size of ASTs grows to 200, indicating that our proposed syntax-driven approach is robust for long code segments. Domain Specific Code Generation Although this is not the focus of our work, evaluation on IFTTT brings us closer to a standard semantic parsing setting, which helps to investigate similarities and differences between generation of more complicated general-purpose code and and more limiteddomain simpler code. Tab. 4 shows the results, following the evaluation protocol in (Beltagy and Quirk, 2016) for accuracies at both channel and full parse tree (channel + function) levels. Our full model performs on par with existing neural network-based methods, while outperforming other neural models in full tree accuracy (82.0%). This score is close to the best classical method (LR), which is based on a logistic regression model with rich hand-engineered features (e.g., brown clusters and paraphrase). Also note that the performance between NMT and other neural models is much closer compared with the results in Tab. 3. This suggests that general-purpose code generation is more challenging than the simpler IFTTT setting, and therefore modeling structural information is more helpful. Case Studies Finally, we present output examples in Tab. 5. On HS, we observe that most of the time our model gives correct predictions by filling learned code templates from training data with arguments (e.g., cost) copied from input. However, we do find interesting examples indicating that the model learns to generalize beyond trivial copy-
8
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
input <name> Brawl </name> <cost> 5 </cost> <desc> Destroy all minions except one (chosen randomly) </desc> <rarity> Epic </rarity> ... pred. class Brawl(SpellCard): def init (self): super(). init (’Brawl’, 5, CHARACTER CLASS.
WARRIOR, CARD RARITY.EPIC) def use(self, player, game): super().use(player, game) targets = copy.copy(game.other player.minions) targets.extend(player.minions) for minion in targets: minion.die(self) A
ref. minions = copy.copy(player.minions) minions.extend(game.other player.minions) if len(minions) > 1: survivor = game.random choice(minions) for minion in minions: if minion is not survivor: minion.die(self) B
input join app config.path and string ’locale’ into a file path, substitute it for localedir. pred. localedir = os.path.join( app config.path, ’locale’) 3
input self.plural is an lambda function with an argument n, which returns result of boolean expression n not equal to integer 1 pred. self.plural = lambda n: len(n) 7 ref. self.plural = lambda n: int(n!=1)
Table 5: Predicted examples from HS (1st) and DJANGO. Copied contents (copy probability > 0.9) are highlighted.
ing. For instance, the first example is one that our model predicted wrong — it generated code block A instead of the gold B (it also missed a function definition not shown here). However, we find that the block A actually conveys part of the input intent by destroying all, not some, of the minions. Since we are unable to find code block A in the training data, it is clear that the model has learned to generalize to some extent from multiple training card examples with similar semantics or structure.
The next two examples are from DJANGO. The first one shows that the model learns the usage of common API calls (e.g., os.path.join), and how to populate the arguments by copying from inputs. The second example illustrates the difficulty of generating code with complex nested structures like lambda functions, a scenario worth further investigation in future studies. More examples are attached in supplementary materials.
6 Related Work
Code Generation and Analysis Most existing works on code generation focus on generating code for domain specific languages (DSLs) (Kushman and Barzilay, 2013; Raza et al., 2015; Manshadi et al., 2013), with neural network-based approaches recently explored (Parisotto et al., 2016; Balog et al., 2016). For general-purpose code gen-
eration, besides the general framework of Ling et al. (2016), existing methods often use language and task-specific rules and strategies (Lei et al., 2013; Raghothaman et al., 2016). A similar line is to use NL queries for code retrieval (Wei et al., 2015; Allamanis et al., 2015). The reverse task of generating NL summaries from source code has also been explored (Oda et al., 2015; Iyer et al., 2016). Finally, there are probabilistic models of source code (Maddison and Tarlow, 2014; Nguyen et al., 2013). The most relevant work is Allamanis et al. (2015), which uses a factorized model to measure semantic relatedness between NL and ASTs for code retrieval, while our model tackles the more challenging generation task. Semantic Parsing Our work is related to the general topic of semantic parsing, where the target logical forms can be viewed as DSLs. The parsing process is often guided by grammatical formalisms like combinatory categorical grammars (Kwiatkowski et al., 2013; Artzi et al., 2015), dependency-based syntax (Liang et al., 2011; Pasupat and Liang, 2015) or task-specific formalisms (Clarke et al., 2010; Yih et al., 2015; Krishnamurthy et al., 2016; Misra et al., 2015; Mei et al., 2016). Recently, there are efforts in designing neural network-based semantic parsers (Misra and Artzi, 2016; Dong and Lapata, 2016; Neelakantan et al., 2016). Several approaches have be proposed to utilize grammar knowledge in a neural parser, such as augmenting the training data by generating examples guided by the grammar (Kociský et al., 2016; Jia and Liang, 2016). Liang et al. (2016) used a neural decoder which constrains the space of next valid tokens in the query language for question answering. Finally, the structured prediction approach proposed by Xiao et al. (2016) is closely related to our model in using the underlying grammar as prior knowledge to constrain the generation process of derivation trees, while our method is based on a unified grammar model which jointly captures production rule application and terminal symbol generation, and scales to general purpose code generation tasks.
7 Conclusion
This paper proposes a syntax-driven neural code generation approach that generates an abstract syntax tree by sequentially applying actions from a grammar model. Experiments on both code generation and semantic parsing tasks demonstrate the effectiveness of our proposed approach.
9
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899

Review:
Summary: The paper proposes a neural model for predicting Python syntax trees from text descriptions. Guided by the actual Python grammar, the model generates tree nodes sequentially in a depth-first fashion. Key ideas include injecting the information from the parent node as part of the LSTM input, a pointer network for copying the terminals, and unary closure which collapses chains of unary productions to reduce the tree size. The model is evaluated on three datasets from different domains and outperforms almost all previous work.  Strengths:  The paper is overall very well-written. The explanation of system is clear, and the analysis is thorough.  The system itself is a natural extension of various ideas. The most similar work include tree-based generation with parent feeding (Dong and Lapata, 2016) and various RNN-based semantic parsing with copy mechanism (Jia and Liang, 2016; Ling et al., 2016). [The guidance of parsing based on grammar is also explored in Chen Liang et al., 2016 (https:  arxiv.org abs 1611.00020) where a code-assist system is used to ensure that the code is valid.] Nevertheless, the model is this paper stands out as it is able to generate much longer and more complex programs than most previous work mentioned.   Weaknesses:  The evaluation is done on code accuracy (exact match) and BLEU score. These metrics (especially BLEU) might not be the best metrics for evaluating the correctness of programs. For instance, the first example in Table 5 shows that while the first two lines in boxes A and B are different, they have the same semantics. Another example is that variable names can be different. Evaluation based on what the code does (e.g., using test cases or static code analysis) would be more convincing.  Another point about evaluation: other systems (e.g., NMT baseline) may generate code with syntactic error. Would it be possible to include the result on the highest-scoring well-formed code (e.g., using beam search) that these baseline systems generate? This would give a fairer comparison since these system can choose to prune malformed code.  General Discussion:  * Lines 120-121: some approaches that use domain-specific languages were also guided by a grammar. One example is Berant and Liang, 2014, which uses a pretty limited grammar for logical forms (Table 1). In addition to comparing to that line of work, emphasizing that the grammar in this paper is much larger than most previous work would make this work stronger.  * Lines 389-397: For the parent feeding mechanism, is the child index being used? In other words, is p_t different when generating a first child versus a second child? In Seq2Tree (Dong and Lapata, 2016) the two non-terminals would have different hidden states.  * Line 373: Are the possible tokens embedded? Is it assumed that the set of possible tokens is known beforehand?  * The examples in the appendix are nice.  ---  I have read the author response.