Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Preserve newlines when removing comments #43

Merged
merged 2 commits into from
Aug 4, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions dissect/cstruct/parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -299,11 +299,11 @@ def _remove_comments(string: str) -> str:
# second group captures comments (//single-line or /* multi-line */)
regex = re.compile(pattern, re.MULTILINE | re.DOTALL)

def _replacer(match):
def _replacer(match: re.Match) -> str:
# if the 2nd group (capturing comments) is not None,
# it means we have captured a non-quoted (real) comment string.
if match.group(2) is not None:
return "" # so we will return empty to remove the comment
if comment := match.group(2):
return "\n" * comment.count("\n") # so we will return empty to remove the comment
else: # otherwise, we will return the 1st group
return match.group(1) # captured quoted-string

Expand All @@ -314,7 +314,7 @@ def _lineno(tok: Token) -> int:
"""Quick and dirty line number calculator"""

match = tok.match
return match.string.count("\n", 0, match.start())
return match.string.count("\n", 0, match.start()) + 1

def _config_flag(self, tokens: TokenConsumer) -> None:
flag_token = tokens.consume()
Expand Down
26 changes: 26 additions & 0 deletions tests/test_parser.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
from unittest.mock import Mock

from dissect.cstruct.parser import TokenParser


def test_preserve_comment_newlines():
Poeloe marked this conversation as resolved.
Show resolved Hide resolved
cdef = """
// normal comment
#define normal_anchor
/*
* Multi
* line
* comment
*/
#define multi_anchor
"""
data = TokenParser._remove_comments(cdef)
print(repr(data))

mock_token = Mock()
mock_token.match.string = data
mock_token.match.start.return_value = data.index("#define normal_anchor")
assert TokenParser._lineno(mock_token) == 3

mock_token.match.start.return_value = data.index("#define multi_anchor")
assert TokenParser._lineno(mock_token) == 9