Skip to content

Commit 00804e9

Browse files
committed
Give JSONPathSyntaxError line and column numbers.
1 parent da18ea7 commit 00804e9

6 files changed

Lines changed: 69 additions & 14 deletions

File tree

‎jsonpath/env.py‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,10 @@ def compile(self, path: str) -> Union[JSONPath, CompoundJSONPath]:
6868
stream.next_token()
6969
_path.intersection(JSONPath(selectors=self.parser.parse(stream)))
7070
else:
71-
raise JSONPathSyntaxError(f"unexpected {stream.current}")
71+
raise JSONPathSyntaxError(
72+
f"unexpected token {stream.current.value!r}",
73+
token=stream.current,
74+
)
7275

7376
return _path
7477

‎jsonpath/exceptions.py‎

Lines changed: 27 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,34 @@
11
# TODO: Base exception with token/index/lineno handling
2+
from __future__ import annotations
3+
from typing import TYPE_CHECKING
24

5+
if TYPE_CHECKING:
6+
from .token import Token
37

4-
class JSONPathSyntaxError(Exception):
5-
""""""
8+
9+
class JSONPathError(Exception):
10+
"""Base exception for all JSONPath syntax and type errors."""
11+
12+
13+
class JSONPathSyntaxError(JSONPathError):
14+
"""An exception raised when parsing a JSONPath string."""
15+
16+
def __init__(self, *args: object, token: Token) -> None:
17+
super().__init__(*args)
18+
self.token = token
19+
20+
def __str__(self) -> str:
21+
msg = super().__str__()
22+
line, column = self.token.position()
23+
# TODO: give context from source path string
24+
return f"{msg}, line {line}, column {column}"
625

726

827
class JSONPathTypeError(Exception):
928
""""""
29+
30+
31+
def _truncate_message(value: str, num: int, end: str = "...") -> str:
32+
if len(value) < num:
33+
return value
34+
return f"{value[:num-len(end)]}{end}"

‎jsonpath/lex.py‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -278,9 +278,13 @@ def tokenize(self, path: str) -> Iterator[Token]:
278278
elif kind == TOKEN_SKIP:
279279
continue
280280
elif kind == TOKEN_ILLEGAL:
281-
# TODO: line and column number
282281
raise JSONPathSyntaxError(
283-
f"unexpected token {kind!r}: {match.group()!r}"
282+
f"unexpected token {match.group()!r}",
283+
token=_token(
284+
TOKEN_ILLEGAL,
285+
value=match.group(),
286+
index=match.start(),
287+
),
284288
)
285289
else:
286290
yield _token(

‎jsonpath/parse.py‎

Lines changed: 17 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -190,7 +190,8 @@ def parse(self, stream: TokenStream) -> Iterable[JSONPathSelector]:
190190

191191
if stream.current.kind not in (TOKEN_EOF, TOKEN_INTERSECTION, TOKEN_UNION):
192192
raise JSONPathSyntaxError(
193-
f"unexpected token {stream.current!r}",
193+
f"unexpected token {stream.current.value!r}",
194+
token=stream.current,
194195
)
195196

196197
def parse_path(
@@ -291,7 +292,10 @@ def parse_selector_list(self, stream: TokenStream) -> ListSelector:
291292
elif stream.current.kind == TOKEN_SLICE_START:
292293
list_items.append(self.parse_slice(stream))
293294
elif stream.current.kind == TOKEN_EOF:
294-
raise JSONPathSyntaxError("unexpected end of selector list")
295+
raise JSONPathSyntaxError(
296+
"unexpected end of selector list",
297+
token=stream.current,
298+
)
295299

296300
if stream.peek.kind != TOKEN_LIST_END:
297301
stream.expect_peek(TOKEN_COMMA)
@@ -306,7 +310,7 @@ def parse_filter(self, stream: TokenStream) -> Filter:
306310
expr = BooleanExpression(self.parse_filter_selector(stream))
307311

308312
if stream.peek.kind == TOKEN_RPAREN:
309-
raise JSONPathSyntaxError("unmatched ')'")
313+
raise JSONPathSyntaxError("unbalanced ')'", token=stream.current)
310314

311315
stream.next_token()
312316
stream.expect(TOKEN_FILTER_END)
@@ -358,7 +362,9 @@ def parse_grouped_expression(self, stream: TokenStream) -> FilterExpression:
358362

359363
while stream.current.kind != TOKEN_RPAREN:
360364
if stream.current.kind in (TOKEN_EOF, TOKEN_FILTER_END):
361-
raise JSONPathSyntaxError("unbalanced parentheses")
365+
raise JSONPathSyntaxError(
366+
"unbalanced parentheses", token=stream.current
367+
)
362368
expr = self.parse_infix_expression(stream, expr)
363369

364370
stream.expect(TOKEN_RPAREN)
@@ -389,8 +395,10 @@ def parse_list_literal(self, stream: TokenStream) -> FilterExpression:
389395
try:
390396
list_items.append(self.list_item_map[stream.current.kind](stream))
391397
except KeyError as err:
392-
# TODO: line number etc.
393-
raise JSONPathSyntaxError(f"unexpected {stream.current}") from err
398+
raise JSONPathSyntaxError(
399+
f"unexpected {stream.current.value!r}",
400+
token=stream.current,
401+
) from err
394402

395403
if stream.peek.kind != TOKEN_LIST_END:
396404
stream.expect_peek(TOKEN_COMMA)
@@ -410,7 +418,9 @@ def parse_filter_selector(
410418
msg = "end of expression"
411419
else:
412420
msg = repr(stream.current.value)
413-
raise JSONPathSyntaxError(f"unexpected {msg}") from err
421+
raise JSONPathSyntaxError(
422+
f"unexpected {msg}", token=stream.current
423+
) from err
414424

415425
while True:
416426
peek_kind = stream.peek.kind

‎jsonpath/stream.py‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -79,9 +79,15 @@ def close(self) -> None:
7979
def expect(self, typ: str) -> None:
8080
""""""
8181
if self.current.kind != typ:
82-
raise JSONPathSyntaxError(f"expected {typ!r}, found {self.current.kind!r}")
82+
raise JSONPathSyntaxError(
83+
f"expected {typ!r}, found {self.current.kind!r}",
84+
token=self.current,
85+
)
8386

8487
def expect_peek(self, typ: str) -> None:
8588
""""""
8689
if self.peek.kind != typ:
87-
raise JSONPathSyntaxError(f"expected {typ!r}, found {self.current.kind!r}")
90+
raise JSONPathSyntaxError(
91+
f"expected {typ!r}, found {self.current.kind!r}",
92+
token=self.peek,
93+
)

‎jsonpath/token.py‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
""""""
22
import sys
3+
from typing import Tuple
34

45
# Utility tokens
56
TOKEN_EOF = sys.intern("EOF")
@@ -102,3 +103,9 @@ def __eq__(self, other: object) -> bool:
102103
and self.index == other.index
103104
and self.path == other.path
104105
)
106+
107+
def position(self) -> Tuple[int, int]:
108+
"""Return the line and column number for the start of this token."""
109+
line_number = self.value.count("\n", 0, self.index) + 1
110+
column_number = self.index - self.value.rfind("\n", 0, self.index)
111+
return (line_number, column_number)

0 commit comments

Comments
 (0)