Skip to content

Commit f3fedb5

Browse files
committed
Add check for reserved fields names
1 parent 5df786d commit f3fedb5

3 files changed

Lines changed: 14 additions & 6 deletions

File tree

cstruct/c_parser.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -316,15 +316,17 @@ def parse_struct(
316316
field_type = parse_type(tokens, __cls__, __byte_order__, offset)
317317
vname = tokens.pop()
318318
if vname in fields_types:
319-
raise ParserError("Duplicate member '{}'".format(vname))
319+
raise ParserError(f"Duplicate member '{vname}'")
320+
if vname in dir(__cls__):
321+
raise ParserError(f"Invalid reserved member name '{vname}'")
320322
# anonymous nested union
321323
if vname == ';' and field_type.ref is not None and (__is_union__ or field_type.ref.__is_union__):
322324
# add the anonymous struct fields to the parent
323325
for nested_field_name, nested_field_type in field_type.ref.__fields_types__.items():
324326
if nested_field_name in fields_types:
325-
raise ParserError("Duplicate member '{}'".format(nested_field_name))
327+
raise ParserError(f"Duplicate member '{nested_field_name}'")
326328
fields_types[nested_field_name] = nested_field_type
327-
vname = "__anonymous{}".format(anonymous)
329+
vname = f"__anonymous{anonymous}"
328330
anonymous += 1
329331
tokens.push(';')
330332
fields_types[vname] = field_type
@@ -336,7 +338,7 @@ def parse_struct(
336338
offset = field_type.offset + field_type.vsize
337339
t = tokens.pop()
338340
if t != ';':
339-
raise ParserError("; expected but {} found".format(t))
341+
raise ParserError(f"; expected but {t} found")
340342

341343
if __is_union__: # C union
342344
# Calculate the sizeof union as size of its largest element

tests/test_cstruct.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -262,4 +262,7 @@ def test_null_compare():
262262
def test_invalid_inline():
263263
with pytest.raises(ParserError):
264264
cstruct.MemCStruct.parse('struct { unsigned char head; unsigned char head; }', __byte_order__=cstruct.LITTLE_ENDIAN)
265-
assert False
265+
266+
def test_invalid_inline_reserved():
267+
with pytest.raises(ParserError):
268+
cstruct.CStruct.parse('struct { int size; }')

tests/test_memcstruct.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -256,4 +256,7 @@ def test_null_compare():
256256
def test_invalid_inline():
257257
with pytest.raises(ParserError):
258258
cstruct.MemCStruct.parse('struct { unsigned char head; unsigned char head; }', __byte_order__=cstruct.LITTLE_ENDIAN)
259-
assert False
259+
260+
def test_invalid_inline_reserved():
261+
with pytest.raises(ParserError):
262+
cstruct.MemCStruct.parse('struct { int size; }')

0 commit comments

Comments
 (0)