Coverage for src/governed_harness/ladder/jsonpath.py: 91%

65 statements  

« prev     ^ index     » next       coverage.py v7.17.2, created at 2026-11-12 16:06 +0000

1"""A small, deterministic subset of JSONPath for probe assertions. 

2 

3Supported: ``$`` (the document), ``.name`` and ``['name']`` (a member), ``[N]`` (an index, 

4negative from the end), ``[*]`` and ``.*`` (every element or member value, in order). Nothing 

5else: no filters, no recursive descent, no scripts. ``select`` returns the matches in document 

6order; a path that matches nothing returns an empty list.""" 

7 

8from __future__ import annotations 

9 

10import re 

11from dataclasses import dataclass 

12from typing import Any 

13 

14_NAME = re.compile(r"[A-Za-z_][A-Za-z0-9_-]*") 

15_INDEX = re.compile(r"-?\d+") 

16 

17 

18@dataclass(frozen=True) 

19class Step: 

20 kind: str # "member", "index" or "wildcard" 

21 name: str = "" 

22 index: int = 0 

23 

24 

25def parse_path(path: str) -> tuple[Step, ...]: 

26 """The steps of ``path``; a path outside the subset raises ``ValueError``.""" 

27 text = path.strip() 

28 if not text.startswith("$"): 

29 raise ValueError(f"a JSON path starts with $: {path!r}") 

30 steps: list[Step] = [] 

31 position = 1 

32 while position < len(text): 

33 char = text[position] 

34 if char == ".": 

35 step, position = _dot_step(text, position + 1, path) 

36 elif char == "[": 36 ↛ 39line 36 didn't jump to line 39 because the condition on line 36 was always true

37 step, position = _bracket_step(text, position, path) 

38 else: 

39 raise ValueError(f"unexpected {char!r} at {position} in {path!r}") 

40 steps.append(step) 

41 return tuple(steps) 

42 

43 

44def _dot_step(text: str, position: int, path: str) -> tuple[Step, int]: 

45 """``.*`` or ``.name`` after the dot at ``position - 1``: the step and where it ends.""" 

46 if position < len(text) and text[position] == "*": 

47 return Step("wildcard"), position + 1 

48 match = _NAME.match(text, position) 

49 if match is None: 

50 raise ValueError(f"expected a member name at {position} in {path!r}") 

51 return Step("member", name=match.group(0)), match.end() 

52 

53 

54def _bracket_step(text: str, position: int, path: str) -> tuple[Step, int]: 

55 """``[*]``, ``['name']`` or ``[N]`` from the bracket at ``position``.""" 

56 end = text.find("]", position) 

57 if end < 0: 57 ↛ 58line 57 didn't jump to line 58 because the condition on line 57 was never true

58 raise ValueError(f"unclosed [ in {path!r}") 

59 inner = text[position + 1 : end].strip() 

60 if inner == "*": 

61 return Step("wildcard"), end + 1 

62 if len(inner) >= 2 and inner[0] == inner[-1] and inner[0] in {"'", '"'}: 

63 return Step("member", name=inner[1:-1]), end + 1 

64 if _INDEX.fullmatch(inner): 

65 return Step("index", index=int(inner)), end + 1 

66 raise ValueError(f"unsupported selector [{inner}] in {path!r}") 

67 

68 

69def _children(value: Any, step: Step) -> list[Any]: 

70 """What one step selects in one value.""" 

71 if step.kind == "member": 

72 return [value[step.name]] if isinstance(value, dict) and step.name in value else [] 

73 if step.kind == "index": 

74 if isinstance(value, list) and -len(value) <= step.index < len(value): 74 ↛ 76line 74 didn't jump to line 76 because the condition on line 74 was always true

75 return [value[step.index]] 

76 return [] 

77 if isinstance(value, list): 

78 return list(value) 

79 if isinstance(value, dict): 79 ↛ 81line 79 didn't jump to line 81 because the condition on line 79 was always true

80 return [value[key] for key in value] 

81 return [] 

82 

83 

84def select(document: Any, path: str) -> list[Any]: 

85 """Every value ``path`` selects in ``document``, in document order.""" 

86 current = [document] 

87 for step in parse_path(path): 

88 current = [child for value in current for child in _children(value, step)] 

89 return current 

90 

91 

92def has_wildcard(path: str) -> bool: 

93 return any(step.kind == "wildcard" for step in parse_path(path)) 

94 

95 

96__all__ = ["Step", "has_wildcard", "parse_path", "select"]