Skip to content

Commit 7ae671d

Browse files
ignatiraboIgnacio Tiraboschi
andauthored
Support for labels with no statement (#562)
* Add possibility to omit semicolon in labeled statement * Add extra rule to properly parse semicolons so that the ASTs remain equal. Add test corroborating equality of ASTs * Remove unnecesary rule for labeled statements * Update label test to check the structure of the AST --------- Co-authored-by: Ignacio Tiraboschi <ignacio.tiraboschi@eclypsium.com>
1 parent 42b5423 commit 7ae671d

2 files changed

Lines changed: 18 additions & 0 deletions

File tree

pycparser/c_parser.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1580,6 +1580,10 @@ def p_labeled_statement_3(self, p):
15801580
""" labeled_statement : DEFAULT COLON pragmacomp_or_statement """
15811581
p[0] = c_ast.Default([p[3]], self._token_coord(p, 1))
15821582

1583+
def p_labeled_statement_4(self, p):
1584+
""" labeled_statement : ID COLON """
1585+
p[0] = c_ast.Label(p[1], c_ast.EmptyStatement(self._token_coord(p, 1)), self._token_coord(p, 1))
1586+
15831587
def p_selection_statement_1(self, p):
15841588
""" selection_statement : IF LPAREN expression RPAREN pragmacomp_or_statement """
15851589
p[0] = c_ast.If(p[3], p[5], None, self._token_coord(p, 1))

tests/test_c_parser.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2489,6 +2489,20 @@ def test_samescope_reuse_name(self):
24892489
'''
24902490
self.assertRaises(ParseError, self.parse, s2)
24912491

2492+
def test_label_empty_statement(self):
2493+
# Labels with empty statements and no semicolon should be parsed correctly
2494+
s1 = r'''
2495+
int main() {
2496+
int i = 0;
2497+
label0: i++;
2498+
label1:
2499+
}
2500+
'''
2501+
s1_ast : FileAST = self.parse(s1)
2502+
self.assertIsInstance(s1_ast.ext[0].body.block_items[1], Label)
2503+
self.assertIsInstance(s1_ast.ext[0].body.block_items[1].stmt, UnaryOp)
2504+
self.assertIsInstance(s1_ast.ext[0].body.block_items[2], Label)
2505+
self.assertIsInstance(s1_ast.ext[0].body.block_items[2].stmt, EmptyStatement)
24922506

24932507
if __name__ == '__main__':
24942508
#~ suite = unittest.TestLoader().loadTestsFromNames(

0 commit comments

Comments
 (0)