Skip to content

Commit

Permalink
Accept empty 'case' or 'default' labels (#564)
Browse files Browse the repository at this point in the history
  • Loading branch information
ignatirabo authored Feb 18, 2025
1 parent 7ae671d commit 9cecc09
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
8 changes: 8 additions & 0 deletions pycparser/c_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -1584,6 +1584,14 @@ def p_labeled_statement_4(self, p):
""" labeled_statement : ID COLON """
p[0] = c_ast.Label(p[1], c_ast.EmptyStatement(self._token_coord(p, 1)), self._token_coord(p, 1))

def p_labeled_statement_5(self, p):
""" labeled_statement : CASE constant_expression COLON """
p[0] = c_ast.Case(p[2], [c_ast.EmptyStatement(self._token_coord(p, 2))], self._token_coord(p, 1))

def p_labeled_statement_6(self, p):
""" labeled_statement : DEFAULT COLON """
p[0] = c_ast.Default([c_ast.EmptyStatement(self._token_coord(p, 1))], self._token_coord(p, 1))

def p_selection_statement_1(self, p):
""" selection_statement : IF LPAREN expression RPAREN pragmacomp_or_statement """
p[0] = c_ast.If(p[3], p[5], None, self._token_coord(p, 1))
Expand Down
34 changes: 34 additions & 0 deletions tests/test_c_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -2504,6 +2504,40 @@ def test_label_empty_statement(self):
self.assertIsInstance(s1_ast.ext[0].body.block_items[2], Label)
self.assertIsInstance(s1_ast.ext[0].body.block_items[2].stmt, EmptyStatement)

def test_case_empty_statement(self):
# Labels with empty statements and no semicolon should be parsed correctly
s1 = r'''
int main() {
int i = 0;
switch (i) {
case 0:
i = 1;
case 1:
}
return i;
}
'''
s2 = r'''
int main() {
int i = 0;
switch (i) {
case 0:
i = 1;
default:
}
return i;
}
'''
s1_ast : FileAST = self.parse(s1)
s2_ast : FileAST = self.parse(s2)
self.assertIsInstance(s1_ast.ext[0].body.block_items[1], Switch)
self.assertIsInstance(s1_ast.ext[0].body.block_items[1].stmt, Compound)
self.assertIsInstance(s1_ast.ext[0].body.block_items[1].stmt.block_items[0], Case)
self.assertIsInstance(s1_ast.ext[0].body.block_items[1].stmt.block_items[0].stmts[0], Assignment)
self.assertIsInstance(s1_ast.ext[0].body.block_items[1].stmt.block_items[1], Case)
self.assertIsInstance(s1_ast.ext[0].body.block_items[1].stmt.block_items[1].stmts[0], EmptyStatement)
self.assertIsInstance(s2_ast.ext[0].body.block_items[1].stmt.block_items[1].stmts[0], EmptyStatement)

if __name__ == '__main__':
#~ suite = unittest.TestLoader().loadTestsFromNames(
#~ ['test_c_parser.TestCParser_fundamentals.test_typedef'])
Expand Down

0 comments on commit 9cecc09

Please # to comment.