Skip to content
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
23 changes: 23 additions & 0 deletions tests/test_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,29 @@ def test_parser_should_raise_an_error_for_empty_tables() -> None:
assert e.value.col == 1


@pytest.mark.parametrize("line_ending", ["\n", "\r\n"])
def test_parser_reports_the_same_position_regardless_of_line_ending(
line_ending: str,
) -> None:
content = line_ending.join(["a = 1", "b = 2", "c = @", "d = 4"]) + line_ending

with pytest.raises(UnexpectedCharError) as e:
Parser(content).parse()

assert e.value.line == 3
assert e.value.col == 4


def test_parser_reports_the_right_position_for_mixed_line_endings() -> None:
content = "a = 1\r\nb = 2\nc = @\r\n"

with pytest.raises(UnexpectedCharError) as e:
Parser(content).parse()

assert e.value.line == 3
assert e.value.col == 4


def test_parser_should_raise_an_error_if_equal_not_found() -> None:
content = """[foo]
a {c = 1, d = 2}
Expand Down
13 changes: 9 additions & 4 deletions tomlkit/source.py
Original file line number Diff line number Diff line change
Expand Up @@ -230,11 +230,16 @@ def parse_error(
return exception(line, col, *args, **kwargs)

def _to_linecol(self) -> tuple[int, int]:
# `keepends` keeps each line's own terminator inside its length: a "\r\n"
# break occupies two characters, and assuming a single one made the
# running offset fall one behind per CRLF line, so an error later in the
# document was reported on the wrong line and column.
lines = self.splitlines(keepends=True)
cur = 0
for i, line in enumerate(self.splitlines()):
if cur + len(line) + 1 > self.idx:
for i, line in enumerate(lines):
if cur + len(line) > self.idx:
return (i + 1, self.idx - cur)

cur += len(line) + 1
cur += len(line)

return len(self.splitlines()), 0
return len(lines), 0
Loading