Skip to content

Commit

Permalink
Merge pull request #62 from robotpy/fix-line-directives
Browse files Browse the repository at this point in the history
Fix #line directives
  • Loading branch information
virtuald authored Aug 22, 2023
2 parents dffcbf9 + 4febbe5 commit 1ba625a
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 8 deletions.
15 changes: 7 additions & 8 deletions cxxheaderparser/lexer.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ class LexError(CxxParseError):
else:
Protocol = object

_line_re = re.compile(r'^#line (\d+) "(.*)"')
_line_re = re.compile(r'^\#[\t ]*line (\d+) "(.*)"')
_multicomment_re = re.compile("\n[\\s]+\\*")


Expand Down Expand Up @@ -176,7 +176,6 @@ class PlyLexer:
# Comments
"COMMENT_SINGLELINE",
"COMMENT_MULTILINE",
"LINE_DIRECTIVE",
"PRAGMA_DIRECTIVE",
"INCLUDE_DIRECTIVE",
"PP_DIRECTIVE",
Expand Down Expand Up @@ -438,12 +437,6 @@ def t_NAME(self, t: LexToken) -> LexToken:
t.type = t.value
return t

@TOKEN(r'\#[\t ]*line (\d+) "(.*)"')
def t_LINE_DIRECTIVE(self, t: LexToken) -> None:
m = t.lexmatch
self.filename = m.group(2)
self.line_offset = 1 + self.lex.lineno - int(m.group(1))

@TOKEN(r"\#[\t ]*pragma")
def t_PRAGMA_DIRECTIVE(self, t: LexToken) -> LexToken:
return t
Expand All @@ -454,6 +447,12 @@ def t_INCLUDE_DIRECTIVE(self, t: LexToken) -> LexToken:

@TOKEN(r"\#(.*)")
def t_PP_DIRECTIVE(self, t: LexToken):
# handle line macros
m = _line_re.match(t.value)
if m:
self.filename = m.group(2)
self.line_offset = 1 + self.lex.lineno - int(m.group(1))
return None
# ignore C++23 warning directive
if t.value.startswith("#warning"):
return
Expand Down
16 changes: 16 additions & 0 deletions tests/test_misc.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
# Note: testcases generated via `python -m cxxheaderparser.gentest`

from cxxheaderparser.errors import CxxParseError
from cxxheaderparser.types import (
BaseClass,
ClassDecl,
Expand All @@ -22,6 +23,8 @@
ParsedData,
)

import pytest

#
# minimal preprocessor support
#
Expand Down Expand Up @@ -93,6 +96,19 @@ def test_pragma_more() -> None:
)


def test_line_and_define() -> None:
content = """
// this should work + change line number of error
#line 40 "filename.h"
// this should fail
#define 1
"""
with pytest.raises(CxxParseError) as e:
parse_string(content, cleandoc=True)

assert "filename.h:41" in str(e.value)


#
# extern "C"
#
Expand Down

0 comments on commit 1ba625a

Please sign in to comment.