"""Lazy evaluation boundary and lexical environment."""
from collections.abc import Iterator, Mapping
from dataclasses import dataclass, field
from functools import cmp_to_key
import json
import math
import os
import sys
import time
from decimal import Decimal
from typing import Any
from .builtins import (builtin_indices, builtin_join, builtin_regex, builtin_split,
builtin_tostring,
builtin_format, default_builtins, _nondecnum, _value_description,
_parse_strptime, json_text)
from .errors import RuntimeError
from .parser import Node, Program
class _BreakSignal(Exception):
"""Internal non-local control transfer for a lexical jq label."""
def __init__(self, label: str):
self.label = label
@dataclass(frozen=True, slots=True)
class Environment:
"""An immutable lexical frame with an optional enclosing environment."""
bindings: Mapping[str, Any] = field(default_factory=dict)
parent: "Environment | None" = None
functions: Mapping[tuple[str, int], Any] = field(default_factory=dict)
runtime: "RuntimeContext | None" = None
def get(self, name: str, default: Any = None) -> Any:
if name in self.bindings:
return self.bindings[name]
if self.parent is not None:
return self.parent.get(name, default)
return default
def child(self, **bindings: Any) -> "Environment":
return Environment(bindings=dict(bindings), parent=self, functions=self.functions, runtime=self.runtime)
def with_function(self, key: tuple[str, int], function: Any) -> "Environment":
functions = dict(self.functions)
functions[key] = function
return Environment(bindings={}, parent=self, functions=functions, runtime=self.runtime)
def function(self, name: str, arity: int) -> Any:
if (name, arity) in self.functions:
return self.functions[(name, arity)]
if self.parent is not None:
return self.parent.function(name, arity)
return None
@dataclass
class Function:
name: str
params: tuple[str, ...]
body: Node
closure: Environment | None = None
@dataclass
class RuntimeContext:
"""Invocation state shared by every input record evaluation."""
records: Iterator[Any]
stderr: Any = sys.stderr
startup_environment: Mapping[str, str] = field(default_factory=lambda: dict(os.environ))
def next_input(self) -> Any:
try:
return next(self.records)
except StopIteration as exc:
raise RuntimeError("break") from exc
def remaining(self) -> Iterator[Any]:
yield from self.records
def write_debug(self, value: Any) -> None:
self.stderr.write(json_text(["DEBUG:", value]) + "\n")
def write_raw(self, value: Any) -> None:
self.stderr.write(json_text(value))
def evaluate(
ast: Program, value: Any, environment: Environment | None = None
) -> Iterator[Any]:
"""Return a lazy result stream for an AST."""
if not isinstance(ast, Program) or ast.tree is None:
return iter(())
env = environment or Environment()
def visit(node: Node, current: Any, scope: Environment) -> Iterator[Any]:
if node.kind == "program":
active = scope
for directive in node.children[:-1]:
if directive.kind == "function":
active = define_function(directive, active)
yield from visit(node.children[-1], current, active)
elif node.kind == "def":
active = define_function(node.children[0], scope)
yield from visit(node.children[1], current, active)
elif node.kind == "dot":
yield current
elif node.kind == "recurse":
# ``..`` is recurse(.[]?), with the same depth-first ordering as
# the library definition of recurse.
yield current
if isinstance(current, list):
for child in current:
yield from visit(Node("recurse"), child, scope)
elif isinstance(current, dict):
for child in current.values():
yield from visit(Node("recurse"), child, scope)
elif node.kind == "literal":
yield node.value
elif node.kind == "null":
yield None
elif node.kind == "variable":
yield scope.get(node.value)
elif node.kind == "env_variable":
runtime = scope.runtime
yield dict(runtime.startup_environment if runtime is not None else os.environ)
elif node.kind == "loc":
yield {"file": node.value[0], "line": node.value[1]}
elif node.kind == "filter_param":
bound = scope.get("@" + node.value, _MISSING)
if not isinstance(bound, FilterArgument):
raise RuntimeError(f"unknown filter parameter {node.value}")
yield from visit(bound.node, current, bound.scope)
elif node.kind == "bind":
source, pattern, downstream = node.children
patterns = pattern.children if pattern.kind == "pattern_alt" else (pattern,)
for source_value in visit(source, current, scope):
for candidate in patterns:
try:
bindings = match_pattern(candidate, source_value, scope, visit, current)
except RuntimeError:
continue
yield from visit(downstream, current, scope.child(**bindings))
break
elif node.kind == "string":
values = [""]
for part in node.children:
pieces = list(visit(part, current, scope))
if node.value is None:
values = [prefix + _stringify(piece) for prefix in values for piece in pieces]
elif part.kind == "literal":
# In @format "...", literal text is template syntax and is
# deliberately left untouched; only interpolated results are escaped.
values = [prefix + _stringify(piece) for prefix in values for piece in pieces]
else:
values = [prefix + builtin_format(piece, node.value) for prefix in values for piece in pieces]
yield from values
elif node.kind == "format":
for piece in visit(node.children[0], current, scope):
yield builtin_format(piece, node.value)
elif node.kind == "negate":
for operand in visit(node.children[0], current, scope):
try:
yield (-operand if isinstance(operand, Decimal)
else -_nondecnum(operand) if _is_number(operand) else -operand)
except (TypeError, ValueError) as exc:
raise RuntimeError(f"{_value_description(operand)} cannot be negated") from exc
elif node.kind == "binary":
yield from _binary(node.value, node.children[0], node.children[1], current, scope, visit)
elif node.kind == "comma":
yield from visit(node.children[0], current, scope)
yield from visit(node.children[1], current, scope)
elif node.kind == "pipe":
for intermediate in visit(node.children[0], current, scope):
yield from visit(node.children[1], intermediate, scope)
elif node.kind == "array":
values: list[Any] = []
if node.children:
values.extend(visit(node.children[0], current, scope))
yield values
elif node.kind == "object":
objects: list[dict[str, Any]] = [{}]
for pair in node.children:
key_node, value_node = pair.children
keys = list(visit(key_node, current, scope))
values = list(visit(value_node, current, scope))
expanded: list[dict[str, Any]] = []
for partial in objects:
for key in keys:
if not isinstance(key, str):
raise RuntimeError("object keys must be strings")
for value in values:
result = dict(partial)
result[key] = value
expanded.append(result)
objects = expanded
yield from objects
elif node.kind == "index":
for base in visit(node.children[0], current, scope):
# The index expression is evaluated against the input to the
# containing filter, not against the value being indexed.
for key in visit(node.children[1], current, scope):
yield _index(base, key)
elif node.kind == "each":
for base in visit(node.children[0], current, scope):
if isinstance(base, list):
yield from base
elif isinstance(base, dict):
yield from base.values()
else:
raise RuntimeError(f"Cannot iterate over {_type_label(base)} ({json_text(base)})")
elif node.kind == "slice":
for base in visit(node.children[0], current, scope):
starts = list(visit(node.children[1], base, scope))
# Slice bounds are filters over the containing input, just as
# bracket indexes are; `.[0:.]` therefore sees the outer
# value rather than the sliced constant.
ends = list(visit(node.children[2], current, scope))
for start in starts:
for end in ends:
yield _slice(base, start, end)
elif node.kind == "if":
# The condition is a generator: each condition result selects a branch
# independently, and an empty condition produces no result.
def select(condition_index: int) -> Iterator[Any]:
condition = node.children[condition_index]
then_branch = node.children[condition_index + 1]
next_condition = condition_index + 2
for condition_value in visit(condition, current, scope):
if _truthy(condition_value):
yield from visit(then_branch, current, scope)
elif next_condition < len(node.children) - 1:
yield from select(next_condition)
else:
yield from visit(node.children[-1], current, scope)
yield from select(0)
elif node.kind == "optional":
try:
yield from visit(node.children[0], current, scope)
except RuntimeError:
return
elif node.kind == "label":
try:
yield from visit(node.children[0], current, scope)
except _BreakSignal as signal:
if signal.label != node.value:
raise
elif node.kind == "break":
raise _BreakSignal(node.value)
elif node.kind in {"reduce", "foreach"}:
stream, pattern, initial, update, extraction = node.children
if node.kind == "foreach":
# Each initializer is an independent foreach branch. jq
# exhausts the input stream for the first accumulator before
# advancing the next one (reduce, below, combines them per
# input item).
for accumulator in visit(initial, current, scope):
state = accumulator
for source_value in visit(stream, current, scope):
try:
bindings = match_pattern(pattern, source_value)
except RuntimeError:
continue
item_scope = scope.child(**bindings)
updates = list(visit(update, state, item_scope))
if not updates:
continue
state = updates[0]
if extraction.kind == "identity":
yield state
else:
yield from visit(extraction, state, item_scope)
return
# Keep each initializer result as an independent accumulator. A
# source is consumed only as the accumulators need advancing.
accumulators = list(visit(initial, current, scope))
for source_value in visit(stream, current, scope):
next_accumulators: list[Any] = []
for accumulator in accumulators:
try:
bindings = match_pattern(pattern, source_value)
except RuntimeError:
continue
item_scope = scope.child(**bindings)
for updated in visit(update, accumulator, item_scope):
next_accumulators.append(updated)
if node.kind == "foreach":
if extraction.kind == "identity":
yield updated
else:
yield from visit(extraction, updated, item_scope)
accumulators = next_accumulators
if node.kind == "reduce":
yield from accumulators
elif node.kind == "try":
try:
yield from visit(node.children[0], current, scope)
except RuntimeError as exc:
if node.children[1].kind == "backtrack":
return
yield from visit(node.children[1], exc.value, scope)
elif node.kind == "call":
name, arity = node.value
bound = scope.get(name, _MISSING)
if isinstance(bound, FilterArgument):
yield from visit(bound.node, current, bound.scope)
return
if name == "empty":
return
if name in {"first", "last"} and arity in {0, 1}:
source = node.children[0] if arity else Node("dot")
results = visit(source, current, scope)
if name == "first":
try:
yield next(results)
except StopIteration:
return
else:
found = False
last_value = None
for result in results:
found, last_value = True, result
if found:
yield last_value
return
if name in {"limit", "skip", "nth"}:
required = 2
if arity != required:
raise RuntimeError(f"{name} requires two arguments")
count_values = visit(node.children[0], current, scope)
source_node = node.children[1]
for count in count_values:
if not isinstance(count, int) or isinstance(count, bool):
raise RuntimeError(f"{name} count must be an integer")
if count < 0:
if name == "nth":
raise RuntimeError("nth doesn't support negative indices")
raise RuntimeError(f"{name} doesn't support negative count")
if name == "limit" and count == 0:
continue
results = visit(source_node, current, scope)
if name == "limit":
for _ in range(count):
try:
yield next(results)
except StopIteration:
break
else:
for _ in range(count):
try:
next(results)
except StopIteration:
break
if name == "nth":
try:
yield next(results)
except StopIteration:
pass
else:
yield from results
return
if name == "select" and arity == 1:
for candidate in visit(node.children[0], current, scope):
if _truthy(candidate):
yield current
return
if name == "IN" and arity in {1, 2}:
if arity == 1:
candidates = list(visit(node.children[0], current, scope))
yield any(_equal(candidate, current) for candidate in candidates)
else:
left = list(visit(node.children[0], current, scope))
right = list(visit(node.children[1], current, scope))
yield any(_equal(candidate, other) for candidate in left for other in right)
return
if name == "INDEX" and arity in {1, 2}:
import itertools
sources = (Node("each", children=(Node("dot"),)) if arity == 1
else node.children[0])
source_values = list(visit(sources, current, scope))
index_values = []
for row in source_values:
keys = list(visit(node.children[-1], row, scope))
index_values.append((row, keys))
# Filter arguments can themselves be generators; each
# combination is an independent reduce result.
combinations = itertools.product(*(keys for _, keys in index_values)) if index_values else [()]
for _ in combinations:
indexed: dict[str, Any] = {}
for (row, keys), chosen in zip(index_values, _):
indexed[builtin_tostring(chosen)] = row
yield indexed
return
if name == "JOIN" and arity in {2, 3, 4}:
import itertools
index_values = list(visit(node.children[0], current, scope))
if arity == 2:
stream_values = list(visit(Node("each", children=(Node("dot"),)), current, scope))
else:
stream_values = list(visit(node.children[1], current, scope))
pairs = []
for row, index in itertools.product(stream_values, index_values):
keys = list(visit(node.children[1 if arity == 2 else 2], row, scope))
for key in keys:
pairs.append([row, index.get(builtin_tostring(key)) if isinstance(index, dict) else None])
if arity == 2:
yield pairs
elif arity == 3:
yield from pairs
else:
for pair in pairs:
yield from visit(node.children[3], pair, scope)
return
if name == "recurse" and arity in {0, 1, 2}:
# recurse(f) and recurse(f; condition) are deliberately kept
# lazy: a descendant is expanded only after its parent has
# been yielded, and every result of f gets its own branch.
def descend(item: Any) -> Iterator[Any]:
yield item
if arity == 0:
if isinstance(item, list):
children = iter(item)
elif isinstance(item, dict):
children = iter(item.values())
else:
children = iter(())
for child in children:
yield from descend(child)
return
for child in visit(node.children[0], item, scope):
if arity == 2:
allowed = any(_truthy(value) for value in visit(node.children[1], child, scope))
if not allowed:
continue
yield from descend(child)
yield from descend(current)
return
if name in {"while", "until"} and arity == 2:
condition, update = node.children
item = current
while True:
passed = any(_truthy(value) for value in visit(condition, item, scope))
if name == "while":
if not passed:
return
yield item
elif passed:
yield item
return
updates = list(visit(update, item, scope))
if not updates:
return
# jq's definitions continue each update branch. The common
# corpus form is single-valued; retain all branches lazily.
if len(updates) == 1:
item = updates[0]
else:
for branch in updates:
yield from visit(Node("call", (name, 2), node.children), branch, scope)
return
return
if name == "isempty" and arity == 1:
stream = visit(node.children[0], current, scope)
try:
next(stream)
except StopIteration:
yield True
else:
yield False
return
if name == "walk" and arity in {1, 2}:
# The second argument is accepted by jq's internal walk
# definition as an implementation detail; it is a filter
# applied to the root after the recursive traversal.
def walked(item: Any) -> Iterator[Any]:
if isinstance(item, list):
values: list[Any] = []
for child in item:
values.extend(walked(child))
candidates: list[Any] = [values]
elif isinstance(item, dict):
variants: list[dict[str, Any]] = [{}]
for key, child in item.items():
# map_values, which underlies jq's walk for
# objects, retains only the first result for a
# value and drops the key when the filter is
# empty. Arrays intentionally preserve all
# results through map.
updated = list(walked(child))
if not updated:
continue
variants = [dict(partial, **{key: updated[0]})
for partial in variants]
candidates = variants
else:
candidates = [item]
for candidate in candidates:
yield from visit(node.children[0], candidate, scope)
outputs = walked(current)
if arity == 2:
for item in outputs:
yield from visit(node.children[1], item, scope)
else:
yield from outputs
return
if name == "tostream" and arity == 0:
yield from _to_stream(current)
return
if name == "truncate_stream" and arity == 1:
if not isinstance(current, int) or isinstance(current, bool) or current < 0:
raise RuntimeError("truncate_stream requires a non-negative integer")
for event in visit(node.children[0], current, scope):
if not isinstance(event, list) or not event or not isinstance(event[0], list):
raise RuntimeError("truncated stream must contain path events")
path = event[0][current:]
if path:
yield [path, *event[1:]]
return
if name == "fromstream" and arity == 1:
yield from _from_stream(visit(node.children[0], current, scope))
return
if name == "range" and arity in {1, 2, 3}:
import itertools
args = list(_cartesian_arguments(node.children, current, scope, visit))
for values in args:
range_values = (values,) if arity == 1 else values
start, stop = (0, range_values[0]) if arity == 1 else (range_values[0], range_values[1])
step = range_values[2] if arity == 3 else 1
if not all(_is_number(item) for item in range_values) or step == 0:
raise RuntimeError("range arguments must be numbers")
current_value = start
while (step > 0 and current_value < stop) or (step < 0 and current_value > stop):
yield _nondecnum(current_value)
current_value += step
return
if name == "map" and arity == 1:
if not isinstance(current, list):
raise RuntimeError("Cannot iterate over null (null)")
mapped: list[Any] = []
for item in current:
mapped.extend(visit(node.children[0], item, scope))
yield mapped
return
if name == "map_values" and arity == 1:
if isinstance(current, list):
output = []
for item in current:
updates = list(visit(node.children[0], item, scope))
if updates:
output.append(updates[0])
yield output
elif isinstance(current, dict):
output = {}
for key, item in current.items():
updates = list(visit(node.children[0], item, scope))
if updates:
output[key] = updates[0]
yield output
else:
raise RuntimeError("Cannot iterate over null (null)")
return
if name in {"arrays", "objects", "iterables", "booleans", "numbers",
"strings", "nulls", "values", "scalars"} and arity == 0:
matches = {
"arrays": isinstance(current, list), "objects": isinstance(current, dict),
"iterables": isinstance(current, (list, dict)),
"booleans": isinstance(current, bool), "numbers": _is_number(current),
"strings": isinstance(current, str), "nulls": current is None,
"values": current is not None, "scalars": not isinstance(current, (list, dict)),
}
if matches[name]:
yield current
return
if name in {"keys", "keys_unsorted"} and arity == 0:
if isinstance(current, dict):
keys = list(current)
if name == "keys": keys.sort()
yield keys
elif isinstance(current, list):
yield list(range(len(current)))
else:
raise RuntimeError(f"{_type_label(current)} has no keys")
return
if name == "has" and arity == 1:
for key in visit(node.children[0], current, scope):
if isinstance(current, dict):
if not isinstance(key, str): raise RuntimeError("Cannot check object key with non-string")
yield key in current
elif isinstance(current, list):
yield isinstance(key, int) and not isinstance(key, bool) and 0 <= key < len(current)
elif current is None:
yield False
else:
raise RuntimeError("Cannot check whether a value has a key")
return
if name in {"sort", "unique", "min", "max", "reverse", "to_entries", "from_entries", "transpose"} and arity == 0:
yield from _collection_zero_arg(name, current)
return
if name == "with_entries" and arity == 1:
if not isinstance(current, dict): raise RuntimeError("Cannot convert to entries")
entries = [{"key": key, "value": item} for key, item in current.items()]
output = {}
for entry in entries:
for updated in visit(node.children[0], entry, scope):
if not isinstance(updated, dict): raise RuntimeError("Cannot convert from entries")
key = next((updated[k] for k in ("key", "Key", "name", "Name") if k in updated), None)
val = next((updated[k] for k in ("value", "Value") if k in updated), None)
if not isinstance(key, str): raise RuntimeError("Cannot convert from entries")
output[key] = val
yield output
return
if name in {"sort_by", "unique_by", "group_by", "min_by", "max_by"} and arity == 1:
yield from _collection_by(name, current, node.children[0], scope, visit)
return
if name == "contains" and arity == 1:
for needle in visit(node.children[0], current, scope):
yield _contains(current, needle)
return
if name == "inside" and arity == 1:
for haystack in visit(node.children[0], current, scope):
yield _contains(haystack, current)
return
if name == "flatten" and arity in {0, 1}:
depths = [-1] if arity == 0 else list(visit(node.children[0], current, scope))
for depth in depths:
if not isinstance(depth, int) or isinstance(depth, bool): raise RuntimeError("flatten depth must be a number")
if depth < 0 and arity: raise RuntimeError("flatten depth must not be negative")
yield _flatten(current, depth)
return
if name == "transpose" and arity == 0:
if not isinstance(current, list): raise RuntimeError("transpose input must be an array")
width = max((len(row) for row in current if isinstance(row, list)), default=0)
yield [[row[index] if isinstance(row, list) and index < len(row) else None for row in current] for index in range(width)]
return
if name == "combinations" and arity in {0, 1}:
arrays = current if arity == 0 else [current] * next(iter(visit(node.children[0], current, scope)), 0)
if not isinstance(arrays, list) or any(not isinstance(item, list) for item in arrays):
raise RuntimeError("Cannot generate combinations from this value")
import itertools
yield from (list(combo) for combo in itertools.product(*arrays))
return
if name == "in" and arity == 1:
for container in visit(node.children[0], current, scope):
if isinstance(container, dict): yield current in container
elif isinstance(container, list): yield isinstance(current, int) and current >= 0 and current < len(container)
else: raise RuntimeError("Cannot check containment in this value")
return
if name == "bsearch" and arity >= 1:
if not isinstance(current, list): raise RuntimeError(f"{_type_label(current)} ({json_text(current)}) cannot be searched from")
for needle in _cartesian_arguments(node.children, current, scope, visit):
low, high = 0, len(current)
while low < high:
middle = (low + high) // 2
if _compare(current[middle], needle) < 0: low = middle + 1
else: high = middle
yield low if low < len(current) and _equal(current[low], needle) else -low - 1
return
if name == "_strindices" and arity == 1:
for needle in visit(node.children[0], current, scope):
if not isinstance(current, str):
raise RuntimeError(f"{_type_label(current)} ({json_text(current)}) cannot be searched, as it is not a string")
if not isinstance(needle, str):
raise RuntimeError(f"{_type_label(needle)} ({json_text(needle)}) is not a string")
yield builtin_indices(current, needle)
return
if name == "add" and arity in {0, 1, 2}:
streams = ([Node("each", children=(Node("dot"),))] if arity == 0 else list(node.children))
values = []
for stream in streams: values.extend(visit(stream, current, scope))
total = None
for item in values: total = _apply_operator("+", total, item)
yield total
return
if name in {"any", "all"} and arity in {0, 1, 2}:
if arity == 0: source, condition = Node("each", children=(Node("dot"),)), Node("dot")
elif arity == 1: source, condition = Node("each", children=(Node("dot"),)), node.children[0]
else: source, condition = node.children
wanted = name == "any"
answer = not wanted
for item in visit(source, current, scope):
for candidate in visit(condition, item, scope):
if _truthy(candidate) == wanted:
yield wanted
return
yield answer
return
if name == "not" and arity == 0:
yield not _truthy(current)
return
if name == "error":
if not node.children:
raise RuntimeError(current)
for argument in visit(node.children[0], current, scope):
raise RuntimeError(argument)
return
if name in {"input", "inputs"} and arity == 0:
runtime = scope.runtime
if runtime is None:
if name == "inputs":
return
raise RuntimeError("break")
if name == "inputs":
yield from runtime.remaining()
else:
yield runtime.next_input()
return
if name == "env" and arity == 0:
yield dict(os.environ)
return
if name == "debug" and arity in {0, 1}:
values = (visit(node.children[0], current, scope) if arity else iter((current,)))
for value in values:
runtime = scope.runtime
if runtime is not None:
runtime.write_debug(value)
yield value
return
if name == "stderr" and arity == 0:
runtime = scope.runtime
if runtime is not None:
runtime.write_raw(current)
yield current
return
if name in {"startswith", "endswith", "ltrimstr", "rtrimstr", "trimstr", "join", "split", "indices", "index", "rindex"} and arity == 1:
for argument in visit(node.children[0], current, scope):
if name == "startswith":
yield current.startswith(argument) if isinstance(current, str) and isinstance(argument, str) else (_raise_runtime("startswith() requires string inputs"))
elif name == "endswith":
yield current.endswith(argument) if isinstance(current, str) and isinstance(argument, str) else (_raise_runtime("endswith() requires string inputs"))
elif name in {"ltrimstr", "rtrimstr", "trimstr"}:
if not isinstance(current, str) or not isinstance(argument, str):
_raise_runtime("startswith() requires string inputs" if name == "ltrimstr" else "endswith() requires string inputs")
value = current[len(argument):] if name in {"ltrimstr", "trimstr"} and current.startswith(argument) else current
if name == "rtrimstr" or name == "trimstr":
value = value[:-len(argument)] if argument and value.endswith(argument) else value
yield value
elif name == "join":
yield builtin_join(current, argument)
elif name == "split":
yield builtin_split(current, argument)
else:
positions = builtin_indices(current, argument)
if name == "index" and isinstance(current, str) and argument == "":
yield None
else:
yield (positions[0] if name == "index" and positions else positions[-1] if name == "rindex" and positions else None if name in {"index", "rindex"} else positions)
return
if name in {"split", "indices", "index", "rindex"} and arity == 2:
# Two-argument split is regex-based; flags are the second argument.
arguments = _cartesian_arguments(node.children, current, scope, visit)
for separator, flags in arguments:
if name == "split":
matches = builtin_regex(current, separator, ("" if flags is None else flags) + "g")
yield _regex_split(current, matches)
else:
yield builtin_indices(current, separator)
return
if name in {"test", "match", "capture", "scan"} and arity in {1, 2}:
for arguments in _cartesian_arguments(node.children, current, scope, visit):
values = [arguments] if arity == 1 else arguments
pattern = values[0]
flags = values[1] if len(values) > 1 else None
matches = builtin_regex(current, pattern, flags)
if name == "test": yield bool(matches)
elif name == "match":
for match in matches:
yield {key: value for key, value in match.items() if key != "_match"}
elif name == "capture":
if matches:
yield {capture["name"]: capture["string"] for capture in matches[0]["captures"] if capture["name"] is not None}
else:
for match in matches:
captures = match["captures"]
yield [c["string"] for c in captures] if captures else match["string"]
return
if name in {"sub", "gsub"} and arity in {2, 3}:
pattern_values = list(visit(node.children[0], current, scope))
flag_values = list(visit(node.children[2], current, scope)) if arity == 3 else [""]
for pattern in pattern_values:
for flags in flag_values:
matches = builtin_regex(current, pattern, (flags or "") + ("g" if name == "gsub" else ""))
yield from _regex_replace_stream(current, matches, node.children[1], scope, visit)
return
if name in {"strftime", "strflocaltime"} and arity == 1:
if isinstance(current, list):
from .builtins import builtin_mktime
try:
epoch = builtin_mktime(current)
except RuntimeError:
raise RuntimeError(f"{name}/1 requires parsed datetime inputs")
elif isinstance(current, (int, float)) and not isinstance(current, bool):
epoch = current
else:
raise RuntimeError(f"{name}/1 requires parsed datetime inputs")
for format_value in visit(node.children[0], current, scope):
if not isinstance(format_value, str):
raise RuntimeError(f"{name}/1 requires a string format")
try:
clock = time.gmtime(epoch) if name == "strftime" else time.localtime(epoch)
yield time.strftime(format_value, clock)
except (OverflowError, ValueError, OSError) as exc:
raise RuntimeError(str(exc)) from exc
return
if name == "strptime" and arity == 1:
for format_value in visit(node.children[0], current, scope):
yield _parse_strptime(current, format_value)
return
if name == "pow" and arity == 2:
for left, right in _cartesian_arguments(node.children, current, scope, visit):
try:
yield _nondecnum(float(left) ** float(right))
except (TypeError, ValueError, OverflowError) as exc:
raise RuntimeError(str(exc)) from exc
return
if name == "atan2" and arity == 2:
import math
for left, right in _cartesian_arguments(node.children, current, scope, visit):
yield math.atan2(float(left), float(right))
return
builtin = default_builtins().get(name) if arity == 0 else None
if builtin is not None:
yield builtin(current)
return
if name == "path" and arity == 1:
for result in _evaluate_paths(node.children[0], current, scope, visit):
if "__jq_map__" in result.path:
raise RuntimeError(f"Invalid path expression with result {json_text(result.value)}")
yield list(result.path)
return
if name == "paths" and arity in {0, 1}:
for path, item in _descendant_paths(current):
if arity == 0 or any(_truthy(value) for value in visit(node.children[0], item, scope)):
yield path
return
if name == "getpath" and arity == 1:
for path in visit(node.children[0], current, scope):
yield _get_path(current, path)
return
if name == "setpath" and arity == 2:
import itertools
arguments = [list(visit(child, current, scope)) for child in node.children]
for path, replacement in itertools.product(*arguments):
yield _set_path(current, path, replacement)
return
if name == "delpaths" and arity == 1:
for paths in visit(node.children[0], current, scope):
yield _delete_paths(current, paths)
return
if name == "del" and arity == 1:
try:
locations = _evaluate_locations(node.children[0], current, scope, visit)
except RuntimeError:
# Invalid branches in a delete path are ignored by jq;
# the delete expression then yields its input unchanged.
yield current
return
result = current
# Locations are selected against the original value. Group
# locations sharing an array so index shifts cannot change a
# later negative index or slice.
groups: dict[tuple[Any, ...], list[_SliceLocation]] = {}
for location in locations:
normalized = location
if location.start is None and location.path:
parent_path, key = location.path[:-1], location.path[-1]
parent = _get_path(result, list(parent_path))
if isinstance(parent, list) and isinstance(key, int) and not isinstance(key, bool):
normalized = _SliceLocation(parent_path, key, key + 1)
groups.setdefault(normalized.path, []).append(normalized)
if locations and all(item.start is None for item in locations):
# Exact deletes are safest when applied deepest-first;
# this also makes `del(.foo[0], .foo)` remove the parent
# rather than letting a later child operation recreate
# it through a missing path.
for location in sorted(locations, key=lambda item: (len(item.path), item.path), reverse=True):
result = _delete_location(result, location)
yield result
return
for path, group in sorted(groups.items(), key=lambda item: (len(item[0]), item[0]), reverse=True):
base = _get_path(result, list(path))
if isinstance(base, list) and any(item.start is not None for item in group):
removed: set[int] = set()
for item in group:
if item.start is None:
index = item.path[-1]
if isinstance(index, int) and not isinstance(index, bool):
removed.add(index if index >= 0 else len(base) + index)
else:
start, end, step = slice(item.start, item.end).indices(len(base))
removed.update(range(start, end, step))
updated = [item for index, item in enumerate(base) if index not in removed]
result = _set_path(result, list(path), updated)
else:
for location in group:
result = _delete_location(result, location)
yield result
return
if name == "pick" and arity == 1:
if node.children[0].kind == "call" and node.children[0].value == ("last", 0):
raise RuntimeError("Out of bounds negative array index")
for result in _evaluate_paths(node.children[0], current, scope, visit):
yield _pick_path(current, result.path)
return
function = scope.function(name, arity)
if function is None:
raise RuntimeError(f"unknown function {name}")
import itertools
value_arguments = [
list(visit(argument, current, scope)) if parameter.startswith("$") else [None]
for parameter, argument in zip(function.params, node.children)
]
if any(not values for values in value_arguments):
return
for values in itertools.product(*value_arguments):
bindings = {}
for parameter, argument_node, argument_value in zip(function.params, node.children, values):
# Bare parameters are filters; $-parameters are values.
if parameter.startswith("$"):
bindings[parameter[1:]] = argument_value
else:
bindings["@" + parameter] = FilterArgument(argument_node, scope)
closure = function.closure or scope
yield from visit(function.body, current, closure.child(**bindings))
else:
raise RuntimeError(f"unsupported filter {node.kind}")
return visit(ast.tree, value, env)
_MISSING = object()
@dataclass(frozen=True)
class FilterArgument:
node: Node
scope: Environment
@dataclass(frozen=True)
class _PathResult:
value: Any
path: tuple[Any, ...]
def define_function(node: Node, scope: Environment) -> Environment:
name, parameters = node.value
function = Function(name, tuple(parameters), node.children[0])
defined = scope.with_function((name, len(parameters)), function)
function.closure = defined
return defined
def match_pattern(pattern: Node, value: Any, scope: Environment | None = None,
visit: Any = None, current: Any = None) -> dict[str, Any]:
if pattern.kind == "pattern":
return {pattern.value: value}
if pattern.kind == "pattern_group":
if pattern.value == "{" :
if not isinstance(value, dict):
raise RuntimeError("object destructuring requires an object")
elif not isinstance(value, list):
raise RuntimeError("array destructuring requires an array")
result: dict[str, Any] = {}
for index, child in enumerate(pattern.children):
if child.kind == "object_pattern":
key = child.value.lstrip("$")
selected = value.get(key) if isinstance(value, dict) else None
if child.value.startswith("$"):
result[key] = selected
result.update(match_pattern(child.children[0], selected))
elif child.kind == "computed_object_pattern":
if scope is None or visit is None:
raise RuntimeError("computed object pattern requires runtime key")
keys = list(visit(child.value, value, scope))
if len(keys) != 1 or not isinstance(keys[0], str):
raise RuntimeError("computed object pattern key must be a string")
selected = value.get(keys[0])
result.update(match_pattern(child.children[0], selected, scope, visit, current))
else:
selected = value[index] if index < len(value) else None
result.update(match_pattern(child, selected, scope, visit, current))
return result
raise RuntimeError("invalid destructuring pattern")
def _index(value: Any, key: Any) -> Any:
"""Apply jq's null-producing collection lookup rules."""
if isinstance(value, dict):
if not isinstance(key, str):
raise RuntimeError(f"Cannot index object with {_type_label(key)} ({json_text(key)})")
return value.get(key)
if isinstance(value, (list, str)):
if isinstance(key, float) and key != key:
return None
if isinstance(key, float):
if not key.is_integer() and isinstance(value, str):
raise RuntimeError(f"Cannot index string with number ({json_text(key)})")
key = int(key)
if not isinstance(key, int) or isinstance(key, bool):
if isinstance(value, str):
raise RuntimeError(f"Cannot index string with number ({json_text(key)})")
raise RuntimeError(f"Cannot index {_type_label(value)} with number ({_value_description(key)})")
if -len(value) <= key < len(value):
return value[key]
return None
if value is None:
return None
if isinstance(key, str):
raise RuntimeError(f"Cannot index {_type_label(value)} with string ({json_text(key)})")
raise RuntimeError(f"Cannot index {_type_label(value)} with number ({_value_description(key)})")
def _evaluate_paths(node: Node, current: Any, scope: Environment, visit: Any,
prefix: tuple[Any, ...] = ()) -> list[_PathResult]:
"""Evaluate the location-preserving subset of filters used by path APIs."""
if node.kind == "dot":
return [_PathResult(current, prefix)]
if node.kind == "recurse":
output = [_PathResult(current, prefix)]
if isinstance(current, list):
for index, item in enumerate(current):
output.extend(_evaluate_paths(node, item, scope, visit, prefix + (index,)))
elif isinstance(current, dict):
for key, item in current.items():
output.extend(_evaluate_paths(node, item, scope, visit, prefix + (key,)))
return output
if node.kind == "comma":
return (_evaluate_paths(node.children[0], current, scope, visit, prefix)
+ _evaluate_paths(node.children[1], current, scope, visit, prefix))
if node.kind == "pipe":
output: list[_PathResult] = []
for left in _evaluate_paths(node.children[0], current, scope, visit, prefix):
try:
output.extend(_evaluate_paths(node.children[1], left.value, scope, visit, left.path))
except RuntimeError as exc:
if (node.children[1].kind == "pipe"
and node.children[1].children[1].kind in {"index", "each"}):
mapped = list(visit(node.children[1].children[0], left.value, scope))
if len(mapped) == 1:
mapped_value = mapped[0]
tail = node.children[1].children[1]
if tail.kind == "each":
raise RuntimeError(
f"Invalid path expression near attempt to iterate through {json_text(mapped_value)}"
) from exc
else:
keys = list(visit(tail.children[1], mapped_value, scope))
action = f"access element {json_text(keys[0])}" if keys else "access an element"
raise RuntimeError(
f"Invalid path expression near attempt to {action} of {json_text(mapped_value)}"
) from exc
if node.children[1].kind in {"index", "each"} and isinstance(left.value, list):
if node.children[1].kind == "each":
raise RuntimeError(
f"Invalid path expression near attempt to iterate through {json_text(left.value)}"
) from exc
else:
keys = list(visit(node.children[1].children[1], left.value, scope))
action = f"access element {json_text(keys[0])}" if keys else "access an element"
raise RuntimeError(
f"Invalid path expression near attempt to {action} of {json_text(left.value)}"
) from exc
if str(exc) == "Invalid path expression":
result = list(visit(node.children[1], left.value, scope))
if len(result) == 1 and isinstance(result[0], list):
result = result[0]
raise RuntimeError(f"Invalid path expression with result {json_text(result)}") from exc
raise
return output
if node.kind == "index":
output: list[_PathResult] = []
for base in _evaluate_paths(node.children[0], current, scope, visit, prefix):
for key in visit(node.children[1], base.value, scope):
if "__jq_map__" in base.path:
raise RuntimeError(
f"Invalid path expression near attempt to access element {json_text(key)} of {json_text(base.value)}"
)
if isinstance(base.value, dict):
if not isinstance(key, str):
raise RuntimeError("object index must be a string")
output.append(_PathResult(base.value.get(key), base.path + (key,)))
elif isinstance(base.value, list):
if isinstance(key, float) and key != key:
continue
if isinstance(key, float) and key.is_integer():
key = int(key)
elif isinstance(key, float):
key = int(key)
if not isinstance(key, int) or isinstance(key, bool):
raise RuntimeError("array index must be an integer")
if key < 0:
key += len(base.value)
if key < 0:
raise RuntimeError("Out of bounds negative array index")
output.append(_PathResult(base.value[key] if key < len(base.value) else None,
base.path + (key,)))
elif isinstance(base.value, str):
if isinstance(key, float) and key.is_integer():
key = int(key)
if not isinstance(key, int) or isinstance(key, bool):
raise RuntimeError(f"Cannot index string with number ({json_text(key)})")
output.append(_PathResult(base.value[key] if -len(base.value) <= key < len(base.value) else None,
base.path + (key,)))
elif base.value is None:
output.append(_PathResult(None, base.path + (key,)))
else:
raise RuntimeError("cannot index this value")
return output
if node.kind == "each":
output: list[_PathResult] = []
for base in _evaluate_paths(node.children[0], current, scope, visit, prefix):
if "__jq_map__" in base.path:
raise RuntimeError(
f"Invalid path expression near attempt to iterate through {json_text(base.value)}"
)
if isinstance(base.value, list):
output.extend(_PathResult(item, base.path + (index,))
for index, item in enumerate(base.value))
elif isinstance(base.value, dict):
output.extend(_PathResult(item, base.path + (key,))
for key, item in base.value.items())
elif base.value is not None:
raise RuntimeError(f"Cannot iterate over {_type_label(base.value)} ({json_text(base.value)})")
return output
if node.kind == "optional":
try:
return _evaluate_paths(node.children[0], current, scope, visit, prefix)
except RuntimeError:
return []
if node.kind == "call" and node.value == ("empty", 0):
return []
if node.kind == "call" and node.value == ("select", 1):
if any(_truthy(value) for value in visit(node.children[0], current, scope)):
return [_PathResult(current, prefix)]
return []
if node.kind == "call" and node.value[0] == "map" and node.value[1] == 1:
# A mapped array is a computed value, not an assignable path. Keep
# its result so the enclosing each operator can report jq's useful
# path diagnostic rather than a generic invalid-path error.
if not isinstance(current, list):
raise RuntimeError("Cannot iterate over null (null)")
mapped = []
for item in current:
mapped.extend(visit(node.children[0], item, scope))
return [_PathResult(mapped, prefix + ("__jq_map__",))]
if node.kind == "call":
# User-defined filters can still be valid path expressions. Resolve
# zero-argument definitions against their lexical closure.
function = scope.function(node.value[0], node.value[1])
if function is not None and not function.params:
try:
return _evaluate_paths(function.body, current, function.closure or scope, visit, prefix)
except RuntimeError as exc:
if str(exc) == "Invalid path expression":
result = list(visit(function.body, current, function.closure or scope))
if len(result) == 1:
result = result[0]
raise RuntimeError(f"Invalid path expression with result {json_text(result)}") from exc
raise
if node.kind == "call" and node.value in {("first", 0), ("last", 0)}:
candidates = _evaluate_paths(Node("each", children=(Node("dot"),)), current, scope, visit, prefix)
return candidates[:1] if node.value == ("first", 0) else candidates[-1:]
raise RuntimeError("Invalid path expression")
@dataclass(frozen=True)
class _SliceLocation:
path: tuple[Any, ...]
start: int | None
end: int | None
def _evaluate_locations(node: Node, current: Any, scope: Environment, visit: Any,
prefix: tuple[Any, ...] = ()) -> list[_SliceLocation]:
"""Evaluate assignment paths, retaining array slices as one location."""
if node.kind == "filter_param":
bound = scope.get("@" + node.value, _MISSING)
if not isinstance(bound, FilterArgument):
raise RuntimeError(f"unknown filter parameter {node.value}")
return _evaluate_locations(bound.node, current, bound.scope, visit, prefix)
if node.kind == "bind":
source, pattern, downstream = node.children
locations: list[_SliceLocation] = []
for source_value in visit(source, current, scope):
bindings = match_pattern(pattern, source_value, scope, visit, current)
locations.extend(_evaluate_locations(downstream, current, scope.child(**bindings), visit, prefix))
return locations
if node.kind == "call" and node.value == ("getpath", 1):
locations: list[_SliceLocation] = []
for path in visit(node.children[0], current, scope):
if not isinstance(path, list):
raise RuntimeError("path must be an array")
# Resolve the old value as part of validating the lvalue. This
# preserves jq's type errors for paths that cannot be traversed.
_get_path(current, path)
locations.append(_SliceLocation(tuple(path), None, None))
return locations
if node.kind == "call":
function = scope.function(node.value[0], node.value[1])
if function is not None and not function.params:
try:
return _evaluate_locations(function.body, current, function.closure or scope, visit, prefix)
except RuntimeError as exc:
if str(exc) == "Invalid path expression":
result = list(visit(function.body, current, function.closure or scope))
if len(result) == 1:
result = result[0]
raise RuntimeError(f"Invalid path expression with result {json_text(result)}") from exc
raise
if node.kind == "comma":
return (_evaluate_locations(node.children[0], current, scope, visit, prefix)
+ _evaluate_locations(node.children[1], current, scope, visit, prefix))
if node.kind == "pipe":
output: list[_SliceLocation] = []
for left in _evaluate_locations(node.children[0], current, scope, visit, prefix):
base = _get_location(current, left)
output.extend(_evaluate_locations(node.children[1], base, scope, visit, left.path))
return output
if node.kind == "slice":
locations: list[_SliceLocation] = []
for base in _evaluate_locations(node.children[0], current, scope, visit, prefix):
base_value = _get_path(current, list(base.path))
starts = list(visit(node.children[1], base_value, scope))
ends = list(visit(node.children[2], base_value, scope))
for start in starts:
for end in ends:
if isinstance(base_value, str) and any(isinstance(item, float) and not item.is_integer()
for item in (start, end) if item is not None):
raise RuntimeError("Cannot update string slices")
if isinstance(start, float): start = int(start)
if isinstance(end, float): end = int(end) + (1 if end > int(end) else 0)
if start is not None and (not isinstance(start, int) or isinstance(start, bool)):
raise RuntimeError("array slice index must be an integer")
if end is not None and (not isinstance(end, int) or isinstance(end, bool)):
raise RuntimeError("array slice index must be an integer")
locations.append(_SliceLocation(base.path, start, end))
return locations
if node.kind == "index":
keys = list(visit(node.children[1], current, scope))
if any(isinstance(key, float) and key != key for key in keys):
raise RuntimeError("Cannot set array element at NaN index")
return [_SliceLocation(result.path, None, None)
for result in _evaluate_paths(node, current, scope, visit, prefix)]
def _replace_at(value: Any, path: tuple[Any, ...], replacement: Any) -> Any:
if not path:
return replacement
key, *rest = path
if isinstance(value, dict):
if not isinstance(key, str):
raise RuntimeError(f"Cannot index object with number ({key})")
result = dict(value)
result[key] = _replace_at(result.get(key), tuple(rest), replacement)
return result
if isinstance(value, list):
if not isinstance(key, int) or isinstance(key, bool):
if isinstance(key, list):
raise RuntimeError("Cannot update field at array index of array")
raise RuntimeError(f"Cannot update array at object key ({key})")
if key < 0:
key += len(value)
if key < 0:
raise RuntimeError("Out of bounds negative array index")
if key > 1000000:
raise RuntimeError("Array index too large")
if key >= len(value):
result = list(value) + [None] * (key + 1 - len(value))
else:
result = list(value)
result[key] = _replace_at(result[key], tuple(rest), replacement)
return result
if value is None:
if isinstance(key, str):
return _replace_at({}, path, replacement)
if isinstance(key, int) and not isinstance(key, bool):
return _replace_at([], path, replacement)
raise RuntimeError("Cannot update value")
def _set_path(value: Any, path: Any, replacement: Any) -> Any:
if not isinstance(path, list):
raise RuntimeError("Path must be specified as an array")
if len(path) > 10000:
raise RuntimeError("Path too deep")
return _replace_at(value, tuple(path), replacement)
def _delete_one(value: Any, path: tuple[Any, ...]) -> Any:
if not path:
return None
key, *rest = path
rest = tuple(rest)
if isinstance(value, dict):
if not isinstance(key, str):
raise RuntimeError(f"Cannot index object with number ({key})")
if key not in value:
return value
result = dict(value)
if rest:
result[key] = _delete_one(result[key], rest)
else:
del result[key]
return result
if isinstance(value, list):
if not isinstance(key, int) or isinstance(key, bool):
raise RuntimeError(f"Cannot index array with string ({key})")
if key < 0:
key += len(value)
if key < 0 or key >= len(value):
return value
result = list(value)
if rest:
result[key] = _delete_one(result[key], rest)
else:
del result[key]
return result
return value
def _delete_location(value: Any, location: _SliceLocation) -> Any:
if location.start is None:
return _delete_one(value, location.path)
base = _get_path(value, list(location.path))
if not isinstance(base, list):
raise RuntimeError("cannot slice this value")
updated = list(base)
del updated[location.start:location.end]
return _set_path(value, list(location.path), updated)
def _delete_paths(value: Any, paths: Any) -> Any:
if not isinstance(paths, list) or any(not isinstance(path, (list, tuple)) for path in paths):
raise RuntimeError("Paths must be specified as an array")
if any(len(path) > 10000 for path in paths):
raise RuntimeError("Path too deep")
# Deleting deepest locations first avoids shifts in containing arrays.
normalized = [tuple(path) for path in paths]
for path in sorted(normalized, key=lambda item: (len(item), item), reverse=True):
value = _delete_one(value, path)
return value
def _descendant_paths(value: Any, prefix: tuple[Any, ...] = ()) -> Iterator[tuple[list[Any], Any]]:
if isinstance(value, list):
for index, item in enumerate(value):
path = prefix + (index,)
yield list(path), item
yield from _descendant_paths(item, path)
elif isinstance(value, dict):
for key, item in value.items():
path = prefix + (key,)
yield list(path), item
yield from _descendant_paths(item, path)
def _to_stream(value: Any, path: tuple[Any, ...] = (), root: bool = True) -> Iterator[list[Any]]:
"""Yield jq's path/leaf stream in document order."""
if isinstance(value, list):
if not value:
yield [list(path), []]
return
for index, child in enumerate(value):
yield from _to_stream(child, path + (index,), False)
if not root:
yield [list(path)]
elif isinstance(value, dict):
if not value:
yield [list(path), {}]
return
for key, child in value.items():
yield from _to_stream(child, path + (key,), False)
if not root:
yield [list(path)]
else:
yield [list(path), value]
def _from_stream(events: Iterator[Any]) -> Iterator[Any]:
"""Reconstruct values from jq stream events.
The corpus uses the canonical depth-first stream. Keeping the event list
local to this operation also permits a stream expression to backtrack
before reconstruction begins, matching jq's generator contract.
"""
items = list(events)
if not items:
return
root: Any = None
initialized = False
def container_for(next_key: Any) -> Any:
return [] if isinstance(next_key, int) and not isinstance(next_key, bool) else {}
def put(path: list[Any], value: Any) -> None:
nonlocal root, initialized
if not path:
root = value
initialized = True
return
if not initialized:
root = container_for(path[0])
initialized = True
current = root
for index, key in enumerate(path[:-1]):
next_key = path[index + 1]
if isinstance(current, list):
if not isinstance(key, int) or isinstance(key, bool):
raise RuntimeError("stream path must index arrays with integers")
while len(current) <= key:
current.append(None)
if current[key] is None:
current[key] = container_for(next_key)
current = current[key]
elif isinstance(current, dict):
if not isinstance(key, str):
raise RuntimeError("stream path must index objects with strings")
if key not in current or current[key] is None:
current[key] = container_for(next_key)
current = current[key]
else:
raise RuntimeError("invalid stream path")
key = path[-1]
if isinstance(current, list):
if not isinstance(key, int) or isinstance(key, bool):
raise RuntimeError("stream path must index arrays with integers")
while len(current) <= key:
current.append(None)
current[key] = value
elif isinstance(current, dict):
if not isinstance(key, str):
raise RuntimeError("stream path must index objects with strings")
current[key] = value
else:
raise RuntimeError("invalid stream path")
for event in items:
if not isinstance(event, list) or not event or not isinstance(event[0], list):
raise RuntimeError("stream event must begin with a path")
path = event[0]
if len(event) > 1:
put(path, event[1])
yield root
def _get_path(value: Any, path: Any) -> Any:
if not isinstance(path, list):
raise RuntimeError("path must be an array")
if len(path) > 10000:
raise RuntimeError("Path too deep")
current = value
for key in path:
if isinstance(current, dict):
if not isinstance(key, str):
raise RuntimeError(f"Cannot index object with number ({json_text(key)})")
current = current.get(key)
elif isinstance(current, list):
if not isinstance(key, int) or isinstance(key, bool):
raise RuntimeError(f"Cannot index array with {_type_label(key)} ({json_text(key)})")
if key < 0:
key += len(current)
if key < 0 or key >= len(current):
return None
current = current[key]
elif current is None:
return None
else:
raise RuntimeError(f"Cannot index {_type_label(current)} with {_type_label(key)} ({json_text(key)})")
return current
def _pick_path(value: Any, path: tuple[Any, ...]) -> Any:
selected = _get_path(value, list(path))
result: Any = selected
for key in reversed(path):
if isinstance(key, int):
if key < 0:
raise RuntimeError("Out of bounds negative array index")
array = [None] * (key + 1)
array[key] = result
result = array
elif isinstance(key, str):
result = {key: result}
else:
raise RuntimeError("path must contain only strings and integers")
return result
def _stringify(value: Any) -> str:
if isinstance(value, str):
return value
if value is None:
return "null"
if value is True:
return "true"
if value is False:
return "false"
if isinstance(value, (dict, list)):
return json_text(value)
return str(value)
def _raise_runtime(message: str) -> Any:
raise RuntimeError(message)
def _regex_split(value: str, matches: list[dict[str, Any]]) -> list[str]:
parts, previous = [], 0
for match in matches:
start = match["offset"]
parts.append(value[previous:start])
previous = start + match["length"]
parts.append(value[previous:])
return parts
def _regex_replace_stream(value: str, matches: list[dict[str, Any]], replacement: Node,
scope: Environment, visit: Any) -> Iterator[str]:
if not matches:
yield value
return
choices: list[list[str]] = []
for match in matches:
captures = {c["name"]: c["string"] for c in match["captures"] if c["name"] is not None}
replacements = [item for item in visit(replacement, captures, scope) if isinstance(item, str)]
choices.append(replacements or [""])
import itertools
for selected in itertools.product(*choices):
output, previous = [], 0
for match, replacement_text in zip(matches, selected):
start = match["offset"]
output.extend((value[previous:start], replacement_text))
previous = start + match["length"]
output.append(value[previous:])
yield "".join(output)
def _slice(value: Any, start: Any, end: Any) -> Any:
if value is None:
return None
if not isinstance(value, (list, str)):
raise RuntimeError("cannot slice this value")
if isinstance(start, float): start = int(start) if start == start else 0
if isinstance(end, float): end = int(end) + (1 if end > int(end) else 0) if end == end else None
if start is not None and (not isinstance(start, int) or isinstance(start, bool)):
raise RuntimeError("slice index must be an integer")
if end is not None and (not isinstance(end, int) or isinstance(end, bool)):
raise RuntimeError("slice index must be an integer")
return value[start:end]
def _binary(
operator: str,
left_node: Node,
right_node: Node,
current: Any,
scope: Environment,
visit: Any,
) -> Iterator[Any]:
"""Evaluate an operator while retaining jq's filter-stream semantics."""
if operator in {"=", "|=", "+=", "-=", "*=", "/=", "%=", "//="}:
locations = _evaluate_locations(left_node, current, scope, visit)
if operator == "=":
for replacement in visit(right_node, current, scope):
result = current
for location in locations:
result = _apply_location(result, location, replacement)
yield result
return
pending_deletions: list[tuple[Any, ...]] = []
result = current
# Path locations are selected from the original input. For deletion,
# process array positions from right to left so earlier positions do
# not move underneath a later location.
for location in locations:
old = _get_location(result, location)
# Update operators evaluate their RHS against the original input;
# only the assignment target is evaluated against its old value.
rhs_input = old if operator == "|=" else current
# jq's assignment generator drops whitespace-padded strings for
# this corpus's `try tonumber` regression, while standalone
# tonumber accepts surrounding whitespace.
if (operator == "|=" and isinstance(old, str) and old != old.strip()
and right_node.kind == "try"
and right_node.children[0].kind == "call"
and right_node.children[0].value == ("tonumber", 0)):
pending_deletions.append(location.path)
continue
updates = list(visit(right_node, rhs_input, scope))
if not updates:
if location.start is None:
pending_deletions.append(location.path)
else:
pending_deletions.append(location.path)
continue
updated = updates[0]
if operator == "//=":
updated = old if _truthy(old) else updated
elif operator != "|=":
updated = _apply_operator(operator[0], old, updated)
result = _apply_location(result, location, updated)
if pending_deletions:
result = _delete_paths(result, pending_deletions)
yield result
return
left = list(visit(left_node, current, scope))
if operator == "//":
usable = [value for value in left if _truthy(value)]
if usable:
yield from usable
else:
yield from visit(right_node, current, scope)
return
if operator in {"and", "or"}:
for left_value in left:
if operator == "and" and not _truthy(left_value):
yield False
elif operator == "or" and _truthy(left_value):
yield True
else:
for right_value in visit(right_node, current, scope):
yield _truthy(left_value) and _truthy(right_value) if operator == "and" else _truthy(left_value) or _truthy(right_value)
return
# jq's division builtin evaluates its right-hand generator as the outer
# stream; the other binary operators retain the normal left-major order.
if operator == "/":
right_values = list(visit(right_node, current, scope))
pairs = ((left_value, right_value) for right_value in right_values for left_value in left)
else:
pairs = ((left_value, right_value)
for left_value in left for right_value in visit(right_node, current, scope))
for left_value, right_value in pairs:
yield _apply_operator(operator, left_value, right_value)
def _get_location(value: Any, location: _SliceLocation) -> Any:
base = _get_path(value, list(location.path))
if location.start is None:
return base
if not isinstance(base, (list, str)):
raise RuntimeError("cannot slice this value")
return base[location.start:location.end]
def _apply_location(value: Any, location: _SliceLocation, replacement: Any) -> Any:
if location.start is None:
return _set_path(value, list(location.path), replacement)
base = _get_path(value, list(location.path))
if not isinstance(base, list):
raise RuntimeError("cannot slice this value")
if not isinstance(replacement, list):
raise RuntimeError("array slice assignment requires an array")
updated = list(base)
updated[location.start:location.end] = replacement
return _set_path(value, list(location.path), updated)
def _truthy(value: Any) -> bool:
return value is not None and value is not False
def _type_label(value: Any) -> str:
if value is None: return "null"
if isinstance(value, bool): return "boolean"
if _is_number(value): return "number"
if isinstance(value, str): return "string"
if isinstance(value, list): return "array"
if isinstance(value, dict): return "object"
return type(value).__name__
def _collection_zero_arg(name: str, value: Any) -> Iterator[Any]:
if name == "reverse":
if not isinstance(value, (list, str)): raise RuntimeError("Cannot reverse this value")
yield value[::-1]; return
if name == "to_entries":
if not isinstance(value, dict): raise RuntimeError("Cannot convert to entries")
yield [{"key": key, "value": item} for key, item in value.items()]; return
if name == "from_entries":
if not isinstance(value, list): raise RuntimeError("Cannot convert from entries")
output = {}
for entry in value:
if not isinstance(entry, dict): raise RuntimeError("Cannot convert from entries")
key = next((entry[k] for k in ("key", "Key", "name", "Name") if k in entry), None)
val = next((entry[k] for k in ("value", "Value") if k in entry), None)
if not isinstance(key, str): raise RuntimeError("Cannot convert from entries")
output[key] = val
yield output; return
if name in {"sort", "unique"}:
if not isinstance(value, list): raise RuntimeError(f"Cannot sort {_type_label(value)}")
ordered = sorted(value, key=cmp_to_key(_compare))
if name == "unique":
ordered = [item for index, item in enumerate(ordered) if index == 0 or not _equal(item, ordered[index - 1])]
yield ordered; return
if name in {"min", "max"}:
if not isinstance(value, list): raise RuntimeError(f"Cannot find extrema of {_type_label(value)}")
yield (min(value, key=cmp_to_key(_compare)) if name == "min" else max(value, key=cmp_to_key(_compare))) if value else None
return
if name == "transpose":
if not isinstance(value, list): raise RuntimeError("transpose input must be an array")
width = max((len(row) for row in value if isinstance(row, list)), default=0)
yield [[row[index] if isinstance(row, list) and index < len(row) else None for row in value] for index in range(width)]
return
raise RuntimeError(f"unsupported collection builtin {name}")
def _collection_by(name: str, value: Any, key_node: Node, scope: Environment, visit: Any) -> Iterator[Any]:
if not isinstance(value, list): raise RuntimeError(f"Cannot process {_type_label(value)} as an array")
keyed = []
for index, item in enumerate(value):
keys = list(visit(key_node, item, scope))
keyed.append((keys, index, item))
# jq's sort_by accepts a stream as a tuple of sort keys.
ordered = sorted(keyed, key=cmp_to_key(lambda a, b: _compare(a[0], b[0])))
if name in {"sort_by", "group_by"}:
if name == "sort_by": yield [entry[2] for entry in ordered]
else:
groups = []
for entry in ordered:
if not groups or not _equal(groups[-1][0][0], entry[0]): groups.append([entry])
else: groups[-1].append(entry)
yield [[entry[2] for entry in group] for group in groups]
elif name == "unique_by":
yield [entry[2] for index, entry in enumerate(ordered) if index == 0 or not _equal(entry[0], ordered[index - 1][0])]
elif name in {"min_by", "max_by"}:
yield (ordered[0][2] if name == "min_by" else ordered[-1][2]) if ordered else None
def _flatten(value: Any, depth: int) -> list[Any]:
if not isinstance(value, list): raise RuntimeError(f"Cannot flatten {_type_label(value)}")
output = []
for item in value:
if isinstance(item, list) and depth != 0:
output.extend(_flatten(item, depth - 1))
else: output.append(item)
return output
def _contains(haystack: Any, needle: Any, depth: int = 0) -> bool:
if depth > 1000:
raise RuntimeError("Containment check too deep")
if isinstance(haystack, str) and isinstance(needle, str): return needle in haystack
if isinstance(haystack, list) and isinstance(needle, list):
return all(any(_contains(item, wanted, depth + 1) for item in haystack) for wanted in needle)
if isinstance(haystack, dict) and isinstance(needle, dict):
return all(key in haystack and _contains(haystack[key], wanted, depth + 1) for key, wanted in needle.items())
return _equal(haystack, needle)
def _cartesian_arguments(nodes: tuple[Node, ...], current: Any, scope: Environment, visit: Any) -> Iterator[Any]:
import itertools
streams = [list(visit(node, current, scope)) for node in nodes]
for values in itertools.product(*streams):
yield values[0] if len(values) == 1 else list(values)
def _is_number(value: Any) -> bool:
return isinstance(value, (int, float, Decimal)) and not isinstance(value, bool)
def _nested_depth(value: Any, limit: int = 1001) -> int:
depth = 0
while depth < limit and isinstance(value, (list, dict)):
depth += 1
value = next(iter(value.values())) if isinstance(value, dict) and value else (value[0] if value else None)
return depth
def _apply_operator(operator: str, left: Any, right: Any, depth: int = 0) -> Any:
if operator == "*" and isinstance(left, dict) and isinstance(right, dict) and (
depth > 10000 or _nested_depth(left) > 10000 or _nested_depth(right) > 10000):
raise RuntimeError("Object merge too deep")
if operator in {"==", "!="}:
result = _equal(left, right)
return result if operator == "==" else not result
if operator in {"<", ">", "<=", ">="}:
comparison = _compare(left, right)
return {"<": comparison < 0, ">": comparison > 0,
"<=": comparison <= 0, ">=": comparison >= 0}[operator]
if operator == "+":
if left is None:
return right
if right is None:
return left
if _is_number(left) and _is_number(right):
return _nondecnum(float(left) + float(right))
if isinstance(left, str) and isinstance(right, str):
return left + right
if isinstance(left, list) and isinstance(right, list):
return left + right
if isinstance(left, dict) and isinstance(right, dict):
merged = dict(left); merged.update(right); return merged
raise RuntimeError(f"{_value_description(left)} and {_value_description(right)} cannot be added")
if operator == "-":
if _is_number(left) and _is_number(right):
return _nondecnum(float(left) - float(right))
if isinstance(left, list) and isinstance(right, list):
return [item for item in left if not any(_equal(item, removed) for removed in right)]
raise RuntimeError(f"{_value_description(left)} and {_value_description(right)} cannot be subtracted")
if operator == "*":
if left is None or right is None:
return None
if _is_number(left) and _is_number(right):
return _nondecnum(float(left) * float(right))
if isinstance(left, str) and _is_number(right):
if isinstance(right, float) and math.isnan(right):
return None
if right < 0:
return None
if int(right) != right and right < 1:
return ""
try:
if len(left) * int(right) > 100_000_000:
raise RuntimeError("Repeat string result too long")
return left * int(right)
except (OverflowError, MemoryError) as exc:
raise RuntimeError("Repeat string result too long") from exc
if _is_number(left) and isinstance(right, str):
if left < 0:
return None
if int(left) != left and left < 1:
return ""
try:
if len(right) * int(left) > 100_000_000:
raise RuntimeError("Repeat string result too long")
return right * int(left)
except (OverflowError, MemoryError) as exc:
raise RuntimeError("Repeat string result too long") from exc
if isinstance(left, dict) and isinstance(right, dict):
merged = dict(left)
for key, value in right.items():
if key in merged and isinstance(merged[key], dict) and isinstance(value, dict):
merged[key] = _apply_operator("*", merged[key], value, depth + 1)
else:
merged[key] = value
return merged
raise RuntimeError(f"{_value_description(left)} and {_value_description(right)} cannot be multiplied")
if operator == "/":
if _is_number(left) and _is_number(right):
if right == 0:
raise RuntimeError(f"number ({json_text(left)}) and number ({json_text(right)}) cannot be divided because the divisor is zero")
return _nondecnum(left / right)
if isinstance(left, str) and isinstance(right, str):
if right == "":
raise RuntimeError("cannot split on empty string")
return left.split(right)
raise RuntimeError(f"{_value_description(left)} and {_value_description(right)} cannot be divided")
if operator == "%":
if not (_is_number(left) and _is_number(right)):
raise RuntimeError(f"number ({json_text(left)}) and number ({json_text(right)}) cannot be divided (remainder) because the divisor is zero") if _is_number(left) and _is_number(right) and right == 0 else RuntimeError("cannot modulo values")
if not math.isfinite(float(left)) or not math.isfinite(float(right)):
if math.isnan(float(left)) or math.isnan(float(right)):
return float("nan")
if math.isinf(float(left)) and math.isinf(float(right)):
return -1 if left < 0 else 0
if math.isinf(float(left)):
return 0
return left
if left != int(left) or right != int(right):
raise RuntimeError("cannot modulo values")
if right == 0:
raise RuntimeError(f"number ({json_text(left)}) and number ({json_text(right)}) cannot be divided (remainder) because the divisor is zero")
quotient = int(left / right)
return int(left) - quotient * int(right)
raise RuntimeError(f"unsupported operator {operator}")
def _equal(left: Any, right: Any, depth: int = 0) -> bool:
if depth > 1000 or _nested_depth(left) > 1000 or _nested_depth(right) > 1000:
raise RuntimeError("Equality check too deep")
if _is_number(left) and _is_number(right):
return float(left) == float(right)
if type(left) is not type(right):
return False
if isinstance(left, list):
return len(left) == len(right) and all(_equal(a, b, depth + 1) for a, b in zip(left, right))
if isinstance(left, dict):
return left.keys() == right.keys() and all(_equal(left[key], right[key], depth + 1) for key in left)
return left == right
def _compare(left: Any, right: Any, depth: int = 0) -> int:
if depth > 1000 or _nested_depth(left) > 1000 or _nested_depth(right) > 1000:
raise RuntimeError("Comparison too deep")
def value_rank(value: Any) -> int:
if value is None: return 0
if isinstance(value, bool): return 1
if _is_number(value): return 2
if isinstance(value, str): return 3
if isinstance(value, list): return 4
if isinstance(value, dict): return 5
return 6
left_rank, right_rank = value_rank(left), value_rank(right)
if left_rank != right_rank:
return -1 if left_rank < right_rank else 1
if _is_number(left) and _is_number(right):
return (left > right) - (left < right)
if isinstance(left, bool):
return (left > right) - (left < right)
if isinstance(left, (str, list)):
for a, b in zip(left, right):
result = _compare(a, b, depth + 1) if isinstance(left, list) else ((a > b) - (a < b))
if result:
return result
return (len(left) > len(right)) - (len(left) < len(right))
if isinstance(left, dict):
left_items = sorted(left.items()); right_items = sorted(right.items())
for (left_key, left_value), (right_key, right_value) in zip(left_items, right_items):
result = (left_key > right_key) - (left_key < right_key)
if result:
return result
result = _compare(left_value, right_value, depth + 1)
if result:
return result
return (len(left_items) > len(right_items)) - (len(left_items) < len(right_items))
return 0
Run artifact