Repository navigation
Expand file tree
/
Copy pathselectors.py
More file actions
769 lines (657 loc) · 26.7 KB
/
Copy pathselectors.py
File metadata and controls
769 lines (657 loc) · 26.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
"""JSONPath segments and selectors, as returned from `Parser.parse`."""
from __future__ import annotations
from abc import ABC
from abc import abstractmethod
from collections.abc import Mapping
from collections.abc import Sequence
from contextlib import suppress
from typing import TYPE_CHECKING
from typing import Any
from typing import AsyncIterable
from typing import Iterable
from typing import List
from typing import Optional
from typing import TypeVar
from typing import Union
from .exceptions import JSONPathIndexError
from .exceptions import JSONPathTypeError
if TYPE_CHECKING:
from .env import JSONPathEnvironment
from .filter import BooleanExpression
from .match import JSONPathMatch
from .token import Token
# ruff: noqa: D102
class JSONPathSelector(ABC):
"""Base class for all JSONPath segments and selectors."""
__slots__ = ("env", "token")
def __init__(self, *, env: JSONPathEnvironment, token: Token) -> None:
self.env = env
self.token = token
@abstractmethod
def resolve(self, matches: Iterable[JSONPathMatch]) -> Iterable[JSONPathMatch]:
"""Apply the segment/selector to each node in _matches_.
Arguments:
matches: Nodes matched by preceding segments/selectors. This is like
a lazy _NodeList_, as described in RFC 9535, but each match carries
more than the node's value and location.
Returns:
The `JSONPathMatch` instances created by applying this selector to each
preceding node.
"""
@abstractmethod
def resolve_async(
self, matches: AsyncIterable[JSONPathMatch]
) -> AsyncIterable[JSONPathMatch]:
"""An async version of `resolve`."""
class PropertySelector(JSONPathSelector):
"""A shorthand or bracketed property selector."""
__slots__ = ("name", "shorthand")
def __init__(
self,
*,
env: JSONPathEnvironment,
token: Token,
name: str,
shorthand: bool,
) -> None:
super().__init__(env=env, token=token)
self.name = name
self.shorthand = shorthand
def __str__(self) -> str:
return f"['{self.name}']" if self.shorthand else f"'{self.name}'"
def __eq__(self, __value: object) -> bool:
return (
isinstance(__value, PropertySelector)
and self.name == __value.name
and self.token == __value.token
)
def __hash__(self) -> int:
return hash((self.name, self.token))
def resolve(self, matches: Iterable[JSONPathMatch]) -> Iterable[JSONPathMatch]:
for match in matches:
if not isinstance(match.obj, Mapping):
continue
with suppress(KeyError):
_match = self.env.match_class(
filter_context=match.filter_context(),
obj=self.env.getitem(match.obj, self.name),
parent=match,
parts=match.parts + (self.name,),
path=match.path + f"['{self.name}']",
root=match.root,
)
match.add_child(_match)
yield _match
async def resolve_async(
self, matches: AsyncIterable[JSONPathMatch]
) -> AsyncIterable[JSONPathMatch]:
async for match in matches:
if not isinstance(match.obj, Mapping):
continue
with suppress(KeyError):
_match = self.env.match_class(
filter_context=match.filter_context(),
obj=await self.env.getitem_async(match.obj, self.name),
parent=match,
parts=match.parts + (self.name,),
path=match.path + f"['{self.name}']",
root=match.root,
)
match.add_child(_match)
yield _match
class IndexSelector(JSONPathSelector):
"""Select an element from an array by index.
Considering we don't require mapping (JSON object) keys/properties to
be quoted, and that we support mappings with numeric keys, we also check
to see if the "index" is a mapping key, which is non-standard.
"""
__slots__ = ("index", "_as_key")
def __init__(
self,
*,
env: JSONPathEnvironment,
token: Token,
index: int,
) -> None:
if index < env.min_int_index or index > env.max_int_index:
raise JSONPathIndexError("index out of range", token=token)
super().__init__(env=env, token=token)
self.index = index
self._as_key = str(self.index)
def __str__(self) -> str:
return str(self.index)
def __eq__(self, __value: object) -> bool:
return (
isinstance(__value, IndexSelector)
and self.index == __value.index
and self.token == __value.token
)
def __hash__(self) -> int:
return hash((self.index, self.token))
def _normalized_index(self, obj: Sequence[object]) -> int:
if self.index < 0 and len(obj) >= abs(self.index):
return len(obj) + self.index
return self.index
def resolve(self, matches: Iterable[JSONPathMatch]) -> Iterable[JSONPathMatch]:
for match in matches:
if isinstance(match.obj, Mapping):
# Try the string representation of the index as a key.
with suppress(KeyError):
_match = self.env.match_class(
filter_context=match.filter_context(),
obj=self.env.getitem(match.obj, self._as_key),
parent=match,
parts=match.parts + (self._as_key,),
path=f"{match.path}['{self.index}']",
root=match.root,
)
match.add_child(_match)
yield _match
elif isinstance(match.obj, Sequence) and not isinstance(match.obj, str):
norm_index = self._normalized_index(match.obj)
with suppress(IndexError):
_match = self.env.match_class(
filter_context=match.filter_context(),
obj=self.env.getitem(match.obj, self.index),
parent=match,
parts=match.parts + (norm_index,),
path=match.path + f"[{norm_index}]",
root=match.root,
)
match.add_child(_match)
yield _match
async def resolve_async(
self, matches: AsyncIterable[JSONPathMatch]
) -> AsyncIterable[JSONPathMatch]:
async for match in matches:
if isinstance(match.obj, Mapping):
# Try the string representation of the index as a key.
with suppress(KeyError):
_match = self.env.match_class(
filter_context=match.filter_context(),
obj=await self.env.getitem_async(match.obj, self._as_key),
parent=match,
parts=match.parts + (self._as_key,),
path=f"{match.path}['{self.index}']",
root=match.root,
)
match.add_child(_match)
yield _match
elif isinstance(match.obj, Sequence) and not isinstance(match.obj, str):
norm_index = self._normalized_index(match.obj)
with suppress(IndexError):
_match = self.env.match_class(
filter_context=match.filter_context(),
obj=await self.env.getitem_async(match.obj, self.index),
parent=match,
parts=match.parts + (norm_index,),
path=match.path + f"[{norm_index}]",
root=match.root,
)
match.add_child(_match)
yield _match
class KeysSelector(JSONPathSelector):
"""Select mapping/object keys/properties.
NOTE: This is a non-standard selector.
"""
__slots__ = ("shorthand",)
def __init__(
self, *, env: JSONPathEnvironment, token: Token, shorthand: bool
) -> None:
super().__init__(env=env, token=token)
self.shorthand = shorthand
def __str__(self) -> str:
return (
f"[{self.env.keys_selector_token}]"
if self.shorthand
else self.env.keys_selector_token
)
def __eq__(self, __value: object) -> bool:
return isinstance(__value, KeysSelector) and self.token == __value.token
def __hash__(self) -> int:
return hash(self.token)
def _keys(self, match: JSONPathMatch) -> Iterable[JSONPathMatch]:
if isinstance(match.obj, Mapping):
for i, key in enumerate(match.obj.keys()):
_match = self.env.match_class(
filter_context=match.filter_context(),
obj=key,
parent=match,
parts=match.parts + (f"{self.env.keys_selector_token}{key}",),
path=f"{match.path}[{self.env.keys_selector_token}][{i}]",
root=match.root,
)
match.add_child(_match)
yield _match
def resolve(self, matches: Iterable[JSONPathMatch]) -> Iterable[JSONPathMatch]:
for match in matches:
yield from self._keys(match)
async def resolve_async(
self, matches: AsyncIterable[JSONPathMatch]
) -> AsyncIterable[JSONPathMatch]:
async for match in matches:
for _match in self._keys(match):
yield _match
class SliceSelector(JSONPathSelector):
"""Sequence slicing selector."""
__slots__ = ("slice",)
def __init__(
self,
*,
env: JSONPathEnvironment,
token: Token,
start: Optional[int] = None,
stop: Optional[int] = None,
step: Optional[int] = None,
) -> None:
super().__init__(env=env, token=token)
self._check_range(start, stop, step)
self.slice = slice(start, stop, step)
def __str__(self) -> str:
stop = self.slice.stop if self.slice.stop is not None else ""
start = self.slice.start if self.slice.start is not None else ""
step = self.slice.step if self.slice.step is not None else "1"
return f"{start}:{stop}:{step}"
def __eq__(self, __value: object) -> bool:
return (
isinstance(__value, SliceSelector)
and self.slice == __value.slice
and self.token == __value.token
)
def __hash__(self) -> int:
return hash((str(self), self.token))
def _check_range(self, *indices: Optional[int]) -> None:
for i in indices:
if i is not None and (
i < self.env.min_int_index or i > self.env.max_int_index
):
raise JSONPathIndexError("index out of range", token=self.token)
def _normalized_index(self, obj: Sequence[object], index: int) -> int:
if index < 0 and len(obj) >= abs(index):
return len(obj) + index
return index
def resolve(self, matches: Iterable[JSONPathMatch]) -> Iterable[JSONPathMatch]:
for match in matches:
if not isinstance(match.obj, Sequence) or self.slice.step == 0:
continue
idx = self.slice.start or 0
step = self.slice.step or 1
for obj in self.env.getitem(match.obj, self.slice):
norm_index = self._normalized_index(match.obj, idx)
_match = self.env.match_class(
filter_context=match.filter_context(),
obj=obj,
parent=match,
parts=match.parts + (norm_index,),
path=f"{match.path}[{norm_index}]",
root=match.root,
)
match.add_child(_match)
yield _match
idx += step
async def resolve_async(
self, matches: AsyncIterable[JSONPathMatch]
) -> AsyncIterable[JSONPathMatch]:
async for match in matches:
if not isinstance(match.obj, Sequence) or self.slice.step == 0:
continue
idx = self.slice.start or 0
step = self.slice.step or 1
for obj in await self.env.getitem_async(match.obj, self.slice):
norm_index = self._normalized_index(match.obj, idx)
_match = self.env.match_class(
filter_context=match.filter_context(),
obj=obj,
parent=match,
parts=match.parts + (norm_index,),
path=f"{match.path}[{norm_index}]",
root=match.root,
)
match.add_child(_match)
yield _match
idx += step
class WildSelector(JSONPathSelector):
"""Select all items from a sequence/array or values from a mapping/object."""
__slots__ = ("shorthand",)
def __init__(
self, *, env: JSONPathEnvironment, token: Token, shorthand: bool
) -> None:
super().__init__(env=env, token=token)
self.shorthand = shorthand
def __str__(self) -> str:
return "[*]" if self.shorthand else "*"
def __eq__(self, __value: object) -> bool:
return isinstance(__value, WildSelector) and self.token == __value.token
def __hash__(self) -> int:
return hash(self.token)
def resolve(self, matches: Iterable[JSONPathMatch]) -> Iterable[JSONPathMatch]:
for match in matches:
if isinstance(match.obj, str):
continue
if isinstance(match.obj, Mapping):
for key, val in match.obj.items():
_match = self.env.match_class(
filter_context=match.filter_context(),
obj=val,
parent=match,
parts=match.parts + (key,),
path=match.path + f"['{key}']",
root=match.root,
)
match.add_child(_match)
yield _match
elif isinstance(match.obj, Sequence):
for i, val in enumerate(match.obj):
_match = self.env.match_class(
filter_context=match.filter_context(),
obj=val,
parent=match,
parts=match.parts + (i,),
path=f"{match.path}[{i}]",
root=match.root,
)
match.add_child(_match)
yield _match
async def resolve_async(
self, matches: AsyncIterable[JSONPathMatch]
) -> AsyncIterable[JSONPathMatch]:
async for match in matches:
if isinstance(match.obj, Mapping):
for key, val in match.obj.items():
_match = self.env.match_class(
filter_context=match.filter_context(),
obj=val,
parent=match,
parts=match.parts + (key,),
path=match.path + f"['{key}']",
root=match.root,
)
match.add_child(_match)
yield _match
elif isinstance(match.obj, Sequence):
for i, val in enumerate(match.obj):
_match = self.env.match_class(
filter_context=match.filter_context(),
obj=val,
parent=match,
parts=match.parts + (i,),
path=f"{match.path}[{i}]",
root=match.root,
)
match.add_child(_match)
yield _match
class RecursiveDescentSelector(JSONPathSelector):
"""A JSONPath selector that visits all nodes recursively.
NOTE: Strictly this is a "segment", not a "selector".
"""
def __str__(self) -> str:
return ".."
def __eq__(self, __value: object) -> bool:
return (
isinstance(__value, RecursiveDescentSelector)
and self.token == __value.token
)
def __hash__(self) -> int:
return hash(self.token)
def _expand(self, match: JSONPathMatch) -> Iterable[JSONPathMatch]:
if isinstance(match.obj, Mapping):
for key, val in match.obj.items():
if isinstance(val, str):
pass
elif isinstance(val, (Mapping, Sequence)):
_match = self.env.match_class(
filter_context=match.filter_context(),
obj=val,
parent=match,
parts=match.parts + (key,),
path=match.path + f"['{key}']",
root=match.root,
)
match.add_child(_match)
yield _match
yield from self._expand(_match)
elif isinstance(match.obj, Sequence) and not isinstance(match.obj, str):
for i, val in enumerate(match.obj):
if isinstance(val, str):
pass
elif isinstance(val, (Mapping, Sequence)):
_match = self.env.match_class(
filter_context=match.filter_context(),
obj=val,
parent=match,
parts=match.parts + (i,),
path=f"{match.path}[{i}]",
root=match.root,
)
match.add_child(_match)
yield _match
yield from self._expand(_match)
def resolve(self, matches: Iterable[JSONPathMatch]) -> Iterable[JSONPathMatch]:
for match in matches:
yield match
yield from self._expand(match)
async def resolve_async(
self, matches: AsyncIterable[JSONPathMatch]
) -> AsyncIterable[JSONPathMatch]:
async for match in matches:
yield match
for _match in self._expand(match):
yield _match
T = TypeVar("T")
async def _alist(it: List[T]) -> AsyncIterable[T]:
for item in it:
yield item
class ListSelector(JSONPathSelector):
"""A bracketed list of selectors, the results of which are concatenated together.
NOTE: Strictly this is a "segment", not a "selector".
"""
__slots__ = ("items",)
def __init__(
self,
*,
env: JSONPathEnvironment,
token: Token,
items: List[
Union[
SliceSelector,
KeysSelector,
IndexSelector,
PropertySelector,
WildSelector,
Filter,
]
],
) -> None:
super().__init__(env=env, token=token)
self.items = tuple(items)
def __str__(self) -> str:
return f"[{', '.join(str(itm) for itm in self.items)}]"
def __eq__(self, __value: object) -> bool:
return (
isinstance(__value, ListSelector)
and self.items == __value.items
and self.token == __value.token
)
def __hash__(self) -> int:
return hash((self.items, self.token))
def resolve(self, matches: Iterable[JSONPathMatch]) -> Iterable[JSONPathMatch]:
for match_ in matches:
for item in self.items:
yield from item.resolve([match_])
async def resolve_async(
self, matches: AsyncIterable[JSONPathMatch]
) -> AsyncIterable[JSONPathMatch]:
async for match_ in matches:
for item in self.items:
async for m in item.resolve_async(_alist([match_])):
yield m
class Filter(JSONPathSelector):
"""Filter sequence/array items or mapping/object values with a filter expression."""
__slots__ = ("expression", "cacheable_nodes")
def __init__(
self,
*,
env: JSONPathEnvironment,
token: Token,
expression: BooleanExpression,
) -> None:
super().__init__(env=env, token=token)
self.expression = expression
# Compile-time check for cacheable nodes.
self.cacheable_nodes = self.expression.cacheable_nodes()
def __str__(self) -> str:
return f"?{self.expression}"
def __eq__(self, __value: object) -> bool:
return (
isinstance(__value, Filter)
and self.expression == __value.expression
and self.token == __value.token
)
def __hash__(self) -> int:
return hash((str(self.expression), self.token))
def resolve( # noqa: PLR0912
self, matches: Iterable[JSONPathMatch]
) -> Iterable[JSONPathMatch]:
if self.cacheable_nodes and self.env.filter_caching:
expr = self.expression.cache_tree()
else:
expr = self.expression
for match in matches:
if isinstance(match.obj, Mapping):
for key, val in match.obj.items():
context = FilterContext(
env=self.env,
current=val,
root=match.root,
extra_context=match.filter_context(),
current_key=key,
)
try:
if expr.evaluate(context):
_match = self.env.match_class(
filter_context=match.filter_context(),
obj=val,
parent=match,
parts=match.parts + (key,),
path=match.path + f"['{key}']",
root=match.root,
)
match.add_child(_match)
yield _match
except JSONPathTypeError as err:
if not err.token:
err.token = self.token
raise
elif isinstance(match.obj, Sequence) and not isinstance(match.obj, str):
for i, obj in enumerate(match.obj):
context = FilterContext(
env=self.env,
current=obj,
root=match.root,
extra_context=match.filter_context(),
current_key=i,
)
try:
if expr.evaluate(context):
_match = self.env.match_class(
filter_context=match.filter_context(),
obj=obj,
parent=match,
parts=match.parts + (i,),
path=f"{match.path}[{i}]",
root=match.root,
)
match.add_child(_match)
yield _match
except JSONPathTypeError as err:
if not err.token:
err.token = self.token
raise
async def resolve_async( # noqa: PLR0912
self, matches: AsyncIterable[JSONPathMatch]
) -> AsyncIterable[JSONPathMatch]:
if self.cacheable_nodes and self.env.filter_caching:
expr = self.expression.cache_tree()
else:
expr = self.expression
async for match in matches:
if isinstance(match.obj, Mapping):
for key, val in match.obj.items():
context = FilterContext(
env=self.env,
current=val,
root=match.root,
extra_context=match.filter_context(),
current_key=key,
)
try:
result = await expr.evaluate_async(context)
except JSONPathTypeError as err:
if not err.token:
err.token = self.token
raise
if result:
_match = self.env.match_class(
filter_context=match.filter_context(),
obj=val,
parent=match,
parts=match.parts + (key,),
path=match.path + f"['{key}']",
root=match.root,
)
match.add_child(_match)
yield _match
elif isinstance(match.obj, Sequence) and not isinstance(match.obj, str):
for i, obj in enumerate(match.obj):
context = FilterContext(
env=self.env,
current=obj,
root=match.root,
extra_context=match.filter_context(),
current_key=i,
)
try:
result = await expr.evaluate_async(context)
except JSONPathTypeError as err:
if not err.token:
err.token = self.token
raise
if result:
_match = self.env.match_class(
filter_context=match.filter_context(),
obj=obj,
parent=match,
parts=match.parts + (i,),
path=f"{match.path}[{i}]",
root=match.root,
)
match.add_child(_match)
yield _match
class FilterContext:
"""Contextual information and data for evaluating a filter expression."""
__slots__ = (
"current_key",
"current",
"env",
"extra_context",
"root",
)
def __init__(
self,
*,
env: JSONPathEnvironment,
current: object,
root: Union[Sequence[Any], Mapping[str, Any]],
extra_context: Optional[Mapping[str, Any]] = None,
current_key: Union[str, int, None] = None,
) -> None:
self.env = env
self.current = current
self.root = root
self.extra_context = extra_context or {}
self.current_key = current_key
def __str__(self) -> str:
return (
f"FilterContext(current={self.current}, "
f"extra_context={self.extra_context!r})"
)