Skip to content

Commit

Permalink
Fix eliben#385: generate code with nested sizeofs
Browse files Browse the repository at this point in the history
  • Loading branch information
huzecong committed Jul 17, 2020
1 parent 61eac63 commit e2b6822
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 7 deletions.
15 changes: 8 additions & 7 deletions pycparser/c_generator.py
Expand Up @@ -59,17 +59,18 @@ def visit_FuncCall(self, n):
return fref + '(' + self.visit(n.args) + ')'

def visit_UnaryOp(self, n):
operand = self._parenthesize_unless_simple(n.expr)
if n.op == 'p++':
return '%s++' % operand
elif n.op == 'p--':
return '%s--' % operand
elif n.op == 'sizeof':
if n.op == 'sizeof':
# Always parenthesize the argument of sizeof since it can be
# a name.
return 'sizeof(%s)' % self.visit(n.expr)
else:
return '%s%s' % (n.op, operand)
operand = self._parenthesize_unless_simple(n.expr)
if n.op == 'p++':
return '%s++' % operand
elif n.op == 'p--':
return '%s--' % operand
else:
return '%s%s' % (n.op, operand)

def visit_BinaryOp(self, n):
lval_str = self._parenthesize_if(n.left,
Expand Down
7 changes: 7 additions & 0 deletions tests/test_c_generator.py
Expand Up @@ -354,6 +354,13 @@ def test_ptr_decl(self):
self.assertEqual(generator.visit(ast.ext[0].type.type.type),
'const int')

def test_nested_sizeof(self):
src = '1'
for _ in range(30):
src = 'sizeof(' + src + ')'
src = 'int x = ' + src + ';'
self._assert_ctoc_correct(src)


class TestCasttoC(unittest.TestCase):
def _find_file(self, name):
Expand Down

0 comments on commit e2b6822

Please sign in to comment.