Skip to content

Commit

Permalink
Correct Parsing of Floating Point Literals, issue #253 (#277)
Browse files Browse the repository at this point in the history
* Corrects the type attribute of a constant node when parsing doubles. This sets the type attribute to either 'float', 'long double' or 'double' depending on if 'f|F', 'l|L' or '' is specified at the end of the constant definition.

* Add tests for previous changes.
  • Loading branch information
robbert-harms authored and eliben committed Aug 31, 2018
1 parent ccd673e commit a915c3d
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
12 changes: 11 additions & 1 deletion pycparser/c_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -1774,8 +1774,18 @@ def p_constant_2(self, p):
""" constant : FLOAT_CONST
| HEX_FLOAT_CONST
"""
if 'x' in p[1].lower():
t = 'float'
else:
if p[1][-1] in ('f', 'F'):
t = 'float'
elif p[1][-1] in ('l', 'L'):
t = 'long double'
else:
t = 'double'

p[0] = c_ast.Constant(
'float', p[1], self._token_coord(p, 1))
t, p[1], self._token_coord(p, 1))

def p_constant_3(self, p):
""" constant : CHAR_CONST
Expand Down
21 changes: 21 additions & 0 deletions tests/test_c_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -1216,6 +1216,27 @@ def test_decl_inits(self):
['Constant', 'int', '5']],
['Constant', 'int', '6']])

d5 = 'float d = 1.0;'
self.assertEqual(self.get_decl_init(d5),
['Constant', 'double', '1.0'])

d51 = 'float ld = 1.0l;'
self.assertEqual(self.get_decl_init(d51),
['Constant', 'long double', '1.0l'])

d52 = 'float ld = 1.0L;'
self.assertEqual(self.get_decl_init(d52),
['Constant', 'long double', '1.0L'])

d53 = 'float ld = 1.0f;'
self.assertEqual(self.get_decl_init(d53),
['Constant', 'float', '1.0f'])

d54 = 'float ld = 1.0F;'
self.assertEqual(self.get_decl_init(d54),
['Constant', 'float', '1.0F'])


def test_decl_named_inits(self):
d1 = 'int a = {.k = 16};'
self.assertEqual(self.get_decl_init(d1),
Expand Down

0 comments on commit a915c3d

Please sign in to comment.