jsonpath-mojo 0.2.5__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- jsonpath_mojo/__init__.py +32 -0
- jsonpath_mojo/_native.py +274 -0
- jsonpath_mojo/_reference.py +750 -0
- jsonpath_mojo/core.py +214 -0
- jsonpath_mojo-0.2.5.dist-info/METADATA +112 -0
- jsonpath_mojo-0.2.5.dist-info/RECORD +7 -0
- jsonpath_mojo-0.2.5.dist-info/WHEEL +4 -0
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
"""jsonpath-mojo: a fast JSONPath query engine, API-compatible with the
|
|
2
|
+
`jsonpath_ng.ext` dialect of the jsonpath-ng package.
|
|
3
|
+
|
|
4
|
+
from jsonpath_mojo import find
|
|
5
|
+
|
|
6
|
+
matches = find("$.store.book[?(@.price < 10)].title", data)
|
|
7
|
+
# -> [(value, path), ...] exactly like
|
|
8
|
+
# [(m.value, str(m.full_path)) for m in jsonpath_ng.ext.parse(q).find(data)]
|
|
9
|
+
|
|
10
|
+
Evaluation runs on the native Mojo kernel when its shared library is
|
|
11
|
+
available (macOS arm64 / Linux x86_64 wheels) and transparently falls back to
|
|
12
|
+
the vendored pure-Python engine everywhere else. Both backends return
|
|
13
|
+
identical results; the differential test suite asserts agreement with
|
|
14
|
+
jsonpath_ng on both paths.
|
|
15
|
+
|
|
16
|
+
Set JSONPATH_MOJO_DISABLE_NATIVE=1 to force the pure-Python engine; inspect
|
|
17
|
+
the active backend with jsonpath_mojo.backend_info().
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from jsonpath_mojo._native import backend_info, native_available
|
|
21
|
+
from jsonpath_mojo.core import JsonPathError, find, find_parsed, parse
|
|
22
|
+
|
|
23
|
+
__version__ = "0.2.5" # x-release-please-version
|
|
24
|
+
__all__ = [
|
|
25
|
+
"JsonPathError",
|
|
26
|
+
"backend_info",
|
|
27
|
+
"find",
|
|
28
|
+
"find_parsed",
|
|
29
|
+
"native_available",
|
|
30
|
+
"parse",
|
|
31
|
+
"__version__",
|
|
32
|
+
]
|
jsonpath_mojo/_native.py
ADDED
|
@@ -0,0 +1,274 @@
|
|
|
1
|
+
"""ctypes loader for the jsonpathmojo native kernel, with an ABI handshake.
|
|
2
|
+
|
|
3
|
+
Resolution order:
|
|
4
|
+
|
|
5
|
+
1. ``$JSONPATH_MOJO_NATIVE_LIB`` (explicit path override, for development)
|
|
6
|
+
2. the shared library bundled in this wheel under ``jsonpath_mojo/_native/``
|
|
7
|
+
3. the repository development build output ``kernels/jsonpath/build/``
|
|
8
|
+
|
|
9
|
+
If the library cannot be found, fails to load, or reports an ABI version this
|
|
10
|
+
package does not understand, :class:`NativeUnavailable` is raised and the
|
|
11
|
+
caller falls back to the vendored pure-Python implementation. Set
|
|
12
|
+
``JSONPATH_MOJO_DISABLE_NATIVE=1`` to force that fallback (used by the
|
|
13
|
+
differential test suite).
|
|
14
|
+
|
|
15
|
+
Stable C ABI (v1)::
|
|
16
|
+
|
|
17
|
+
int32_t jsonpathmojo_abi_version(void)
|
|
18
|
+
void* jsonpathmojo_find(const uint8_t* expr, int64_t expr_len,
|
|
19
|
+
const uint8_t* json, int64_t json_len,
|
|
20
|
+
int64_t* status_out /* [0]=status [1]=aux */)
|
|
21
|
+
int64_t jsonpathmojo_count(void* handle, int32_t which)
|
|
22
|
+
void jsonpathmojo_copy(void* handle, uint8_t* kinds, int64_t* vals,
|
|
23
|
+
int64_t* path_off, int64_t* str_off,
|
|
24
|
+
uint8_t* str_buf)
|
|
25
|
+
void jsonpathmojo_destroy(void* handle)
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
from __future__ import annotations
|
|
29
|
+
|
|
30
|
+
import ctypes
|
|
31
|
+
import os
|
|
32
|
+
import sys
|
|
33
|
+
import threading
|
|
34
|
+
|
|
35
|
+
# Must equal ABI_VERSION in kernels/jsonpath/src/jsonpathmojo.mojo. A mismatch
|
|
36
|
+
# means the installed wheel and the resolved shared library disagree; fall back.
|
|
37
|
+
ABI_VERSION = 1
|
|
38
|
+
|
|
39
|
+
_ENV_LIB = "JSONPATH_MOJO_NATIVE_LIB"
|
|
40
|
+
_ENV_DISABLE = "JSONPATH_MOJO_DISABLE_NATIVE"
|
|
41
|
+
|
|
42
|
+
# find() status codes, mirrored from the kernel.
|
|
43
|
+
ST_OK = 0
|
|
44
|
+
ST_PARSE = 1
|
|
45
|
+
ST_TE_INT = 2 # TypeError from int() coercion; aux = value tag
|
|
46
|
+
ST_TE_ORD = 3 # TypeError from ordering comparison; aux = op*64 + ltag*8 + rtag
|
|
47
|
+
ST_INDEXERROR = 4 # aux = 0 list, 1 string
|
|
48
|
+
ST_KEYERROR = 5 # aux = index
|
|
49
|
+
ST_VE_SLICE = 6
|
|
50
|
+
ST_NOTIMPL = 7
|
|
51
|
+
ST_FALLBACK = 8 # out of the native domain; the wrapper must use the fallback
|
|
52
|
+
ST_TE_LEN = 9 # "object of type 'X' has no len()"; aux = tag
|
|
53
|
+
|
|
54
|
+
# Output step kinds, mirrored from the kernel.
|
|
55
|
+
OUT_FIELD = 0
|
|
56
|
+
OUT_INDEX = 1
|
|
57
|
+
OUT_DICTPOS = 2
|
|
58
|
+
OUT_SELFIDX = 3
|
|
59
|
+
|
|
60
|
+
# Value tags for error message composition (mirror the kernel's TAG_*).
|
|
61
|
+
_TAG_NAMES = {
|
|
62
|
+
0: "NoneType",
|
|
63
|
+
1: "bool",
|
|
64
|
+
2: "bool",
|
|
65
|
+
3: "int",
|
|
66
|
+
4: "float",
|
|
67
|
+
5: "str",
|
|
68
|
+
6: "list",
|
|
69
|
+
7: "dict",
|
|
70
|
+
}
|
|
71
|
+
_OP_CHARS = {0: "==", 1: "!=", 2: "<", 3: "<=", 4: ">", 5: ">="}
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
class NativeUnavailable(RuntimeError): # noqa: N818
|
|
75
|
+
"""The native jsonpathmojo kernel could not be found, loaded, or verified."""
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _lib_basename() -> str:
|
|
79
|
+
if sys.platform == "darwin":
|
|
80
|
+
return "libjsonpathmojo.dylib"
|
|
81
|
+
if sys.platform.startswith("linux"):
|
|
82
|
+
return "libjsonpathmojo.so"
|
|
83
|
+
if sys.platform.startswith("win"):
|
|
84
|
+
return "jsonpathmojo.dll" # no Mojo toolchain builds this today
|
|
85
|
+
return "libjsonpathmojo.so"
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _candidate_paths() -> list[tuple[str, str]]:
|
|
89
|
+
"""(source_label, path) candidates, in resolver order."""
|
|
90
|
+
out: list[tuple[str, str]] = []
|
|
91
|
+
override = os.environ.get(_ENV_LIB)
|
|
92
|
+
if override:
|
|
93
|
+
out.append((f"env {_ENV_LIB}", override))
|
|
94
|
+
here = os.path.dirname(__file__)
|
|
95
|
+
out.append(("bundled in wheel", os.path.join(here, "_native", _lib_basename())))
|
|
96
|
+
out.append(
|
|
97
|
+
(
|
|
98
|
+
"repo-dev build output",
|
|
99
|
+
os.path.abspath(
|
|
100
|
+
os.path.join(here, "..", "..", "..", "kernels", "jsonpath", "build", _lib_basename())
|
|
101
|
+
),
|
|
102
|
+
)
|
|
103
|
+
)
|
|
104
|
+
return out
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _bind_abi(lib: ctypes.CDLL) -> None:
|
|
108
|
+
u8p = ctypes.POINTER(ctypes.c_uint8)
|
|
109
|
+
i64p = ctypes.POINTER(ctypes.c_int64)
|
|
110
|
+
lib.jsonpathmojo_abi_version.argtypes = []
|
|
111
|
+
lib.jsonpathmojo_abi_version.restype = ctypes.c_int32
|
|
112
|
+
lib.jsonpathmojo_find.argtypes = [u8p, ctypes.c_int64, u8p, ctypes.c_int64, i64p]
|
|
113
|
+
lib.jsonpathmojo_find.restype = ctypes.c_void_p
|
|
114
|
+
lib.jsonpathmojo_count.argtypes = [ctypes.c_void_p, ctypes.c_int32]
|
|
115
|
+
lib.jsonpathmojo_count.restype = ctypes.c_int64
|
|
116
|
+
lib.jsonpathmojo_copy.argtypes = [ctypes.c_void_p, u8p, i64p, i64p, i64p, u8p]
|
|
117
|
+
lib.jsonpathmojo_copy.restype = None
|
|
118
|
+
lib.jsonpathmojo_destroy.argtypes = [ctypes.c_void_p]
|
|
119
|
+
lib.jsonpathmojo_destroy.restype = None
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
_LOCK = threading.Lock()
|
|
123
|
+
_LIB: ctypes.CDLL | None = None
|
|
124
|
+
_LIB_SOURCE: str | None = None
|
|
125
|
+
_LOAD_ERROR: str | None = None
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _load() -> ctypes.CDLL:
|
|
129
|
+
"""Resolve, dlopen, and ABI-handshake the native kernel. Never caches failure."""
|
|
130
|
+
global _LIB, _LIB_SOURCE, _LOAD_ERROR
|
|
131
|
+
if os.environ.get(_ENV_DISABLE) == "1":
|
|
132
|
+
raise NativeUnavailable(f"native kernel disabled by {_ENV_DISABLE}=1")
|
|
133
|
+
if _LIB is not None:
|
|
134
|
+
return _LIB
|
|
135
|
+
with _LOCK:
|
|
136
|
+
if _LIB is not None:
|
|
137
|
+
return _LIB
|
|
138
|
+
errors: list[str] = []
|
|
139
|
+
for label, path in _candidate_paths():
|
|
140
|
+
try:
|
|
141
|
+
if not path or not os.path.exists(path):
|
|
142
|
+
continue
|
|
143
|
+
try:
|
|
144
|
+
lib = ctypes.CDLL(path)
|
|
145
|
+
except OSError as exc:
|
|
146
|
+
errors.append(f"{label} ({path}): {exc}")
|
|
147
|
+
continue
|
|
148
|
+
try:
|
|
149
|
+
_bind_abi(lib)
|
|
150
|
+
abi = int(lib.jsonpathmojo_abi_version())
|
|
151
|
+
except Exception as exc: # missing/renamed symbol = wrong lib
|
|
152
|
+
errors.append(f"{label} ({path}): ABI not recognized: {exc}")
|
|
153
|
+
continue
|
|
154
|
+
if abi != ABI_VERSION:
|
|
155
|
+
errors.append(
|
|
156
|
+
f"{label} ({path}): native ABI v{abi} != wrapper ABI v{ABI_VERSION}"
|
|
157
|
+
)
|
|
158
|
+
continue
|
|
159
|
+
_LIB, _LIB_SOURCE = lib, f"{label} ({path})"
|
|
160
|
+
_LOAD_ERROR = None
|
|
161
|
+
return lib
|
|
162
|
+
except OSError as exc:
|
|
163
|
+
errors.append(f"{label}: {exc}")
|
|
164
|
+
_LOAD_ERROR = "; ".join(errors) or "no native kernel found on any resolver path"
|
|
165
|
+
raise NativeUnavailable(_LOAD_ERROR)
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def native_available() -> bool:
|
|
169
|
+
"""True if the native kernel can evaluate right now. Never raises."""
|
|
170
|
+
try:
|
|
171
|
+
_load()
|
|
172
|
+
return True
|
|
173
|
+
except NativeUnavailable:
|
|
174
|
+
return False
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def backend_info() -> dict:
|
|
178
|
+
"""Diagnostics for the active backend. Never raises."""
|
|
179
|
+
info = {
|
|
180
|
+
"native_available": False,
|
|
181
|
+
"native_source": None,
|
|
182
|
+
"abi_version_expected": ABI_VERSION,
|
|
183
|
+
"abi_version_native": None,
|
|
184
|
+
"disabled_by_env": os.environ.get(_ENV_DISABLE) == "1",
|
|
185
|
+
"platform": sys.platform,
|
|
186
|
+
"error": None,
|
|
187
|
+
}
|
|
188
|
+
try:
|
|
189
|
+
lib = _load()
|
|
190
|
+
except NativeUnavailable as exc:
|
|
191
|
+
info["error"] = str(exc)
|
|
192
|
+
return info
|
|
193
|
+
info["native_available"] = True
|
|
194
|
+
info["native_source"] = _LIB_SOURCE
|
|
195
|
+
info["abi_version_native"] = int(lib.jsonpathmojo_abi_version())
|
|
196
|
+
return info
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def find_native(
|
|
200
|
+
expr_bytes: bytes, json_bytes: bytes
|
|
201
|
+
) -> tuple[int, int, list[int], list[int], list[int], list[str]]:
|
|
202
|
+
"""Run one native query.
|
|
203
|
+
|
|
204
|
+
Returns ``(status, aux, kinds, vals, path_off, strings)``; on status != 0
|
|
205
|
+
the last four are empty. The caller interprets status (raising the
|
|
206
|
+
matching Python exception or falling back).
|
|
207
|
+
"""
|
|
208
|
+
lib = _load() # raises NativeUnavailable
|
|
209
|
+
u8p = ctypes.POINTER(ctypes.c_uint8)
|
|
210
|
+
i64p = ctypes.POINTER(ctypes.c_int64)
|
|
211
|
+
|
|
212
|
+
def _u8buf(data: bytes) -> ctypes.Array:
|
|
213
|
+
if not data:
|
|
214
|
+
return (ctypes.c_uint8 * 1)()
|
|
215
|
+
return (ctypes.c_uint8 * len(data)).from_buffer_copy(data)
|
|
216
|
+
|
|
217
|
+
expr_buf = _u8buf(expr_bytes)
|
|
218
|
+
json_buf = _u8buf(json_bytes)
|
|
219
|
+
status_out = (ctypes.c_int64 * 2)()
|
|
220
|
+
handle = lib.jsonpathmojo_find(
|
|
221
|
+
expr_buf, len(expr_bytes), json_buf, len(json_bytes), status_out
|
|
222
|
+
)
|
|
223
|
+
if not handle:
|
|
224
|
+
raise NativeUnavailable("native kernel returned no result handle")
|
|
225
|
+
try:
|
|
226
|
+
status, aux = int(status_out[0]), int(status_out[1])
|
|
227
|
+
if status != ST_OK:
|
|
228
|
+
return status, aux, [], [], [], []
|
|
229
|
+
n_matches = lib.jsonpathmojo_count(handle, 0)
|
|
230
|
+
n_steps = lib.jsonpathmojo_count(handle, 1)
|
|
231
|
+
n_strings = lib.jsonpathmojo_count(handle, 2)
|
|
232
|
+
n_bytes = lib.jsonpathmojo_count(handle, 3)
|
|
233
|
+
kinds = (ctypes.c_uint8 * max(n_steps, 1))()
|
|
234
|
+
vals = (ctypes.c_int64 * max(n_steps, 1))()
|
|
235
|
+
path_off = (ctypes.c_int64 * (n_matches + 1))()
|
|
236
|
+
str_off = (ctypes.c_int64 * (n_strings + 1))()
|
|
237
|
+
str_buf = (ctypes.c_uint8 * max(n_bytes, 1))()
|
|
238
|
+
lib.jsonpathmojo_copy(handle, kinds, vals, path_off, str_off, str_buf)
|
|
239
|
+
raw = bytes(str_buf[:n_bytes])
|
|
240
|
+
strings = [
|
|
241
|
+
raw[str_off[i] : str_off[i + 1]].decode("utf-8", "surrogatepass")
|
|
242
|
+
for i in range(n_strings)
|
|
243
|
+
]
|
|
244
|
+
return (
|
|
245
|
+
status,
|
|
246
|
+
aux,
|
|
247
|
+
list(kinds[:n_steps]),
|
|
248
|
+
list(vals[:n_steps]),
|
|
249
|
+
list(path_off[: n_matches + 1]),
|
|
250
|
+
strings,
|
|
251
|
+
)
|
|
252
|
+
finally:
|
|
253
|
+
lib.jsonpathmojo_destroy(handle)
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def ordering_type_error(aux: int) -> TypeError:
|
|
257
|
+
"""Rebuild the CPython 3.12 message for a mixed-type ordering comparison."""
|
|
258
|
+
op = _OP_CHARS[(aux // 64) % 8]
|
|
259
|
+
lname = _TAG_NAMES[(aux // 8) % 8]
|
|
260
|
+
rname = _TAG_NAMES[aux % 8]
|
|
261
|
+
return TypeError(f"'{op}' not supported between instances of '{lname}' and '{rname}'")
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
def int_coercion_type_error(aux: int) -> TypeError:
|
|
265
|
+
name = _TAG_NAMES[aux % 8]
|
|
266
|
+
return TypeError(
|
|
267
|
+
"int() argument must be a string, a bytes-like object or a real number, "
|
|
268
|
+
f"not '{name}'"
|
|
269
|
+
)
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def len_type_error(aux: int) -> TypeError:
|
|
273
|
+
name = _TAG_NAMES[aux % 8]
|
|
274
|
+
return TypeError(f"object of type '{name}' has no len()")
|
|
@@ -0,0 +1,750 @@
|
|
|
1
|
+
"""Vendored pure-Python JSONPath engine (h2non/jsonpath-ng ext-dialect semantics).
|
|
2
|
+
|
|
3
|
+
This is a clean-room reimplementation of the observable behavior of
|
|
4
|
+
``jsonpath_ng.ext.parse(expr).find(data)`` (PyPI jsonpath_ng 1.7.0), written
|
|
5
|
+
from a black-box semantics contract (see the package README and the
|
|
6
|
+
differential test suite). It serves two roles:
|
|
7
|
+
|
|
8
|
+
* the transparent fallback on platforms without the native Mojo kernel, and
|
|
9
|
+
* the in-repo semantics reference for the native kernel.
|
|
10
|
+
|
|
11
|
+
Supported grammar:
|
|
12
|
+
|
|
13
|
+
child steps $.a $['a'] $.a.b (dot-number children: $.a.0)
|
|
14
|
+
field unions $['a', 'b'] (expression order, duplicates repeated)
|
|
15
|
+
wildcards $.* $[*]
|
|
16
|
+
recursive descent $..a $..* $..[0] $..['a'] (DFS pre-order)
|
|
17
|
+
index $.a[0] $.a[-1]
|
|
18
|
+
slices $.a[1:5:2] $.a[::-1] (Python slice semantics)
|
|
19
|
+
filters $.a[?(@.x > 2)] with ==, !=, <, <=, >, >=, `&`
|
|
20
|
+
conjunctions, `@` paths, arith (+, -, *), and bare
|
|
21
|
+
existence tests `?(@.x)`
|
|
22
|
+
|
|
23
|
+
Find results are ``(value, path)`` pairs in the oracle's order, with paths
|
|
24
|
+
rendered exactly like the oracle's ``str(DatumInContext.full_path)``.
|
|
25
|
+
|
|
26
|
+
The observable error contract (raised for invalid queries or hostile data)
|
|
27
|
+
mirrors the oracle: ``JsonPathError`` for parse/lex errors, and the same
|
|
28
|
+
builtin ``TypeError`` / ``IndexError`` / ``KeyError`` / ``ValueError`` /
|
|
29
|
+
``NotImplementedError`` the oracle raises at evaluation time, with matching
|
|
30
|
+
messages (CPython produces most of them for free).
|
|
31
|
+
"""
|
|
32
|
+
|
|
33
|
+
from __future__ import annotations
|
|
34
|
+
|
|
35
|
+
__all__ = ["JsonPathError", "parse", "find", "render_path"]
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class JsonPathError(Exception):
|
|
39
|
+
"""Invalid JSONPath expression (parse or lex error)."""
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
# ---------------------------------------------------------------------------
|
|
43
|
+
# Parser
|
|
44
|
+
# ---------------------------------------------------------------------------
|
|
45
|
+
|
|
46
|
+
_WS = " \t\n\r"
|
|
47
|
+
_QUOTE_NEEDED_CHARS = ".,:[]()|&$*~"
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class _Parser:
|
|
51
|
+
def __init__(self, text: str):
|
|
52
|
+
self.text = text
|
|
53
|
+
self.pos = 0
|
|
54
|
+
|
|
55
|
+
def error(self) -> JsonPathError:
|
|
56
|
+
return JsonPathError(f"Parse error at 1:{self.pos} in {self.text!r}")
|
|
57
|
+
|
|
58
|
+
def peek(self, k: int = 0) -> str:
|
|
59
|
+
i = self.pos + k
|
|
60
|
+
return self.text[i] if i < len(self.text) else ""
|
|
61
|
+
|
|
62
|
+
def ws(self) -> None:
|
|
63
|
+
while self.pos < len(self.text) and self.text[self.pos] in _WS:
|
|
64
|
+
self.pos += 1
|
|
65
|
+
|
|
66
|
+
def quoted(self) -> str:
|
|
67
|
+
quote = self.text[self.pos]
|
|
68
|
+
self.pos += 1
|
|
69
|
+
out = []
|
|
70
|
+
while True:
|
|
71
|
+
if self.pos >= len(self.text):
|
|
72
|
+
raise self.error()
|
|
73
|
+
c = self.text[self.pos]
|
|
74
|
+
if c == quote:
|
|
75
|
+
self.pos += 1
|
|
76
|
+
return "".join(out)
|
|
77
|
+
if c == "\\":
|
|
78
|
+
# a backslash escapes the next character literally
|
|
79
|
+
self.pos += 1
|
|
80
|
+
if self.pos >= len(self.text):
|
|
81
|
+
raise self.error()
|
|
82
|
+
out.append(self.text[self.pos])
|
|
83
|
+
self.pos += 1
|
|
84
|
+
else:
|
|
85
|
+
out.append(c)
|
|
86
|
+
self.pos += 1
|
|
87
|
+
|
|
88
|
+
def ident(self) -> str:
|
|
89
|
+
start = self.pos
|
|
90
|
+
while self.pos < len(self.text) and (
|
|
91
|
+
self.text[self.pos].isascii()
|
|
92
|
+
and (self.text[self.pos].isalnum() or self.text[self.pos] == "_")
|
|
93
|
+
):
|
|
94
|
+
self.pos += 1
|
|
95
|
+
return self.text[start : self.pos]
|
|
96
|
+
|
|
97
|
+
def uint(self) -> int:
|
|
98
|
+
start = self.pos
|
|
99
|
+
while self.pos < len(self.text) and self.text[self.pos].isdigit():
|
|
100
|
+
self.pos += 1
|
|
101
|
+
if self.pos == start:
|
|
102
|
+
raise self.error()
|
|
103
|
+
return int(self.text[start : self.pos])
|
|
104
|
+
|
|
105
|
+
def number_token(self):
|
|
106
|
+
"""INT or FLOAT literal (no exponents, digits on both sides of '.')."""
|
|
107
|
+
neg = self.peek() == "-"
|
|
108
|
+
if neg:
|
|
109
|
+
self.pos += 1
|
|
110
|
+
if not self.peek().isdigit():
|
|
111
|
+
raise self.error()
|
|
112
|
+
iv = self.uint()
|
|
113
|
+
if self.peek() == ".":
|
|
114
|
+
self.pos += 1
|
|
115
|
+
if not self.peek().isdigit():
|
|
116
|
+
raise self.error()
|
|
117
|
+
frac_start = self.pos
|
|
118
|
+
frac = self.uint()
|
|
119
|
+
dv = float(iv) + float(frac) / 10 ** (self.pos - frac_start)
|
|
120
|
+
return ("dbl", -dv if neg else dv)
|
|
121
|
+
if self.peek() and (self.peek().isalpha() or self.peek() == "_"):
|
|
122
|
+
# e.g. 1e2 — the oracle lexes 'e2' as an ID and fails at parse time
|
|
123
|
+
raise self.error()
|
|
124
|
+
return ("int", -iv if neg else iv)
|
|
125
|
+
|
|
126
|
+
def dot_child(self):
|
|
127
|
+
"""After '.': '*' | ID | digits (digits become a field name)."""
|
|
128
|
+
self.ws()
|
|
129
|
+
c = self.peek()
|
|
130
|
+
if c == "*":
|
|
131
|
+
self.pos += 1
|
|
132
|
+
return ("wild",)
|
|
133
|
+
if c.isdigit():
|
|
134
|
+
return ("child", (str(self.uint()),))
|
|
135
|
+
name = self.ident()
|
|
136
|
+
if not name:
|
|
137
|
+
raise self.error()
|
|
138
|
+
return ("child", (name,))
|
|
139
|
+
|
|
140
|
+
def index_or_slice_body(self):
|
|
141
|
+
"""Inside brackets: INT | [start]:[end][:step]."""
|
|
142
|
+
has_start = False
|
|
143
|
+
start_v = 0
|
|
144
|
+
neg = self.peek() == "-"
|
|
145
|
+
if neg:
|
|
146
|
+
self.pos += 1
|
|
147
|
+
if self.peek().isdigit():
|
|
148
|
+
start_v = self.uint()
|
|
149
|
+
has_start = True
|
|
150
|
+
if neg:
|
|
151
|
+
start_v = -start_v
|
|
152
|
+
elif neg:
|
|
153
|
+
raise self.error()
|
|
154
|
+
self.ws()
|
|
155
|
+
if self.peek() != ":":
|
|
156
|
+
if not has_start:
|
|
157
|
+
raise self.error()
|
|
158
|
+
if self.peek() != "]":
|
|
159
|
+
raise self.error()
|
|
160
|
+
self.pos += 1
|
|
161
|
+
return ("index", start_v)
|
|
162
|
+
self.pos += 1
|
|
163
|
+
self.ws()
|
|
164
|
+
end_v = None
|
|
165
|
+
neg = self.peek() == "-"
|
|
166
|
+
if neg:
|
|
167
|
+
self.pos += 1
|
|
168
|
+
if self.peek().isdigit():
|
|
169
|
+
end_v = self.uint()
|
|
170
|
+
if neg:
|
|
171
|
+
end_v = -end_v
|
|
172
|
+
elif neg:
|
|
173
|
+
raise self.error()
|
|
174
|
+
self.ws()
|
|
175
|
+
step_v = None
|
|
176
|
+
if self.peek() == ":":
|
|
177
|
+
self.pos += 1
|
|
178
|
+
self.ws()
|
|
179
|
+
neg = self.peek() == "-"
|
|
180
|
+
if neg:
|
|
181
|
+
self.pos += 1
|
|
182
|
+
if self.peek().isdigit():
|
|
183
|
+
step_v = self.uint()
|
|
184
|
+
if neg:
|
|
185
|
+
step_v = -step_v
|
|
186
|
+
elif neg:
|
|
187
|
+
raise self.error()
|
|
188
|
+
self.ws()
|
|
189
|
+
if self.peek() != "]":
|
|
190
|
+
raise self.error()
|
|
191
|
+
self.pos += 1
|
|
192
|
+
return ("slice", start_v if has_start else None, end_v, step_v)
|
|
193
|
+
|
|
194
|
+
def bracket(self, after_descend: bool):
|
|
195
|
+
self.ws()
|
|
196
|
+
c = self.peek()
|
|
197
|
+
if c == "*":
|
|
198
|
+
self.pos += 1
|
|
199
|
+
self.ws()
|
|
200
|
+
if self.peek() != "]":
|
|
201
|
+
raise self.error()
|
|
202
|
+
self.pos += 1
|
|
203
|
+
return ("idxwild",)
|
|
204
|
+
if c == "?":
|
|
205
|
+
if after_descend:
|
|
206
|
+
raise self.error() # the oracle rejects `..[?(...)]`
|
|
207
|
+
self.pos += 1
|
|
208
|
+
filt = self.filter_expr()
|
|
209
|
+
self.ws()
|
|
210
|
+
if self.peek() != "]":
|
|
211
|
+
raise self.error()
|
|
212
|
+
self.pos += 1
|
|
213
|
+
return ("filter", filt)
|
|
214
|
+
if c in "'\"":
|
|
215
|
+
names = [self.quoted()]
|
|
216
|
+
self.ws()
|
|
217
|
+
while self.peek() == ",":
|
|
218
|
+
self.pos += 1
|
|
219
|
+
self.ws()
|
|
220
|
+
if self.peek() not in "'\"":
|
|
221
|
+
raise self.error()
|
|
222
|
+
names.append(self.quoted())
|
|
223
|
+
self.ws()
|
|
224
|
+
if self.peek() != "]":
|
|
225
|
+
raise self.error()
|
|
226
|
+
self.pos += 1
|
|
227
|
+
# a quoted '*' — alone or inside a union — is a dict wildcard
|
|
228
|
+
if "*" in names:
|
|
229
|
+
return ("wild",)
|
|
230
|
+
return ("child", tuple(names))
|
|
231
|
+
if c == "-" or c.isdigit() or c == ":":
|
|
232
|
+
return self.index_or_slice_body()
|
|
233
|
+
raise self.error()
|
|
234
|
+
|
|
235
|
+
def descend_substep(self):
|
|
236
|
+
self.ws()
|
|
237
|
+
c = self.peek()
|
|
238
|
+
if c == "*":
|
|
239
|
+
self.pos += 1
|
|
240
|
+
return ("wild",)
|
|
241
|
+
if c == "[":
|
|
242
|
+
self.pos += 1
|
|
243
|
+
return self.bracket(after_descend=True)
|
|
244
|
+
if c.isdigit():
|
|
245
|
+
return ("child", (str(self.uint()),))
|
|
246
|
+
name = self.ident()
|
|
247
|
+
if not name:
|
|
248
|
+
raise self.error()
|
|
249
|
+
return ("child", (name,))
|
|
250
|
+
|
|
251
|
+
# --- filter expressions ---
|
|
252
|
+
|
|
253
|
+
def fpath(self):
|
|
254
|
+
"""The step sequence after `@` in a filter (empty = current node)."""
|
|
255
|
+
steps = []
|
|
256
|
+
while True:
|
|
257
|
+
c = self.peek()
|
|
258
|
+
if c == ".":
|
|
259
|
+
if self.peek(1) == ".":
|
|
260
|
+
break
|
|
261
|
+
self.pos += 1
|
|
262
|
+
self.ws()
|
|
263
|
+
nc = self.peek()
|
|
264
|
+
if nc == "*":
|
|
265
|
+
self.pos += 1
|
|
266
|
+
steps.append(("wild",))
|
|
267
|
+
elif nc.isdigit():
|
|
268
|
+
steps.append(("field", str(self.uint())))
|
|
269
|
+
else:
|
|
270
|
+
name = self.ident()
|
|
271
|
+
if not name:
|
|
272
|
+
raise self.error()
|
|
273
|
+
steps.append(("field", name))
|
|
274
|
+
elif c == "[":
|
|
275
|
+
self.pos += 1
|
|
276
|
+
self.ws()
|
|
277
|
+
nc = self.peek()
|
|
278
|
+
if nc == "*":
|
|
279
|
+
self.pos += 1
|
|
280
|
+
self.ws()
|
|
281
|
+
if self.peek() != "]":
|
|
282
|
+
raise self.error()
|
|
283
|
+
self.pos += 1
|
|
284
|
+
steps.append(("idxwild",))
|
|
285
|
+
elif nc in "'\"":
|
|
286
|
+
names = [self.quoted()]
|
|
287
|
+
self.ws()
|
|
288
|
+
while self.peek() == ",":
|
|
289
|
+
self.pos += 1
|
|
290
|
+
self.ws()
|
|
291
|
+
if self.peek() not in "'\"":
|
|
292
|
+
raise self.error()
|
|
293
|
+
names.append(self.quoted())
|
|
294
|
+
self.ws()
|
|
295
|
+
if self.peek() != "]":
|
|
296
|
+
raise self.error()
|
|
297
|
+
self.pos += 1
|
|
298
|
+
if "*" in names:
|
|
299
|
+
steps.append(("wild",))
|
|
300
|
+
elif len(names) == 1:
|
|
301
|
+
steps.append(("field", names[0]))
|
|
302
|
+
else:
|
|
303
|
+
steps.append(("union", tuple(names)))
|
|
304
|
+
elif nc == "-" or nc.isdigit() or nc == ":":
|
|
305
|
+
steps.append(self.index_or_slice_body())
|
|
306
|
+
else:
|
|
307
|
+
raise self.error()
|
|
308
|
+
else:
|
|
309
|
+
break
|
|
310
|
+
return ("path", steps)
|
|
311
|
+
|
|
312
|
+
def factor(self):
|
|
313
|
+
self.ws()
|
|
314
|
+
c = self.peek()
|
|
315
|
+
if c == "@":
|
|
316
|
+
self.pos += 1
|
|
317
|
+
return self.fpath()
|
|
318
|
+
if c in "'\"":
|
|
319
|
+
return ("str", self.quoted())
|
|
320
|
+
if c == "(":
|
|
321
|
+
self.pos += 1
|
|
322
|
+
inner = self.arith()
|
|
323
|
+
self.ws()
|
|
324
|
+
if self.peek() != ")":
|
|
325
|
+
raise self.error()
|
|
326
|
+
self.pos += 1
|
|
327
|
+
return inner
|
|
328
|
+
if c == "-" or c.isdigit():
|
|
329
|
+
return self.number_token()
|
|
330
|
+
if c.isascii() and (c.isalpha() or c == "_"):
|
|
331
|
+
word = self.ident()
|
|
332
|
+
if word == "true":
|
|
333
|
+
return ("int", 1)
|
|
334
|
+
if word == "false":
|
|
335
|
+
return ("int", 0)
|
|
336
|
+
# any other bare word (null, None, foo, ...) is a string literal
|
|
337
|
+
return ("str", word)
|
|
338
|
+
raise self.error()
|
|
339
|
+
|
|
340
|
+
def term(self):
|
|
341
|
+
left = self.factor()
|
|
342
|
+
while True:
|
|
343
|
+
self.ws()
|
|
344
|
+
if self.peek() != "*":
|
|
345
|
+
return left
|
|
346
|
+
self.pos += 1
|
|
347
|
+
left = ("mul", left, self.factor())
|
|
348
|
+
|
|
349
|
+
def arith(self):
|
|
350
|
+
left = self.term()
|
|
351
|
+
while True:
|
|
352
|
+
self.ws()
|
|
353
|
+
c = self.peek()
|
|
354
|
+
if c not in "+-":
|
|
355
|
+
return left
|
|
356
|
+
self.pos += 1
|
|
357
|
+
left = ("add" if c == "+" else "sub", left, self.term())
|
|
358
|
+
|
|
359
|
+
def filter_literal(self):
|
|
360
|
+
"""The right operand of a filter comparison: a single literal —
|
|
361
|
+
number, quoted string, true/false, or bare word (no parens, no @,
|
|
362
|
+
no arith), matching the oracle grammar."""
|
|
363
|
+
self.ws()
|
|
364
|
+
c = self.peek()
|
|
365
|
+
if c == "-" or c.isdigit():
|
|
366
|
+
return self.number_token()
|
|
367
|
+
if c in "'\"":
|
|
368
|
+
return ("str", self.quoted())
|
|
369
|
+
if c.isascii() and (c.isalpha() or c == "_"):
|
|
370
|
+
word = self.ident()
|
|
371
|
+
if word == "true":
|
|
372
|
+
return ("int", 1)
|
|
373
|
+
if word == "false":
|
|
374
|
+
return ("int", 0)
|
|
375
|
+
return ("str", word)
|
|
376
|
+
raise self.error()
|
|
377
|
+
|
|
378
|
+
def filter_expr(self):
|
|
379
|
+
if self.peek() != "(":
|
|
380
|
+
raise self.error()
|
|
381
|
+
self.pos += 1
|
|
382
|
+
conjs = []
|
|
383
|
+
while True:
|
|
384
|
+
left = self.arith()
|
|
385
|
+
self.ws()
|
|
386
|
+
two = self.text[self.pos : self.pos + 2]
|
|
387
|
+
one = self.text[self.pos]
|
|
388
|
+
op = None
|
|
389
|
+
if two in ("==", "!=", "<=", ">="):
|
|
390
|
+
op = two
|
|
391
|
+
self.pos += 2
|
|
392
|
+
elif one in "<>":
|
|
393
|
+
op = one
|
|
394
|
+
self.pos += 1
|
|
395
|
+
if op is not None:
|
|
396
|
+
right = self.filter_literal()
|
|
397
|
+
conjs.append(("cmp", left, op, right))
|
|
398
|
+
else:
|
|
399
|
+
conjs.append(("exists", left))
|
|
400
|
+
self.ws()
|
|
401
|
+
if self.peek() == "&":
|
|
402
|
+
self.pos += 1
|
|
403
|
+
continue
|
|
404
|
+
if self.peek() == ")":
|
|
405
|
+
self.pos += 1
|
|
406
|
+
return conjs
|
|
407
|
+
raise self.error()
|
|
408
|
+
|
|
409
|
+
def expression(self):
|
|
410
|
+
"""Parse a whole JSONPath expression into a list of plan steps."""
|
|
411
|
+
self.ws()
|
|
412
|
+
if self.peek() == "$":
|
|
413
|
+
self.pos += 1
|
|
414
|
+
steps = []
|
|
415
|
+
while True:
|
|
416
|
+
self.ws()
|
|
417
|
+
c = self.peek()
|
|
418
|
+
if not c:
|
|
419
|
+
return steps
|
|
420
|
+
if c == ".":
|
|
421
|
+
if self.peek(1) == ".":
|
|
422
|
+
self.pos += 2
|
|
423
|
+
steps.append(("desc", self.descend_substep()))
|
|
424
|
+
else:
|
|
425
|
+
self.pos += 1
|
|
426
|
+
steps.append(self.dot_child())
|
|
427
|
+
elif c == "[":
|
|
428
|
+
self.pos += 1
|
|
429
|
+
steps.append(self.bracket(after_descend=False))
|
|
430
|
+
elif not steps and (c == "*" or c in "'\"" or c.isascii() and (c.isalpha() or c == "_")):
|
|
431
|
+
# implicit root: the oracle accepts a leading step without '$'
|
|
432
|
+
if c == "*":
|
|
433
|
+
self.pos += 1
|
|
434
|
+
steps.append(("wild",))
|
|
435
|
+
elif c in "'\"":
|
|
436
|
+
steps.append(("child", (self.quoted(),)))
|
|
437
|
+
else:
|
|
438
|
+
steps.append(("child", (self.ident(),)))
|
|
439
|
+
else:
|
|
440
|
+
raise self.error()
|
|
441
|
+
|
|
442
|
+
|
|
443
|
+
def _arith_has_path(arith) -> bool:
|
|
444
|
+
kind = arith[0]
|
|
445
|
+
if kind == "path":
|
|
446
|
+
return True
|
|
447
|
+
if kind in ("add", "sub", "mul"):
|
|
448
|
+
return _arith_has_path(arith[1]) or _arith_has_path(arith[2])
|
|
449
|
+
return False
|
|
450
|
+
|
|
451
|
+
|
|
452
|
+
def parse(expr: str):
|
|
453
|
+
"""Compile a JSONPath expression to a plan (list of steps)."""
|
|
454
|
+
if not isinstance(expr, str):
|
|
455
|
+
raise TypeError(f"expression must be a str, not {type(expr).__name__}")
|
|
456
|
+
parser = _Parser(expr)
|
|
457
|
+
steps = parser.expression()
|
|
458
|
+
parser.ws()
|
|
459
|
+
if parser.pos != len(expr):
|
|
460
|
+
raise parser.error()
|
|
461
|
+
return tuple(steps)
|
|
462
|
+
|
|
463
|
+
|
|
464
|
+
# ---------------------------------------------------------------------------
|
|
465
|
+
# Path rendering (matches the oracle's str(full_path) byte for byte)
|
|
466
|
+
# ---------------------------------------------------------------------------
|
|
467
|
+
|
|
468
|
+
# step kinds in result paths: ("f", name) object field; ("i", idx) sequence
|
|
469
|
+
# index; ("d", pos) dict-position (filter/`[*]` on dicts); ("s", idx)
|
|
470
|
+
# render-only index that keeps the current node ([*] on dicts/str/scalars).
|
|
471
|
+
|
|
472
|
+
|
|
473
|
+
def _render_field(name: str) -> str:
|
|
474
|
+
# NB: `ch in name` (not `ch in _QUOTE_NEEDED`) — for non-string keys this
|
|
475
|
+
# raises TypeError "argument of type 'int' is not iterable", the oracle's
|
|
476
|
+
# exact error when a path containing such a key is rendered.
|
|
477
|
+
if any(ch in name for ch in _QUOTE_NEEDED_CHARS):
|
|
478
|
+
return f"'{name}'"
|
|
479
|
+
return name
|
|
480
|
+
|
|
481
|
+
|
|
482
|
+
def render_path(steps) -> str:
|
|
483
|
+
"""Render a result path like the oracle's ``str(full_path)``."""
|
|
484
|
+
if not steps:
|
|
485
|
+
return "$"
|
|
486
|
+
pieces = []
|
|
487
|
+
for kind, val in steps:
|
|
488
|
+
if kind == "f":
|
|
489
|
+
pieces.append(_render_field(val))
|
|
490
|
+
else:
|
|
491
|
+
pieces.append(f"[{val}]")
|
|
492
|
+
return pieces[0] + "".join("." + p for p in pieces[1:])
|
|
493
|
+
|
|
494
|
+
|
|
495
|
+
# ---------------------------------------------------------------------------
|
|
496
|
+
# Evaluator
|
|
497
|
+
# ---------------------------------------------------------------------------
|
|
498
|
+
|
|
499
|
+
|
|
500
|
+
def _child(value, names):
|
|
501
|
+
if not isinstance(value, dict):
|
|
502
|
+
return
|
|
503
|
+
for name in names:
|
|
504
|
+
if name in value:
|
|
505
|
+
yield value[name], ("f", name)
|
|
506
|
+
|
|
507
|
+
|
|
508
|
+
def _wild(value):
|
|
509
|
+
if not isinstance(value, dict):
|
|
510
|
+
return
|
|
511
|
+
for key, val in value.items():
|
|
512
|
+
yield val, ("f", key)
|
|
513
|
+
|
|
514
|
+
|
|
515
|
+
def _index(value, idx):
|
|
516
|
+
if not value:
|
|
517
|
+
return
|
|
518
|
+
if isinstance(value, (list, tuple, str)):
|
|
519
|
+
if idx >= 0:
|
|
520
|
+
if idx < len(value):
|
|
521
|
+
yield value[idx], ("i", idx)
|
|
522
|
+
else:
|
|
523
|
+
# out-of-range negatives raise IndexError (CPython message)
|
|
524
|
+
yield value[idx], ("i", idx)
|
|
525
|
+
return
|
|
526
|
+
if isinstance(value, dict):
|
|
527
|
+
if idx >= 0 and idx >= len(value):
|
|
528
|
+
return
|
|
529
|
+
# value[idx] on a dict raises KeyError(idx) for JSON-domain keys
|
|
530
|
+
yield value[idx], ("i", idx)
|
|
531
|
+
return
|
|
532
|
+
# truthy scalar: len() raises TypeError ("object of type 'int' has no len()")
|
|
533
|
+
len(value)
|
|
534
|
+
return # unreachable
|
|
535
|
+
|
|
536
|
+
|
|
537
|
+
def _idxwild(value):
|
|
538
|
+
if isinstance(value, (list, tuple)):
|
|
539
|
+
for i, item in enumerate(value):
|
|
540
|
+
yield item, ("i", i)
|
|
541
|
+
return
|
|
542
|
+
if not value:
|
|
543
|
+
return
|
|
544
|
+
if isinstance(value, float):
|
|
545
|
+
len(value) # TypeError: object of type 'float' has no len()
|
|
546
|
+
# truthy dict/str/int/bool/other-sized-object: the node itself at [0]
|
|
547
|
+
yield value, ("s", 0)
|
|
548
|
+
|
|
549
|
+
|
|
550
|
+
def _slice(value, start, end, step):
|
|
551
|
+
if not value:
|
|
552
|
+
return
|
|
553
|
+
step_v = step if step is not None else 1
|
|
554
|
+
if step_v == 0:
|
|
555
|
+
raise ValueError("slice step cannot be zero")
|
|
556
|
+
if not isinstance(value, (list, tuple)):
|
|
557
|
+
return
|
|
558
|
+
for i in range(*slice(start, end, step).indices(len(value))):
|
|
559
|
+
yield value[i], ("i", i)
|
|
560
|
+
|
|
561
|
+
|
|
562
|
+
def _descend(substep, value, path, out):
|
|
563
|
+
"""DFS pre-order: apply the substep at the node, then descend."""
|
|
564
|
+
for val, step in _apply(substep, value):
|
|
565
|
+
out.append((val, path + (step,)))
|
|
566
|
+
if isinstance(value, dict):
|
|
567
|
+
children = ((v, ("f", k)) for k, v in value.items())
|
|
568
|
+
elif isinstance(value, list):
|
|
569
|
+
children = ((v, ("i", i)) for i, v in enumerate(value))
|
|
570
|
+
else:
|
|
571
|
+
return
|
|
572
|
+
for child, step in children:
|
|
573
|
+
_descend(substep, child, path + (step,), out)
|
|
574
|
+
|
|
575
|
+
|
|
576
|
+
def _filter(filt, value):
|
|
577
|
+
if isinstance(value, list):
|
|
578
|
+
candidates = ((v, ("i", i)) for i, v in enumerate(value))
|
|
579
|
+
elif isinstance(value, dict):
|
|
580
|
+
candidates = ((v, ("d", i)) for i, v in enumerate(value.values()))
|
|
581
|
+
else:
|
|
582
|
+
return
|
|
583
|
+
for cand, step in candidates:
|
|
584
|
+
if _eval_filter(filt, cand):
|
|
585
|
+
yield cand, step
|
|
586
|
+
|
|
587
|
+
|
|
588
|
+
def _apply(step, value):
|
|
589
|
+
kind = step[0]
|
|
590
|
+
if kind == "child":
|
|
591
|
+
yield from _child(value, step[1])
|
|
592
|
+
elif kind == "wild":
|
|
593
|
+
yield from _wild(value)
|
|
594
|
+
elif kind == "index":
|
|
595
|
+
yield from _index(value, step[1])
|
|
596
|
+
elif kind == "idxwild":
|
|
597
|
+
yield from _idxwild(value)
|
|
598
|
+
elif kind == "slice":
|
|
599
|
+
yield from _slice(value, step[1], step[2], step[3])
|
|
600
|
+
elif kind == "filter":
|
|
601
|
+
yield from _filter(step[1], value)
|
|
602
|
+
else: # desc is handled by _descend, never here
|
|
603
|
+
raise AssertionError(f"unexpected step {step!r}")
|
|
604
|
+
|
|
605
|
+
|
|
606
|
+
def _eval_filter(conjs, at) -> bool:
|
|
607
|
+
"""Evaluate all conjuncts (the oracle does NOT short-circuit `&`: later
|
|
608
|
+
conjuncts still run and their TypeErrors propagate) and AND the results.
|
|
609
|
+
The comparison cross product is likewise fully evaluated."""
|
|
610
|
+
all_ok = True
|
|
611
|
+
for i, conj in enumerate(conjs):
|
|
612
|
+
if conj[0] == "exists":
|
|
613
|
+
if i == 0 and len(conjs) > 1:
|
|
614
|
+
# `?(@.a & ...)`: existence as the LEFT operand of `&`
|
|
615
|
+
raise NotImplementedError()
|
|
616
|
+
ok = _arith_has_path(conj[1]) and bool(_eval_arith_safe(conj[1], at))
|
|
617
|
+
else:
|
|
618
|
+
_, left, op, right = conj
|
|
619
|
+
lefts = _eval_arith_safe(left, at)
|
|
620
|
+
rights = _eval_arith_safe(right, at)
|
|
621
|
+
ok = False
|
|
622
|
+
for lv in lefts:
|
|
623
|
+
for rv in rights:
|
|
624
|
+
if _compare(lv, op, rv):
|
|
625
|
+
ok = True
|
|
626
|
+
all_ok = all_ok and ok
|
|
627
|
+
return all_ok
|
|
628
|
+
|
|
629
|
+
|
|
630
|
+
def _eval_arith(arith, at) -> list:
|
|
631
|
+
kind = arith[0]
|
|
632
|
+
if kind in ("int", "dbl", "str"):
|
|
633
|
+
return [arith[1]]
|
|
634
|
+
if kind == "path":
|
|
635
|
+
values = [at]
|
|
636
|
+
for fpstep in arith[1]:
|
|
637
|
+
nxt = []
|
|
638
|
+
for node in values:
|
|
639
|
+
nxt.extend(_apply_fpath(fpstep, node))
|
|
640
|
+
values = nxt
|
|
641
|
+
return values
|
|
642
|
+
# binary arithmetic: cross product. A pair that would raise in Python
|
|
643
|
+
# poisons the WHOLE expression (see _eval_arith_safe). Note that path
|
|
644
|
+
# evaluation errors (TypeError/KeyError/IndexError/ValueError from index
|
|
645
|
+
# and slice steps) are raised OUTSIDE this try and propagate, exactly
|
|
646
|
+
# like the oracle.
|
|
647
|
+
lefts = _eval_arith(arith[1], at)
|
|
648
|
+
rights = _eval_arith(arith[2], at)
|
|
649
|
+
out = []
|
|
650
|
+
for lv in lefts:
|
|
651
|
+
for rv in rights:
|
|
652
|
+
try:
|
|
653
|
+
if kind == "add":
|
|
654
|
+
out.append(lv + rv)
|
|
655
|
+
elif kind == "sub":
|
|
656
|
+
out.append(lv - rv)
|
|
657
|
+
else:
|
|
658
|
+
out.append(lv * rv)
|
|
659
|
+
except (TypeError, ValueError):
|
|
660
|
+
raise _ArithPoison from None
|
|
661
|
+
return out
|
|
662
|
+
|
|
663
|
+
|
|
664
|
+
class _ArithPoison(Exception):
|
|
665
|
+
"""An arithmetic pair raised TypeError/ValueError: the whole operand
|
|
666
|
+
yields no values (the oracle treats the conjunct as a non-match)."""
|
|
667
|
+
|
|
668
|
+
|
|
669
|
+
def _eval_arith_safe(arith, at) -> list:
|
|
670
|
+
"""Evaluate an arith operand; an arithmetic TypeError/ValueError anywhere
|
|
671
|
+
in it makes the whole operand yield no values. Errors from PATH steps
|
|
672
|
+
(indexing scalars, out-of-range negatives, ...) propagate."""
|
|
673
|
+
try:
|
|
674
|
+
return _eval_arith(arith, at)
|
|
675
|
+
except _ArithPoison:
|
|
676
|
+
return []
|
|
677
|
+
|
|
678
|
+
|
|
679
|
+
def _apply_fpath(step, value):
|
|
680
|
+
kind = step[0]
|
|
681
|
+
if kind == "field":
|
|
682
|
+
return [v for v, _ in _child(value, (step[1],))]
|
|
683
|
+
if kind == "union":
|
|
684
|
+
return [v for v, _ in _child(value, step[1])]
|
|
685
|
+
if kind == "wild":
|
|
686
|
+
return [v for v, _ in _wild(value)]
|
|
687
|
+
if kind == "index":
|
|
688
|
+
return [v for v, _ in _index(value, step[1])]
|
|
689
|
+
if kind == "slice":
|
|
690
|
+
return [v for v, _ in _slice(value, step[1], step[2], step[3])]
|
|
691
|
+
if kind == "idxwild":
|
|
692
|
+
return [v for v, _ in _idxwild(value)]
|
|
693
|
+
raise AssertionError(f"unexpected filter-path step {step!r}")
|
|
694
|
+
|
|
695
|
+
|
|
696
|
+
def _compare(left, op, right) -> bool:
|
|
697
|
+
"""One filter comparison under the oracle's coercion contract."""
|
|
698
|
+
if type(right) is int:
|
|
699
|
+
# int() coercion of the left operand; ValueError is caught (no
|
|
700
|
+
# match), TypeError propagates (CPython's message, like the oracle)
|
|
701
|
+
try:
|
|
702
|
+
lv = int(left)
|
|
703
|
+
except ValueError:
|
|
704
|
+
return False
|
|
705
|
+
if op == "==":
|
|
706
|
+
return lv == right
|
|
707
|
+
if op == "!=":
|
|
708
|
+
return lv != right
|
|
709
|
+
if op == "<":
|
|
710
|
+
return lv < right
|
|
711
|
+
if op == "<=":
|
|
712
|
+
return lv <= right
|
|
713
|
+
if op == ">":
|
|
714
|
+
return lv > right
|
|
715
|
+
return lv >= right
|
|
716
|
+
# float / str (incl. bare-word) right: direct comparison; mixed-type
|
|
717
|
+
# ordering raises TypeError with CPython's message, like the oracle
|
|
718
|
+
if op == "==":
|
|
719
|
+
return left == right
|
|
720
|
+
if op == "!=":
|
|
721
|
+
return left != right
|
|
722
|
+
if op == "<":
|
|
723
|
+
return left < right
|
|
724
|
+
if op == "<=":
|
|
725
|
+
return left <= right
|
|
726
|
+
if op == ">":
|
|
727
|
+
return left > right
|
|
728
|
+
return left >= right
|
|
729
|
+
|
|
730
|
+
|
|
731
|
+
def evaluate(plan, data):
|
|
732
|
+
"""Evaluate a parsed plan; return [(value, path_steps), ...]."""
|
|
733
|
+
current = [(data, ())]
|
|
734
|
+
for step in plan:
|
|
735
|
+
kind = step[0]
|
|
736
|
+
nxt = []
|
|
737
|
+
if kind == "desc":
|
|
738
|
+
for value, path in current:
|
|
739
|
+
_descend(step[1], value, path, nxt)
|
|
740
|
+
else:
|
|
741
|
+
for value, path in current:
|
|
742
|
+
for val, pstep in _apply(step, value):
|
|
743
|
+
nxt.append((val, path + (pstep,)))
|
|
744
|
+
current = nxt
|
|
745
|
+
return current
|
|
746
|
+
|
|
747
|
+
|
|
748
|
+
def find(plan, data):
|
|
749
|
+
"""Evaluate a parsed plan and return ``[(value, rendered_path), ...]``."""
|
|
750
|
+
return [(value, render_path(path)) for value, path in evaluate(plan, data)]
|
jsonpath_mojo/core.py
ADDED
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
"""Public query API: one-shot JSONPath find with native + fallback backends.
|
|
2
|
+
|
|
3
|
+
``find(expr, data)`` returns a list of ``(value, path)`` pairs identical —
|
|
4
|
+
in values, order, and path rendering — to
|
|
5
|
+
``[(m.value, str(m.full_path)) for m in jsonpath_ng.ext.parse(expr).find(data)]``.
|
|
6
|
+
|
|
7
|
+
Backend selection, per call:
|
|
8
|
+
|
|
9
|
+
1. If the native Mojo kernel is available and ``data`` is JSON-representable
|
|
10
|
+
(``json.dumps(data, allow_nan=False)`` succeeds), the query runs natively:
|
|
11
|
+
the kernel parses the expression and the JSON text and returns the matched
|
|
12
|
+
paths; values are then resolved against the original Python objects, so
|
|
13
|
+
they are the same objects the oracle would return.
|
|
14
|
+
2. Otherwise (no kernel, non-JSON data, or any kernel/wrapper disagreement
|
|
15
|
+
such as >63-bit integers or duplicate-after-serialization keys), the
|
|
16
|
+
vendored pure-Python engine evaluates the query with identical results.
|
|
17
|
+
|
|
18
|
+
Set ``JSONPATH_MOJO_DISABLE_NATIVE=1`` to force the pure-Python engine.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
import json
|
|
24
|
+
from itertools import islice
|
|
25
|
+
|
|
26
|
+
from jsonpath_mojo import _reference
|
|
27
|
+
from jsonpath_mojo._native import (
|
|
28
|
+
ST_INDEXERROR,
|
|
29
|
+
ST_KEYERROR,
|
|
30
|
+
ST_NOTIMPL,
|
|
31
|
+
ST_OK,
|
|
32
|
+
ST_PARSE,
|
|
33
|
+
ST_FALLBACK,
|
|
34
|
+
ST_TE_INT,
|
|
35
|
+
ST_TE_LEN,
|
|
36
|
+
ST_TE_ORD,
|
|
37
|
+
ST_VE_SLICE,
|
|
38
|
+
NativeUnavailable,
|
|
39
|
+
backend_info,
|
|
40
|
+
find_native,
|
|
41
|
+
int_coercion_type_error,
|
|
42
|
+
len_type_error,
|
|
43
|
+
native_available,
|
|
44
|
+
ordering_type_error,
|
|
45
|
+
)
|
|
46
|
+
from jsonpath_mojo._reference import JsonPathError
|
|
47
|
+
|
|
48
|
+
__all__ = [
|
|
49
|
+
"JsonPathError",
|
|
50
|
+
"backend_info",
|
|
51
|
+
"find",
|
|
52
|
+
"find_parsed",
|
|
53
|
+
"native_available",
|
|
54
|
+
"parse",
|
|
55
|
+
]
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class _NativeMismatch(Exception):
|
|
59
|
+
"""Kernel-result paths could not be resolved against the original data
|
|
60
|
+
(only possible for data outside the JSON domain, e.g. non-string dict
|
|
61
|
+
keys). The caller re-runs the query on the pure-Python engine."""
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _serialize(data) -> bytes | None:
|
|
65
|
+
"""JSON-representable check + serialization; None when out of domain."""
|
|
66
|
+
try:
|
|
67
|
+
return json.dumps(data, allow_nan=False).encode("ascii")
|
|
68
|
+
except (TypeError, ValueError):
|
|
69
|
+
return None
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _resolve(data, kinds, vals, path_off, strings):
|
|
73
|
+
"""Resolve kernel path steps against the original Python objects and
|
|
74
|
+
render oracle-style path strings."""
|
|
75
|
+
def _resolve(data, kinds, vals, path_off, strings):
|
|
76
|
+
"""Resolve kernel path steps against the original Python objects and
|
|
77
|
+
render oracle-style path strings.
|
|
78
|
+
|
|
79
|
+
Matches arrive in document order, so consecutive paths share long
|
|
80
|
+
prefixes; a chain of already-resolved (step, node, rendered-prefix)
|
|
81
|
+
entries is kept and only the diverging tail is walked per match. This
|
|
82
|
+
keeps big result sets (e.g. `$..*`) fast.
|
|
83
|
+
"""
|
|
84
|
+
out = []
|
|
85
|
+
# rendered field fragments, memoized per output string id
|
|
86
|
+
field_frags: dict[int, str] = {}
|
|
87
|
+
# index fragments, memoized per index value
|
|
88
|
+
idx_frags: dict[int, str] = {}
|
|
89
|
+
# resolution chain for the previous match: steps, nodes, rendered prefixes
|
|
90
|
+
chain_steps: list = []
|
|
91
|
+
chain_nodes: list = [data]
|
|
92
|
+
chain_render: list = [""]
|
|
93
|
+
n_matches = len(path_off) - 1
|
|
94
|
+
for m in range(n_matches):
|
|
95
|
+
start, end = path_off[m], path_off[m + 1]
|
|
96
|
+
# longest common prefix with the previous match's chain
|
|
97
|
+
depth = end - start
|
|
98
|
+
common = 0
|
|
99
|
+
limit = depth if depth < len(chain_steps) else len(chain_steps)
|
|
100
|
+
while common < limit:
|
|
101
|
+
s = start + common
|
|
102
|
+
if chain_steps[common] != (kinds[s], vals[s]):
|
|
103
|
+
break
|
|
104
|
+
common += 1
|
|
105
|
+
del chain_steps[common:]
|
|
106
|
+
del chain_nodes[common + 1 :]
|
|
107
|
+
del chain_render[common + 1 :]
|
|
108
|
+
node = chain_nodes[-1]
|
|
109
|
+
rendered = chain_render[-1]
|
|
110
|
+
for s in range(start + common, end):
|
|
111
|
+
kind = kinds[s]
|
|
112
|
+
val = vals[s]
|
|
113
|
+
if kind == 0: # object field
|
|
114
|
+
key = strings[val]
|
|
115
|
+
try:
|
|
116
|
+
node = node[key]
|
|
117
|
+
except (KeyError, TypeError) as exc:
|
|
118
|
+
raise _NativeMismatch from exc
|
|
119
|
+
frag = field_frags.get(val)
|
|
120
|
+
if frag is None:
|
|
121
|
+
frag = field_frags[val] = _reference._render_field(key)
|
|
122
|
+
elif kind == 1: # sequence index (list/tuple/str; may be negative)
|
|
123
|
+
try:
|
|
124
|
+
node = node[val]
|
|
125
|
+
except (IndexError, KeyError, TypeError) as exc:
|
|
126
|
+
raise _NativeMismatch from exc
|
|
127
|
+
frag = idx_frags.get(val)
|
|
128
|
+
if frag is None:
|
|
129
|
+
frag = idx_frags[val] = f"[{val}]"
|
|
130
|
+
elif kind == 4 or kind == 5: # list-only steps (filter/descend):
|
|
131
|
+
# the oracle applies these only to lists, so tuple data must
|
|
132
|
+
# reroute to the pure-Python engine
|
|
133
|
+
if not isinstance(node, list):
|
|
134
|
+
raise _NativeMismatch
|
|
135
|
+
node = node[val]
|
|
136
|
+
frag = idx_frags.get(val)
|
|
137
|
+
if frag is None:
|
|
138
|
+
frag = idx_frags[val] = f"[{val}]"
|
|
139
|
+
elif kind == 2: # dict-position index (filter on dicts)
|
|
140
|
+
values = getattr(node, "values", None)
|
|
141
|
+
if values is None:
|
|
142
|
+
raise _NativeMismatch
|
|
143
|
+
view = values()
|
|
144
|
+
if val >= len(view):
|
|
145
|
+
raise _NativeMismatch
|
|
146
|
+
node = next(islice(view, val, None))
|
|
147
|
+
frag = idx_frags.get(val)
|
|
148
|
+
if frag is None:
|
|
149
|
+
frag = idx_frags[val] = f"[{val}]"
|
|
150
|
+
else: # render-only [val]: the node itself ([*] on dict/str/scalar)
|
|
151
|
+
frag = idx_frags.get(val)
|
|
152
|
+
if frag is None:
|
|
153
|
+
frag = idx_frags[val] = f"[{val}]"
|
|
154
|
+
rendered = frag if not rendered else rendered + "." + frag
|
|
155
|
+
chain_steps.append((kind, val))
|
|
156
|
+
chain_nodes.append(node)
|
|
157
|
+
chain_render.append(rendered)
|
|
158
|
+
out.append((node, rendered if chain_steps else "$"))
|
|
159
|
+
return out
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def _raise_for_status(status: int, aux: int):
|
|
163
|
+
"""Translate a native error status into the oracle's exception."""
|
|
164
|
+
if status == ST_PARSE:
|
|
165
|
+
raise JsonPathError(f"Parse error at 1:{aux}")
|
|
166
|
+
if status == ST_TE_INT:
|
|
167
|
+
raise int_coercion_type_error(aux)
|
|
168
|
+
if status == ST_TE_ORD:
|
|
169
|
+
raise ordering_type_error(aux)
|
|
170
|
+
if status == ST_TE_LEN:
|
|
171
|
+
raise len_type_error(aux)
|
|
172
|
+
if status == ST_INDEXERROR:
|
|
173
|
+
raise IndexError("list index out of range" if aux == 0 else "string index out of range")
|
|
174
|
+
if status == ST_KEYERROR:
|
|
175
|
+
raise KeyError(aux)
|
|
176
|
+
if status == ST_VE_SLICE:
|
|
177
|
+
raise ValueError("slice step cannot be zero")
|
|
178
|
+
if status == ST_NOTIMPL:
|
|
179
|
+
raise NotImplementedError()
|
|
180
|
+
raise NativeUnavailable(f"unexpected native status {status}")
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def find(expr, data):
|
|
184
|
+
"""Evaluate a JSONPath expression; return oracle-equal (value, path) pairs."""
|
|
185
|
+
if not isinstance(expr, str):
|
|
186
|
+
raise TypeError(f"expression must be a str, not {type(expr).__name__}")
|
|
187
|
+
json_bytes = _serialize(data)
|
|
188
|
+
if json_bytes is not None:
|
|
189
|
+
try:
|
|
190
|
+
status, aux, kinds, vals, path_off, strings = find_native(
|
|
191
|
+
expr.encode("utf-8", "surrogatepass"), json_bytes
|
|
192
|
+
)
|
|
193
|
+
except NativeUnavailable:
|
|
194
|
+
status = ST_FALLBACK
|
|
195
|
+
if status == ST_OK:
|
|
196
|
+
try:
|
|
197
|
+
return _resolve(data, kinds, vals, path_off, strings)
|
|
198
|
+
except _NativeMismatch:
|
|
199
|
+
pass # non-JSON-domain data: fall through to pure Python
|
|
200
|
+
elif status == ST_FALLBACK:
|
|
201
|
+
pass # kernel flagged out-of-domain input: pure Python takes over
|
|
202
|
+
else:
|
|
203
|
+
_raise_for_status(status, aux)
|
|
204
|
+
return _reference.find(_reference.parse(expr), data)
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def parse(expr):
|
|
208
|
+
"""Compile a JSONPath expression for repeated use with find_parsed."""
|
|
209
|
+
return _reference.parse(expr)
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def find_parsed(plan, data):
|
|
213
|
+
"""Evaluate a plan from parse(); always uses the pure-Python engine."""
|
|
214
|
+
return _reference.find(plan, data)
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: jsonpath-mojo
|
|
3
|
+
Version: 0.2.5
|
|
4
|
+
Summary: Fast JSONPath queries (jsonpath-ng ext dialect), powered by a Mojo kernel (pure-Python fallback included).
|
|
5
|
+
Project-URL: Repository, https://github.com/thyn-ai/mojo-kernels
|
|
6
|
+
Project-URL: Company, https://thyn.ai
|
|
7
|
+
Author: Thyn
|
|
8
|
+
Maintainer: Thyn
|
|
9
|
+
License-Expression: Apache-2.0
|
|
10
|
+
Keywords: json,jsonpath,jsonpath-ng,mojo,query
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
15
|
+
Requires-Python: >=3.10
|
|
16
|
+
Description-Content-Type: text/markdown
|
|
17
|
+
|
|
18
|
+
# jsonpath-mojo
|
|
19
|
+
|
|
20
|
+
A fast JSONPath query engine, API-compatible with the
|
|
21
|
+
[`jsonpath-ng`](https://pypi.org/project/jsonpath-ng/) package (the
|
|
22
|
+
`jsonpath_ng.ext` extended dialect), powered by a clean-room Mojo kernel —
|
|
23
|
+
with a vendored pure-Python engine for platforms without a native build (including Windows — tested there in CI: [`windows-fallback`](https://github.com/thyn-ai/mojo-kernels/actions/workflows/windows-fallback.yml)).
|
|
24
|
+
|
|
25
|
+
```python
|
|
26
|
+
from jsonpath_mojo import find
|
|
27
|
+
|
|
28
|
+
data = {"store": {"book": [{"title": "Sayings", "price": 8.95},
|
|
29
|
+
{"title": "Sword", "price": 12.99}]}}
|
|
30
|
+
|
|
31
|
+
find("$.store.book[*].title", data) # [('Sayings', 'store.book.[0].title'),
|
|
32
|
+
# ('Sword', 'store.book.[1].title')]
|
|
33
|
+
find("$.store.book[?(@.price < 10)]", data) # filter scripts
|
|
34
|
+
find("$..price", data) # recursive descent
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
`find(expr, data)` returns the same `(value, str(full_path))` sequence as
|
|
38
|
+
`[(m.value, str(m.full_path)) for m in jsonpath_ng.ext.parse(expr).find(data)]`
|
|
39
|
+
— same values, same order, same path rendering, verified element-for-element
|
|
40
|
+
by the differential test suite on both backends.
|
|
41
|
+
|
|
42
|
+
- **Same results**: the suite runs every query against the published
|
|
43
|
+
`jsonpath_ng==1.7.0` oracle and asserts exact sequence parity — plus
|
|
44
|
+
exception-type parity for the error contract (parse errors raise
|
|
45
|
+
`jsonpath_mojo.JsonPathError`; runtime errors raise the same builtin
|
|
46
|
+
`TypeError`/`KeyError`/`IndexError`/`ValueError`/`NotImplementedError` the
|
|
47
|
+
oracle raises).
|
|
48
|
+
- **Much faster**: a native expression parser + evaluator instead of a PLY
|
|
49
|
+
parser rebuilt per call — 49x faster at 100-book documents, 3.6x at 2k,
|
|
50
|
+
1.7x at 20k (Apple M4 Max; full method and numbers below).
|
|
51
|
+
- **No toolchain needed**: per-platform wheels ship the compiled kernel.
|
|
52
|
+
Everywhere else the package transparently uses its pure-Python engine
|
|
53
|
+
(which is itself ~2-28x faster than the oracle on these datasets).
|
|
54
|
+
- Force the fallback with `JSONPATH_MOJO_DISABLE_NATIVE=1`; inspect the
|
|
55
|
+
active backend with `jsonpath_mojo.backend_info()`.
|
|
56
|
+
|
|
57
|
+
## Supported syntax
|
|
58
|
+
|
|
59
|
+
- child steps: `$.a`, `$['a']`, `$.a.b`, dot-number children `$.a.0`
|
|
60
|
+
- field unions: `$['a', 'b']` (expression order, duplicates repeated); a
|
|
61
|
+
quoted `'*'` — alone or in a union — is a wildcard
|
|
62
|
+
- wildcards: `$.*` (object values), `$[*]` (sequence elements; see README in
|
|
63
|
+
the repo for the exact non-list truth table)
|
|
64
|
+
- recursive descent: `$..a`, `$..*`, `$..[0]`, `$..['a']` (DFS pre-order)
|
|
65
|
+
- index: `$.a[0]`, `$.a[-1]`
|
|
66
|
+
- slices: `$.a[1:5:2]`, `$.a[::-1]` (Python slice semantics)
|
|
67
|
+
- filters: `$.a[?(@.x > 2)]` with `== != < <= > >=`, `&` conjunctions,
|
|
68
|
+
existence tests `?(@.x)`, arith (`+ - *`) on the left side, literals
|
|
69
|
+
(numbers, quoted strings, `true`/`false`, bare words) on the right, and
|
|
70
|
+
`@` paths with fields/indexes/slices/wildcards
|
|
71
|
+
|
|
72
|
+
Expressions outside this grammar (or data outside the JSON domain — non-string
|
|
73
|
+
dict keys, NaN/Infinity, tuples, custom objects) are handled with identical
|
|
74
|
+
results: grammar gaps raise `JsonPathError`, non-JSON data transparently
|
|
75
|
+
reroutes to the pure-Python engine. Currently unsupported oracle features:
|
|
76
|
+
`?(...)` filters nested inside a filter path (e.g. `?(@.a[?(@ > 1)] == 2)`),
|
|
77
|
+
and sorting/`~` regex extensions.
|
|
78
|
+
|
|
79
|
+
## Benchmarks
|
|
80
|
+
|
|
81
|
+
Method (see `benchmarks/bench_jsonpath.py` in the repository): store-shaped
|
|
82
|
+
JSON documents (100 / 2,000 / 20,000 book records) and a 14-query battery
|
|
83
|
+
covering the supported scope. Each cell runs `jsonpath_ng.ext.parse(expr).
|
|
84
|
+
find(data)` per query against `jsonpath_mojo.find(expr, data)`. COLD = first
|
|
85
|
+
battery call (includes one-time parser setup); WARM = median of 5 battery
|
|
86
|
+
runs. Correctness is asserted before timing.
|
|
87
|
+
|
|
88
|
+
Measured on Apple M4 Max, macOS 26.6.2, Python 3.12.14, jsonpath_ng 1.7.0,
|
|
89
|
+
Mojo 1.1.0, 2026-09-19:
|
|
90
|
+
|
|
91
|
+
| dataset | backend | cold (s) | warm (s) | speedup (warm) |
|
|
92
|
+
|---|---|---|---|---|
|
|
93
|
+
| 100 books | oracle jsonpath_ng | 0.1568 | 0.1993 | 1.0x |
|
|
94
|
+
| | jsonpath-mojo native | 0.0050 | 0.0041 | **49.2x** |
|
|
95
|
+
| | jsonpath-mojo fallback | 0.0078 | 0.0071 | 27.9x |
|
|
96
|
+
| 2,000 books | oracle jsonpath_ng | 0.3209 | 0.2750 | 1.0x |
|
|
97
|
+
| | jsonpath-mojo native | 0.0728 | 0.0766 | **3.6x** |
|
|
98
|
+
| | jsonpath-mojo fallback | 0.1411 | 0.1353 | 2.0x |
|
|
99
|
+
| 20,000 books | oracle jsonpath_ng | 1.7522 | 1.4909 | 1.0x |
|
|
100
|
+
| | jsonpath-mojo native | 0.7877 | 0.8738 | **1.7x** |
|
|
101
|
+
| | jsonpath-mojo fallback | 1.4734 | 1.2992 | 1.1x |
|
|
102
|
+
|
|
103
|
+
The oracle rebuilds its PLY parser on every `parse()` call (~7 ms), so small
|
|
104
|
+
and medium documents are dominated by expression parsing — where the native
|
|
105
|
+
kernel and even the pure-Python engine win overwhelmingly. On very large
|
|
106
|
+
documents the evaluation itself dominates; the native pipeline
|
|
107
|
+
(`json.dumps` → kernel parse+eval → path resolution) still leads, and result
|
|
108
|
+
correctness is identical either way.
|
|
109
|
+
|
|
110
|
+
Source, tests, and development: <https://github.com/thyn-ai/mojo-kernels>
|
|
111
|
+
|
|
112
|
+
License: Apache-2.0, © 2026 Algenta
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
jsonpath_mojo/__init__.py,sha256=g44-uyF9b6-_R4shhh8J-2l5XOvuzuK2Q0YEx6l0PbQ,1134
|
|
2
|
+
jsonpath_mojo/_native.py,sha256=zJ-gOmUOXpI8kubmeT9jH0ABZIQ4KaDOBOfQZhLQlMI,9672
|
|
3
|
+
jsonpath_mojo/_reference.py,sha256=UEFCwA1Ded0mPbLyjRiqrhF0rACPiMlONHrUBGTJ_LQ,24761
|
|
4
|
+
jsonpath_mojo/core.py,sha256=fN-GzlKhVih69jIsrk1WhQxlqALImBPrCqGhWi4WVAg,8078
|
|
5
|
+
jsonpath_mojo-0.2.5.dist-info/METADATA,sha256=NM_ZQKEf6HdMgmxEbmwnNdjCRWX-WwC03Fq8m85iqPw,5641
|
|
6
|
+
jsonpath_mojo-0.2.5.dist-info/WHEEL,sha256=THafob7ofN-NsuMN7Mg4qZyHaQI7KkD-QlcQatYhXPo,87
|
|
7
|
+
jsonpath_mojo-0.2.5.dist-info/RECORD,,
|