{"type":"thread.started","thread_id":"01a183a0-95cf-7142-a74d-667595faae8c"}
{"type":"turn.started"}
{"type":"item.completed","item":{"id":"item_0","type":"agent_message","text":"I’ll inspect the existing implementation and tests first, then add only the command-layer changes required by the specification and run the declared targeted checks."}}
{"type":"item.started","item":{"id":"item_1","type":"command_execution","command":"/bin/bash -lc \"pwd; rg --files -g '\"'!sources/**'\"' -g '\"'!__pycache__/**'\"' | sort; printf '\\\\n--- source files ---\\\\n'; for f in \"'$(rg --files -g '\"'\"'!sources/**'\"' | sort); do echo \\\"### \"'$f\"; sed -n '\"'1,240p' \\\"\"'$f\"; done'","aggregated_output":"","exit_code":null,"status":"in_progress"}}
{"type":"item.completed","item":{"id":"item_1","type":"command_execution","command":"/bin/bash -lc \"pwd; rg --files -g '\"'!sources/**'\"' -g '\"'!__pycache__/**'\"' | sort; printf '\\\\n--- source files ---\\\\n'; for f in \"'$(rg --files -g '\"'\"'!sources/**'\"' | sort); do echo \\\"### \"'$f\"; sed -n '\"'1,240p' \\\"\"'$f\"; done'","aggregated_output":"/mnt/c/Users/barlo/projects/drydock/uat/jq/runs/20261028.145919/build/jq\njq\njq_interpreter/__init__.py\njq_interpreter/__main__.py\njq_interpreter/builtins.py\njq_interpreter/command.py\njq_interpreter/errors.py\njq_interpreter/evaluator.py\njq_interpreter/lexer.py\njq_interpreter/parser.py\npyproject.toml\ntests/conftest.py\ntests/test_assignment.py\ntests/test_bindings.py\ntests/test_collections.py\ntests/test_conversion.py\ntests/test_dates.py\ntests/test_evaluator.py\ntests/test_formats.py\ntests/test_foundation.py\ntests/test_generator_control.py\ntests/test_input_diagnostics.py\ntests/test_lexer.py\ntests/test_numeric.py\ntests/test_parser.py\ntests/test_paths.py\ntests/test_sql_builtins.py\ntests/test_strings.py\ntests/test_traversal.py\nuv.lock\n\n--- source files ---\n### jq\n#!/usr/bin/env python3\nfrom jq_interpreter.command import main\n\nraise SystemExit(main())\n### jq_interpreter/__init__.py\n\"\"\"Public package for the standalone jq interpreter.\"\"\"\n\nfrom .errors import CompileError, RuntimeError\n\n__all__ = [\"CompileError\", \"RuntimeError\"]\n### jq_interpreter/__main__.py\nfrom .command import main\n\nraise SystemExit(main())\n### jq_interpreter/builtins.py\n\"\"\"Builtin conversion helpers and registration boundary.\"\"\"\n\nfrom collections.abc import Callable\nimport base64\nimport binascii\nimport calendar\nimport json\nimport math\nimport re\nimport time\nfrom urllib.parse import quote, unquote\nfrom typing import Any\n\nfrom .errors import RuntimeError\n\nBuiltin = Callable[..., Any]\n\n\ndef default_builtins() -> dict[str, Builtin]:\n \"\"\"Return a fresh builtin registry for one interpreter invocation.\"\"\"\n\n return {\n \"type\": builtin_type,\n \"length\": builtin_length,\n \"utf8bytelength\": builtin_utf8bytelength,\n \"tonumber\": builtin_tonumber,\n \"toboolean\": builtin_toboolean,\n \"tostring\": builtin_tostring,\n \"tojson\": builtin_tojson,\n \"fromjson\": builtin_fromjson,\n \"explode\": builtin_explode,\n \"implode\": builtin_implode,\n \"isnan\": builtin_isnan,\n \"isfinite\": builtin_isfinite,\n \"isinfinite\": builtin_isinfinite,\n \"isnormal\": builtin_isnormal,\n \"have_decnum\": builtin_have_decnum,\n \"nan\": builtin_nan,\n \"infinite\": builtin_infinite,\n \"abs\": builtin_abs,\n \"fabs\": builtin_fabs,\n \"floor\": builtin_floor,\n \"ceil\": builtin_ceil,\n \"round\": builtin_round,\n \"sqrt\": builtin_sqrt,\n \"cbrt\": builtin_cbrt,\n \"exp\": builtin_exp,\n \"exp2\": builtin_exp2,\n \"log\": builtin_log,\n \"log2\": builtin_log2,\n \"log10\": builtin_log10,\n \"sin\": builtin_sin,\n \"cos\": builtin_cos,\n \"tan\": builtin_tan,\n \"asin\": builtin_asin,\n \"acos\": builtin_acos,\n \"atan\": builtin_atan,\n \"startswith\": builtin_startswith,\n \"endswith\": builtin_endswith,\n \"trim\": builtin_trim,\n \"ltrim\": builtin_ltrim,\n \"rtrim\": builtin_rtrim,\n \"ascii_upcase\": builtin_ascii_upcase,\n \"ascii_downcase\": builtin_ascii_downcase,\n \"gmtime\": builtin_gmtime,\n \"localtime\": builtin_localtime,\n \"mktime\": builtin_mktime,\n \"now\": builtin_now,\n \"fromdateiso8601\": builtin_fromdateiso8601,\n \"fromdate\": builtin_fromdateiso8601,\n \"todateiso8601\": builtin_todateiso8601,\n \"todate\": builtin_todateiso8601,\n \"builtins\": builtin_builtins,\n }\n\n\n# This is the public inventory exposed by jq's ``builtins`` filter. Keep the\n# entries in name/arity form, including aliases and functions with several\n# arities. The evaluator adds the stream-oriented SQL builtins below because\n# their arguments are filters rather than ordinary Python values.\n_BUILTIN_ARITIES: tuple[tuple[str, int], ...] = tuple(\n (name, 0) for name in (\n \"type\", \"length\", \"utf8bytelength\", \"tonumber\", \"toboolean\", \"tostring\",\n \"tojson\", \"fromjson\", \"explode\", \"implode\", \"isnan\", \"isfinite\",\n \"isinfinite\", \"isnormal\", \"have_decnum\", \"nan\", \"infinite\", \"abs\",\n \"fabs\", \"floor\", \"ceil\", \"round\", \"sqrt\", \"cbrt\", \"exp\", \"exp2\",\n \"log\", \"log2\", \"log10\", \"sin\", \"cos\", \"tan\", \"asin\", \"acos\", \"atan\",\n \"startswith\", \"endswith\", \"trim\", \"ltrim\", \"rtrim\", \"ascii_upcase\",\n \"ascii_downcase\", \"gmtime\", \"localtime\", \"mktime\", \"now\", \"fromdateiso8601\",\n \"fromdate\", \"todateiso8601\", \"todate\", \"empty\", \"select\", \"recurse\",\n \"walk\", \"tostream\", \"input\", \"inputs\", \"env\", \"debug\", \"stderr\",\n \"builtins\",\n )\n) + tuple((name, arity) for name, arity in (\n (\"INDEX\", 1), (\"INDEX\", 2), (\"JOIN\", 2), (\"JOIN\", 3), (\"JOIN\", 4),\n (\"IN\", 1), (\"IN\", 2), (\"first\", 0), (\"first\", 1), (\"last\", 0),\n (\"last\", 1), (\"limit\", 2), (\"skip\", 2), (\"nth\", 1), (\"nth\", 2),\n (\"range\", 1), (\"range\", 2), (\"range\", 3), (\"map\", 1), (\"map_values\", 1),\n (\"keys\", 0), (\"keys_unsorted\", 0), (\"has\", 1), (\"sort\", 0),\n (\"unique\", 0), (\"to_entries\", 0), (\"from_entries\", 0), (\"contains\", 1),\n (\"inside\", 1), (\"flatten\", 0), (\"flatten\", 1), (\"add\", 0), (\"add\", 1),\n (\"any\", 0), (\"any\", 1), (\"any\", 2), (\"all\", 0), (\"all\", 1), (\"all\", 2),\n (\"not\", 0), (\"path\", 1), (\"paths\", 0), (\"paths\", 1), (\"getpath\", 1),\n (\"setpath\", 2), (\"delpaths\", 1), (\"del\", 1), (\"pick\", 1),\n))\n\n\ndef builtin_builtins(value: Any) -> list[str]:\n return [f\"{name}/{arity}\" for name, arity in _BUILTIN_ARITIES]\n\n\ndef _require_string(value: Any, message: str = \"input must be a string\") -> str:\n if not isinstance(value, str):\n raise RuntimeError(message)\n return value\n\n\ndef builtin_startswith(value: Any, prefix: Any = None) -> bool:\n if not isinstance(value, str) or not isinstance(prefix, str):\n raise RuntimeError(\"startswith() requires string inputs\")\n return value.startswith(prefix)\n\n\ndef builtin_endswith(value: Any, suffix: Any = None) -> bool:\n if not isinstance(value, str) or not isinstance(suffix, str):\n raise RuntimeError(\"endswith() requires string inputs\")\n return value.endswith(suffix)\n\n\ndef builtin_trim(value: Any) -> str:\n return _require_string(value, \"trim input must be a string\").strip()\n\n\ndef builtin_ltrim(value: Any) -> str:\n return _require_string(value, \"trim input must be a string\").lstrip()\n\n\ndef builtin_rtrim(value: Any) -> str:\n return _require_string(value, \"trim input must be a string\").rstrip()\n\n\ndef builtin_ascii_upcase(value: Any) -> str:\n return \"\".join(chr(ord(c) - 32) if \"a\" <= c <= \"z\" else c for c in _require_string(value))\n\n\ndef builtin_ascii_downcase(value: Any) -> str:\n return \"\".join(chr(ord(c) + 32) if \"A\" <= c <= \"Z\" else c for c in _require_string(value))\n\n\ndef _epoch_number(value: Any, name: str) -> int | float:\n if not isinstance(value, (int, float)) or isinstance(value, bool):\n raise RuntimeError(f\"{name} requires a number\")\n return value\n\n\ndef _broken_down(clock: time.struct_time, seconds: int | float) -> list[int | float]:\n second = clock.tm_sec + (float(seconds) - math.floor(float(seconds)))\n if second.is_integer():\n second = int(second)\n return [clock.tm_year, clock.tm_mon - 1, clock.tm_mday, clock.tm_hour,\n clock.tm_min, second, (clock.tm_wday + 1) % 7, clock.tm_yday - 1]\n\n\ndef builtin_gmtime(value: Any) -> list[int | float]:\n seconds = _epoch_number(value, \"gmtime\")\n try:\n return _broken_down(time.gmtime(seconds), seconds)\n except (OverflowError, OSError, ValueError) as exc:\n raise RuntimeError(str(exc)) from exc\n\n\ndef builtin_localtime(value: Any) -> list[int | float]:\n seconds = _epoch_number(value, \"localtime\")\n try:\n return _broken_down(time.localtime(seconds), seconds)\n except (OverflowError, OSError, ValueError) as exc:\n raise RuntimeError(str(exc)) from exc\n\n\ndef builtin_mktime(value: Any) -> int | float:\n if not isinstance(value, list) or len(value) < 3 or any(\n not isinstance(item, (int, float)) or isinstance(item, bool) for item in value[:min(6, len(value))]\n ):\n raise RuntimeError(\"mktime requires parsed datetime inputs\")\n try:\n components = [int(item) for item in value[:6]] + [0] * (6 - min(6, len(value)))\n seconds = float(value[5]) if len(value) > 5 else 0.0\n whole = math.floor(seconds)\n components[1] += 1 # jq months are zero-based; struct tm months are not.\n epoch = calendar.timegm(tuple(components) + (whole,))\n result = epoch + (seconds - whole)\n return int(result) if result.is_integer() else result\n except (OverflowError, OSError, ValueError, TypeError) as exc:\n raise RuntimeError(str(exc)) from exc\n\n\ndef builtin_now(value: Any) -> float:\n return time.time()\n\n\ndef builtin_fromdateiso8601(value: Any) -> int | float:\n if not isinstance(value, str):\n raise RuntimeError(\"strptime/1 requires a string input\")\n return builtin_mktime(_parse_strptime(value, \"%Y-%m-%dT%H:%M:%SZ\"))\n\n\ndef builtin_todateiso8601(value: Any) -> str:\n return time.strftime(\"%Y-%m-%dT%H:%M:%SZ\", time.gmtime(_epoch_number(value, \"strftime\")))\n\n\ndef _parse_strptime(value: Any, format_value: Any) -> list[int | float]:\n if not isinstance(value, str):\n raise RuntimeError(\"strptime/1 requires a string input\")\n if not isinstance(format_value, str):\n raise RuntimeError(\"strptime/1 requires a string format\")\n try:\n parsed = time.strptime(value, format_value)\n except (ValueError, OverflowError, OSError) as exc:\n raise RuntimeError(str(exc)) from exc\n return _broken_down(parsed, parsed.tm_sec)\n\n\ndef builtin_split(value: Any, separator: Any) -> list[str]:\n value = _require_string(value, \"split input must be a string\")\n separator = _require_string(separator, \"split separator must be a string\")\n return list(value) if separator == \"\" else value.split(separator)\n\n\ndef builtin_join(value: Any, separator: Any) -> str:\n if not isinstance(value, list) or not isinstance(separator, str):\n raise RuntimeError(\"join input must be an array\")\n return separator.join(\"\" if item is None else (item if isinstance(item, str) else\n (\"true\" if item is True else \"false\" if item is False else str(item))) for item in value)\n\n\ndef builtin_indices(value: Any, needle: Any) -> list[int]:\n if isinstance(value, str) and isinstance(needle, str):\n if needle == \"\": return list(range(len(value) + 1))\n result, start = [], 0\n while True:\n### jq_interpreter/command.py\n\"\"\"Command-line boundary for the root ``jq`` executable.\"\"\"\n\nimport json\nimport re\nimport sys\nfrom collections.abc import Sequence\nfrom typing import TextIO\n\nfrom .builtins import json_text\nfrom .errors import CompileError, RuntimeError\nfrom .evaluator import RuntimeContext, Environment, evaluate\nfrom .parser import parse\n\n\n_SPECIAL_JSON_NUMBERS = re.compile(r\"(?<![A-Za-z0-9_])(-?infinite|nan)(?![A-Za-z0-9_])\")\n\n\ndef _parse_input(line: str) -> object:\n normalized = _SPECIAL_JSON_NUMBERS.sub(\n lambda match: {\"nan\": \"NaN\", \"infinite\": \"Infinity\", \"-infinite\": \"-Infinity\"}[match.group()],\n line,\n )\n return json.loads(normalized, parse_constant=lambda value: float(value))\n\n\ndef main(\n argv: Sequence[str] | None = None,\n stdin: TextIO | None = None,\n stdout: TextIO | None = None,\n stderr: TextIO | None = None,\n) -> int:\n \"\"\"Run jq and map compile/runtime failures to their specified statuses.\"\"\"\n\n args = list(sys.argv[1:] if argv is None else argv)\n input_stream = sys.stdin if stdin is None else stdin\n output_stream = sys.stdout if stdout is None else stdout\n error_stream = sys.stderr if stderr is None else stderr\n try:\n if len(args) != 2 or args[0] != \"-c\":\n raise CompileError(\"usage: jq -c PROGRAM\")\n ast = parse(args[1])\n def records():\n for line in input_stream:\n # jq accepts an optional UTF-8 BOM at the beginning of an input record.\n yield _parse_input(line.removeprefix(\"\\ufeff\"))\n\n shared = RuntimeContext(iter(records()), stderr=error_stream)\n environment = Environment(runtime=shared)\n for value in shared.records:\n for result in evaluate(ast, value, environment):\n output_stream.write(json_text(result) + \"\\n\")\n return 0\n except CompileError as exc:\n print(exc, file=error_stream)\n return 3\n except (RuntimeError, json.JSONDecodeError, OSError, TypeError, ValueError) as exc:\n print(exc, file=error_stream)\n return 5\n### jq_interpreter/errors.py\n\"\"\"Errors crossing the interpreter's compile and execution boundaries.\"\"\"\n\n\nclass CompileError(Exception):\n \"\"\"Raised when jq source cannot be compiled.\"\"\"\n\n\nclass RuntimeError(Exception):\n \"\"\"Raised when evaluation fails after compilation.\"\"\"\n\n def __init__(self, message: object = \"error\") -> None:\n self.value = message\n super().__init__(str(message))\n### jq_interpreter/evaluator.py\n\"\"\"Lazy evaluation boundary and lexical environment.\"\"\"\n\nfrom collections.abc import Iterator, Mapping\nfrom dataclasses import dataclass, field\nfrom functools import cmp_to_key\nimport json\nimport os\nimport sys\nimport time\nfrom typing import Any\n\nfrom .builtins import (builtin_indices, builtin_join, builtin_regex, builtin_split,\n builtin_tostring,\n builtin_format, default_builtins, _nondecnum, _value_description,\n _parse_strptime, json_text)\nfrom .errors import RuntimeError\nfrom .parser import Node, Program\n\n\nclass _BreakSignal(Exception):\n \"\"\"Internal non-local control transfer for a lexical jq label.\"\"\"\n\n def __init__(self, label: str):\n self.label = label\n\n\n@dataclass(frozen=True, slots=True)\nclass Environment:\n \"\"\"An immutable lexical frame with an optional enclosing environment.\"\"\"\n\n bindings: Mapping[str, Any] = field(default_factory=dict)\n parent: \"Environment | None\" = None\n functions: Mapping[tuple[str, int], Any] = field(default_factory=dict)\n runtime: \"RuntimeContext | None\" = None\n\n def get(self, name: str, default: Any = None) -> Any:\n if name in self.bindings:\n return self.bindings[name]\n if self.parent is not None:\n return self.parent.get(name, default)\n return default\n\n def child(self, **bindings: Any) -> \"Environment\":\n return Environment(bindings=dict(bindings), parent=self, functions=self.functions, runtime=self.runtime)\n\n def with_function(self, key: tuple[str, int], function: Any) -> \"Environment\":\n functions = dict(self.functions)\n functions[key] = function\n return Environment(bindings={}, parent=self, functions=functions, runtime=self.runtime)\n\n def function(self, name: str, arity: int) -> Any:\n if (name, arity) in self.functions:\n return self.functions[(name, arity)]\n if self.parent is not None:\n return self.parent.function(name, arity)\n return None\n\n\n@dataclass\nclass Function:\n name: str\n params: tuple[str, ...]\n body: Node\n closure: Environment | None = None\n\n\n@dataclass\nclass RuntimeContext:\n \"\"\"Invocation state shared by every input record evaluation.\"\"\"\n\n records: Iterator[Any]\n stderr: Any = sys.stderr\n startup_environment: Mapping[str, str] = field(default_factory=lambda: dict(os.environ))\n\n def next_input(self) -> Any:\n try:\n return next(self.records)\n except StopIteration as exc:\n raise RuntimeError(\"break\") from exc\n\n def remaining(self) -> Iterator[Any]:\n yield from self.records\n\n def write_debug(self, value: Any) -> None:\n self.stderr.write(json_text([\"DEBUG:\", value]) + \"\\n\")\n\n def write_raw(self, value: Any) -> None:\n self.stderr.write(json_text(value))\n\n\ndef evaluate(\n ast: Program, value: Any, environment: Environment | None = None\n) -> Iterator[Any]:\n \"\"\"Return a lazy result stream for an AST.\"\"\"\n\n if not isinstance(ast, Program) or ast.tree is None:\n return iter(())\n env = environment or Environment()\n\n def visit(node: Node, current: Any, scope: Environment) -> Iterator[Any]:\n if node.kind == \"program\":\n active = scope\n for directive in node.children[:-1]:\n if directive.kind == \"function\":\n active = define_function(directive, active)\n yield from visit(node.children[-1], current, active)\n elif node.kind == \"def\":\n active = define_function(node.children[0], scope)\n yield from visit(node.children[1], current, active)\n elif node.kind == \"dot\":\n yield current\n elif node.kind == \"recurse\":\n # ``..`` is recurse(.[]?), with the same depth-first ordering as\n # the library definition of recurse.\n yield current\n if isinstance(current, list):\n for child in current:\n yield from visit(Node(\"recurse\"), child, scope)\n elif isinstance(current, dict):\n for child in current.values():\n yield from visit(Node(\"recurse\"), child, scope)\n elif node.kind == \"literal\":\n yield node.value\n elif node.kind == \"null\":\n yield None\n elif node.kind == \"variable\":\n yield scope.get(node.value)\n elif node.kind == \"env_variable\":\n runtime = scope.runtime\n yield dict(runtime.startup_environment if runtime is not None else os.environ)\n elif node.kind == \"loc\":\n yield {\"file\": node.value[0], \"line\": node.value[1]}\n elif node.kind == \"filter_param\":\n bound = scope.get(\"@\" + node.value, _MISSING)\n if not isinstance(bound, FilterArgument):\n raise RuntimeError(f\"unknown filter parameter {node.value}\")\n yield from visit(bound.node, current, bound.scope)\n elif node.kind == \"bind\":\n source, pattern, downstream = node.children\n patterns = pattern.children if pattern.kind == \"pattern_alt\" else (pattern,)\n for source_value in visit(source, current, scope):\n for candidate in patterns:\n try:\n bindings = match_pattern(candidate, source_value)\n yield from visit(downstream, current, scope.child(**bindings))\n break\n except RuntimeError:\n continue\n elif node.kind == \"string\":\n values = [\"\"]\n for part in node.children:\n pieces = list(visit(part, current, scope))\n if node.value is None:\n values = [prefix + _stringify(piece) for prefix in values for piece in pieces]\n elif part.kind == \"literal\":\n # In @format \"...\", literal text is template syntax and is\n # deliberately left untouched; only interpolated results are escaped.\n values = [prefix + _stringify(piece) for prefix in values for piece in pieces]\n else:\n values = [prefix + builtin_format(piece, node.value) for prefix in values for piece in pieces]\n yield from values\n elif node.kind == \"format\":\n for piece in visit(node.children[0], current, scope):\n yield builtin_format(piece, node.value)\n elif node.kind == \"negate\":\n for operand in visit(node.children[0], current, scope):\n try:\n yield -_nondecnum(operand) if _is_number(operand) else -operand\n except (TypeError, ValueError) as exc:\n raise RuntimeError(\"cannot negate value\") from exc\n elif node.kind == \"binary\":\n yield from _binary(node.value, node.children[0], node.children[1], current, scope, visit)\n elif node.kind == \"comma\":\n yield from visit(node.children[0], current, scope)\n yield from visit(node.children[1], current, scope)\n elif node.kind == \"pipe\":\n for intermediate in visit(node.children[0], current, scope):\n yield from visit(node.children[1], intermediate, scope)\n elif node.kind == \"array\":\n values: list[Any] = []\n if node.children:\n values.extend(visit(node.children[0], current, scope))\n yield values\n elif node.kind == \"object\":\n objects: list[dict[str, Any]] = [{}]\n for pair in node.children:\n key_node, value_node = pair.children\n keys = list(visit(key_node, current, scope))\n values = list(visit(value_node, current, scope))\n expanded: list[dict[str, Any]] = []\n for partial in objects:\n for key in keys:\n if not isinstance(key, str):\n raise RuntimeError(\"object keys must be strings\")\n for value in values:\n result = dict(partial)\n result[key] = value\n expanded.append(result)\n objects = expanded\n yield from objects\n elif node.kind == \"index\":\n for base in visit(node.children[0], current, scope):\n for key in visit(node.children[1], base, scope):\n yield _index(base, key)\n elif node.kind == \"each\":\n for base in visit(node.children[0], current, scope):\n if isinstance(base, list):\n yield from base\n elif isinstance(base, dict):\n yield from base.values()\n else:\n raise RuntimeError(\"cannot iterate over this value\")\n elif node.kind == \"slice\":\n for base in visit(node.children[0], current, scope):\n starts = list(visit(node.children[1], base, scope))\n ends = list(visit(node.children[2], base, scope))\n for start in starts:\n for end in ends:\n yield _slice(base, start, end)\n elif node.kind == \"if\":\n # The condition is a generator: each condition result selects a branch\n # independently, and an empty condition produces no result.\n def select(condition_index: int) -> Iterator[Any]:\n condition = node.children[condition_index]\n then_branch = node.children[condition_index + 1]\n next_condition = condition_index + 2\n for condition_value in visit(condition, current, scope):\n if _truthy(condition_value):\n yield from visit(then_branch, current, scope)\n elif next_condition < len(node.children) - 1:\n yield from select(next_condition)\n else:\n yield from visit(node.children[-1], current, scope)\n\n yield from select(0)\n elif node.kind == \"optional\":\n try:\n yield from visit(node.children[0], current, scope)\n except RuntimeError:\n return\n### jq_interpreter/lexer.py\n\"\"\"Lexer for the jq source language.\"\"\"\n\nfrom collections.abc import Iterable, Iterator\nfrom dataclasses import dataclass\nimport json\nimport math\nimport re\nfrom typing import Any\n\nfrom .errors import CompileError\n\n\n@dataclass(frozen=True, slots=True)\nclass Token:\n \"\"\"A jq token with its decoded value and one-based source location.\"\"\"\n\n kind: str\n value: Any\n line: int\n column: int\n\n\n_NUMBER = re.compile(r\"(?:[0-9]+(?:\\.[0-9]*)?|\\.[0-9]+)(?:[eE][+-]?[0-9]+)?\")\n_IDENT = re.compile(r\"(?:[A-Za-z_][A-Za-z_0-9]*::)*[A-Za-z_][A-Za-z_0-9]*\")\n_FIELD = re.compile(r\"\\.[A-Za-z_][A-Za-z_0-9]*\")\n_BINDING = re.compile(r\"\\$(?:[A-Za-z_][A-Za-z_0-9]*::)*[A-Za-z_][A-Za-z_0-9]*\")\n_FORMAT = re.compile(r\"@[A-Za-z0-9_]+\")\n_WORDS = {\n \"as\": \"AS\", \"import\": \"IMPORT\", \"include\": \"INCLUDE\", \"module\": \"MODULE\",\n \"def\": \"DEF\", \"if\": \"IF\", \"then\": \"THEN\", \"else\": \"ELSE\", \"elif\": \"ELSE_IF\",\n \"and\": \"AND\", \"or\": \"OR\", \"end\": \"END\", \"reduce\": \"REDUCE\", \"foreach\": \"FOREACH\",\n \"try\": \"TRY\", \"catch\": \"CATCH\", \"label\": \"LABEL\", \"break\": \"BREAK\",\n}\n_MULTI = {\n \"!=\": \"NEQ\", \"==\": \"EQ\", \"|=\": \"SETPIPE\", \"+=\": \"SETPLUS\", \"-=\": \"SETMINUS\",\n \"*=\": \"SETMULT\", \"/=\": \"SETDIV\", \"%=\": \"SETMOD\", \"//=\": \"SETDEFINEDOR\",\n \"<=\": \"LESSEQ\", \">=\": \"GREATEREQ\", \"..\": \"REC\", \"?//\": \"ALTERNATION\", \"//\": \"DEFINEDOR\",\n}\n_PUNCTUATION = set(\".?=;,:|+-*/%$<>()[]{}\")\n\n\nclass _Scanner:\n def __init__(self, source: str):\n self.source, self.index, self.line, self.column = source, 0, 1, 1\n\n def position(self) -> tuple[int, int]:\n return self.line, self.column\n\n def advance(self, count: int = 1) -> str:\n text = self.source[self.index:self.index + count]\n for char in text:\n self.index += 1\n if char == \"\\n\":\n self.line, self.column = self.line + 1, 1\n else:\n self.column += 1\n return text\n\n def error(self, message: str = \"invalid character\") -> CompileError:\n return CompileError(f\"{message} at {self.line}:{self.column}\")\n\n def skip_space_and_comments(self) -> None:\n while self.index < len(self.source):\n if self.source[self.index] in \" \\r\\n\\t\":\n self.advance()\n continue\n if self.source[self.index] != \"#\":\n return\n self.advance()\n while self.index < len(self.source):\n char = self.source[self.index]\n if char == \"\\n\":\n self.advance()\n break\n if char == \"\\\\\":\n if self.source.startswith(\"\\\\\\r\\n\", self.index):\n self.advance(3)\n elif self.source.startswith(\"\\\\\\n\", self.index) or self.source.startswith(\"\\\\\\\\\", self.index):\n self.advance(2)\n else:\n self.advance()\n else:\n self.advance()\n\n def scan(self, stop: str | None = None) -> Iterator[Token]:\n while True:\n self.skip_space_and_comments()\n if self.index >= len(self.source):\n if stop is not None:\n raise self.error(f\"unterminated delimiter {stop!r}\")\n return\n if stop is not None and self.source[self.index] == stop:\n return\n line, column = self.position()\n text = self.source[self.index:]\n if text.startswith('\"'):\n yield from self.scan_string()\n continue\n matched = next((op for op in sorted(_MULTI, key=len, reverse=True) if text.startswith(op)), None)\n if matched:\n self.advance(len(matched))\n yield Token(_MULTI[matched], matched, line, column)\n continue\n if text.startswith(\"$__loc__\") and not re.match(r\"[A-Za-z0-9_]\", text[8:9]):\n self.advance(8)\n yield Token(\"LOC\", \"$__loc__\", line, column)\n continue\n match = _FORMAT.match(text)\n if match:\n spelling = match.group(); self.advance(len(spelling))\n yield Token(\"FORMAT\", spelling[1:], line, column); continue\n match = _NUMBER.match(text)\n if match:\n spelling = match.group(); self.advance(len(spelling))\n try: value = json.loads(spelling)\n except json.JSONDecodeError:\n try: value = float(spelling)\n except ValueError as exc: raise self.error(\"invalid number\") from exc\n if isinstance(value, float) and math.isinf(value):\n value = math.copysign(float.fromhex(\"0x1.fffffffffffffp+1023\"), value)\n yield Token(\"LITERAL\", value, line, column); continue\n match = _BINDING.match(text)\n if match:\n spelling = match.group(); self.advance(len(spelling))\n yield Token(\"BINDING\", spelling[1:], line, column); continue\n match = _FIELD.match(text)\n if match:\n spelling = match.group(); self.advance(len(spelling))\n yield Token(\"FIELD\", spelling[1:], line, column); continue\n match = _IDENT.match(text)\n if match:\n spelling = match.group(); self.advance(len(spelling))\n yield Token(_WORDS.get(spelling, \"IDENT\"), spelling, line, column); continue\n char = self.source[self.index]\n if char in \"([{\":\n self.advance(); yield Token(char, char, line, column)\n yield from self.scan_delimited({\"(\": \")\", \"[\": \"]\", \"{\": \"}\"}[char]); continue\n if char in \")]}\":\n if stop == char: return\n raise self.error(\"mismatched delimiter\")\n if char in _PUNCTUATION:\n self.advance(); yield Token(char, char, line, column); continue\n raise self.error()\n\n def scan_delimited(self, closing: str) -> Iterator[Token]:\n yield from self.scan(stop=closing)\n if self.index >= len(self.source): raise self.error(f\"unterminated delimiter {closing!r}\")\n line, column = self.position(); self.advance()\n yield Token(closing, closing, line, column)\n\n def scan_string(self) -> Iterator[Token]:\n line, column = self.position(); self.advance()\n yield Token(\"QQSTRING_START\", '\"', line, column)\n text_start = self.position(); parts: list[str] = []\n\n def emit_text() -> Iterator[Token]:\n if parts:\n value = \"\".join(parts); parts.clear()\n yield Token(\"QQSTRING_TEXT\", value, text_start[0], text_start[1])\n\n while self.index < len(self.source):\n char = self.source[self.index]\n if char == '\"':\n yield from emit_text(); end_line, end_column = self.position(); self.advance()\n yield Token(\"QQSTRING_END\", '\"', end_line, end_column); return\n if char == \"\\\\\":\n if self.source.startswith(\"\\\\(\", self.index):\n yield from emit_text(); start_line, start_column = self.position(); self.advance(2)\n yield Token(\"QQSTRING_INTERP_START\", \"\\\\(\", start_line, start_column)\n yield from self.scan_interpolation(); text_start = self.position(); continue\n escape_line, escape_column = self.position()\n if self.index + 1 >= len(self.source): raise self.error(\"unterminated string escape\")\n if self.source.startswith(\"\\\\u\", self.index):\n spelling = self.source[self.index:self.index + 6]\n if not re.fullmatch(r\"\\\\u[0-9a-fA-F]{4}\", spelling):\n raise self.error(\"invalid string escape\")\n else:\n spelling = self.source[self.index:self.index + 2]\n if spelling[1] not in '\"\\\\/bfnrt':\n raise CompileError(f\"invalid string escape at {escape_line}:{escape_column}\")\n try: parts.append(json.loads('\"' + spelling + '\"'))\n except json.JSONDecodeError as exc:\n raise CompileError(f\"invalid string escape at {escape_line}:{escape_column}\") from exc\n self.advance(len(spelling)); continue\n if char in \"\\r\\n\": raise self.error(\"unterminated string\")\n parts.append(char); self.advance()\n raise self.error(\"unterminated string\")\n\n def scan_interpolation(self) -> Iterator[Token]:\n yield from self.scan(stop=\")\")\n if self.index >= len(self.source): raise self.error(\"unterminated interpolation\")\n line, column = self.position(); self.advance()\n yield Token(\"QQSTRING_INTERP_END\", \")\", line, column)\n\n\ndef tokenize(source: str) -> Iterable[Token]:\n \"\"\"Yield jq tokens, rejecting invalid characters and unbalanced syntax.\"\"\"\n if not isinstance(source, str): raise TypeError(\"source must be text\")\n return _Scanner(source).scan()\n### jq_interpreter/parser.py\n\"\"\"Recursive-descent parser and static validator for jq programs.\"\"\"\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom typing import Any\n\nfrom .errors import CompileError\nfrom .lexer import Token, tokenize\n\n\n@dataclass(frozen=True, slots=True)\nclass Node:\n kind: str\n value: Any = None\n children: tuple[\"Node\", ...] = ()\n\n\n@dataclass(frozen=True, slots=True)\nclass Program:\n source: str\n tokens: tuple[Token, ...]\n tree: Node | None = None\n\n\n_OPS = {\"DEFINEDOR\": (1, \"//\"), \"OR\": (2, \"or\"), \"AND\": (3, \"and\"),\n \"EQ\": (4, \"==\"), \"NEQ\": (4, \"!=\"), \"<\": (4, \"<\"), \">\": (4, \">\"),\n \"LESSEQ\": (4, \"<=\"), \"GREATEREQ\": (4, \">=\"), \"+\": (5, \"+\"),\n \"-\": (5, \"-\"), \"*\": (6, \"*\"), \"/\": (6, \"/\"), \"%\": (6, \"%\"),\n \"=\": (0, \"=\"), \"SETPIPE\": (0, \"|=\"), \"SETPLUS\": (0, \"+=\"),\n \"SETMINUS\": (0, \"-=\"), \"SETMULT\": (0, \"*=\"), \"SETDIV\": (0, \"/=\"),\n \"SETMOD\": (0, \"%=\"), \"SETDEFINEDOR\": (0, \"//=\")}\n_KEYWORDS = {\"AS\", \"DEF\", \"MODULE\", \"IMPORT\", \"INCLUDE\", \"IF\", \"THEN\", \"ELSE\",\n \"ELSE_IF\", \"REDUCE\", \"FOREACH\", \"END\", \"AND\", \"OR\", \"TRY\", \"CATCH\",\n \"LABEL\", \"BREAK\"}\n\n\nclass _Parser:\n def __init__(self, source: str, tokens: tuple[Token, ...]):\n self.source, self.tokens, self.pos = source, tokens, 0\n self.scopes: list[set[str]] = [set()]\n self.labels: list[set[str]] = []\n self.functions: dict[str, int] = {}\n self.filter_params: list[set[str]] = []\n\n def current(self) -> Token | None:\n return self.tokens[self.pos] if self.pos < len(self.tokens) else None\n\n def accept(self, kind: str) -> Token | None:\n if self.current() and self.current().kind == kind:\n token = self.current(); self.pos += 1; return token\n return None\n\n def expect(self, kind: str, message: str | None = None) -> Token:\n token = self.accept(kind)\n if token is None:\n got = self.current(); place = \"end of input\" if got is None else f\"{got.kind!r} at {got.line}:{got.column}\"\n raise CompileError(message or f\"expected {kind!r}, got {place}\")\n return token\n\n def fail(self, message: str, token: Token | None = None) -> CompileError:\n token = token or self.current()\n return CompileError(message if token is None else f\"{message} at {token.line}:{token.column}\")\n\n def bound(self, name: str) -> bool:\n return any(name in scope for scope in reversed(self.scopes))\n\n def parse(self) -> Node:\n directives = []\n while self.current() and self.current().kind in {\"MODULE\", \"IMPORT\", \"INCLUDE\", \"DEF\"}:\n directives.append(self.parse_function() if self.current().kind == \"DEF\" else self.parse_directive())\n if self.current() is None: raise self.fail(\"program is empty\")\n query = self.query()\n if self.current(): raise self.fail(\"unexpected token\")\n return Node(\"program\", children=tuple(directives + [query]))\n\n def parse_directive(self) -> Node:\n tok = self.current(); self.pos += 1\n if tok.kind == \"MODULE\":\n metadata = self.query(); self.expect(\";\", \"module directive requires ';'\")\n if metadata.kind != \"object\": raise self.fail(\"module metadata must be a constant object\", tok)\n return Node(\"module\", children=(metadata,))\n path = self.string()\n if tok.kind == \"IMPORT\":\n self.expect(\"AS\", \"import requires 'as'\"); alias = self.expect(\"BINDING\").value\n else: alias = None\n self.expect(\";\", \"import/include directive requires ';'\")\n return Node(tok.kind.lower(), alias, (path,))\n\n def parse_function(self) -> Node:\n self.expect(\"DEF\"); name = self.expect(\"IDENT\").value; params = []\n if self.accept(\"(\") and not self.accept(\")\"):\n while True:\n tok = self.current()\n if not tok or tok.kind not in {\"IDENT\", \"BINDING\"}: raise self.fail(\"expected function parameter\")\n self.pos += 1; params.append((\"$\" if tok.kind == \"BINDING\" else \"\") + tok.value)\n if self.accept(\")\"): break\n self.expect(\";\", \"function parameters are separated by ';'\")\n self.expect(\":\", \"function definition requires ':'\"); self.functions[name] = len(params)\n self.scopes.append({name.lstrip(\"$\") for name in params})\n self.filter_params.append({name for name in params if not name.startswith(\"$\")})\n body = self.query(); self.filter_params.pop(); self.scopes.pop()\n self.expect(\";\", \"function definition requires ';'\")\n return Node(\"function\", (name, tuple(params)), (body,))\n\n def query(self) -> Node:\n if self.current() and self.current().kind == \"DEF\":\n definition = self.parse_function()\n return Node(\"def\", children=(definition, self.query()))\n left = self.pipe_expr()\n if self.accept(\"AS\"):\n patterns = [self.pattern()]\n while self.accept(\"ALTERNATION\"):\n patterns.append(self.pattern())\n pattern = patterns[0] if len(patterns) == 1 else Node(\"pattern_alt\", children=tuple(patterns))\n self.expect(\"|\", \"binding requires '|'\")\n self.scopes.append(self.names(pattern)); right = self.query(); self.scopes.pop()\n return Node(\"bind\", children=(left, pattern, right))\n return left\n\n def pipe_expr(self) -> Node:\n \"\"\"Parse pipes below comma expressions.\n\n jq applies a pipe to the complete comma expression on its left, so\n ``a,b | f`` means ``(a,b) | f``. Keeping this level separate from\n ``query`` also makes the same rule apply inside array constructors.\n \"\"\"\n left = self.comma_expr()\n if self.accept(\"|\"):\n return Node(\"pipe\", children=(left, self.pipe_expr()))\n return left\n\n def comma_expr(self) -> Node:\n left = self.expr()\n if self.accept(\",\"):\n return Node(\"comma\", children=(left, self.comma_expr()))\n return left\n\n def expr(self, minimum: int = 0) -> Node:\n left = self.term()\n while self.current() and self.current().kind in _OPS and _OPS[self.current().kind][0] >= minimum:\n tok = self.current(); precedence, spelling = _OPS[tok.kind]; self.pos += 1\n right = self.expr(precedence + (0 if precedence == 0 else 1)); left = Node(\"binary\", spelling, (left, right))\n return left\n\n def term(self) -> Node:\n node = self.atom()\n while True:\n if node.kind == \"dot\" and self.current() and self.current().kind in {\"QQSTRING_START\", \"FORMAT\"}:\n node = Node(\"index\", children=(node, self.string())); continue\n if self.accept(\"?\"): node = Node(\"optional\", children=(node,)); continue\n if self.accept(\"[\"):\n if self.accept(\"]\"): node = Node(\"each\", children=(node,)); continue\n first = Node(\"null\") if self.accept(\":\") else self.query()\n if first.kind == \"null\":\n last = self.query(); self.expect(\"]\")\n node = Node(\"slice\", children=(node, first, last)); continue\n if self.accept(\":\"):\n last = Node(\"null\") if self.accept(\"]\") else self.query()\n if last.kind != \"null\": self.expect(\"]\")\n node = Node(\"slice\", children=(node, first, last))\n else: self.expect(\"]\"); node = Node(\"index\", children=(node, first))\n continue\n if self.accept(\".\"):\n if self.accept(\"[\"):\n if self.accept(\"]\"): node = Node(\"each\", children=(node,))\n else:\n value = self.query(); self.expect(\"]\"); node = Node(\"index\", children=(node, value))\n elif self.current() and self.current().kind in {\"QQSTRING_START\", \"FORMAT\"}:\n node = Node(\"index\", children=(node, self.string()))\n else:\n raise self.fail(\"expected field name after '.'\")\n continue\n field = self.accept(\"FIELD\")\n if field: node = Node(\"index\", field.value, (node, Node(\"literal\", field.value))); continue\n break\n return node\n\n def atom(self) -> Node:\n tok = self.current()\n if tok is None: raise self.fail(\"expected expression\")\n if tok.kind == \"-\": self.pos += 1; return Node(\"negate\", children=(self.term(),))\n if tok.kind == \"LITERAL\": self.pos += 1; return Node(\"literal\", tok.value)\n if tok.kind == \"FIELD\": self.pos += 1; return Node(\"index\", tok.value, (Node(\"dot\"), Node(\"literal\", tok.value)))\n if tok.kind == \".\": self.pos += 1; return Node(\"dot\")\n if tok.kind == \"REC\": self.pos += 1; return Node(\"recurse\")\n if tok.kind == \"BINDING\":\n self.pos += 1\n if tok.value == \"ENV\": return Node(\"env_variable\")\n if not self.bound(tok.value): raise self.fail(f\"unknown variable ${tok.value}\", tok)\n return Node(\"variable\", tok.value)\n if tok.kind == \"LOC\":\n self.pos += 1\n return Node(\"loc\", (\"<top-level>\", tok.line))\n if tok.kind == \"FORMAT\":\n self.pos += 1\n if self.current() and self.current().kind == \"QQSTRING_START\":\n formatted = self.string()\n return Node(\"string\", tok.value, formatted.children)\n return Node(\"format\", tok.value, (Node(\"dot\"),))\n if tok.kind == \"QQSTRING_START\": return self.string()\n if tok.kind == \"IDENT\":\n self.pos += 1; name = tok.value\n if name in {\"true\", \"false\", \"null\"}: return Node(\"literal\", {\"true\": True, \"false\": False, \"null\": None}[name])\n if any(name in params for params in reversed(self.filter_params)):\n return Node(\"filter_param\", name)\n args = []\n if self.accept(\"(\") and not self.accept(\")\"):\n while True:\n args.append(self.query())\n if self.accept(\")\"): break\n self.expect(\";\", \"function arguments are separated by ';'\")\n if name in self.functions and self.functions[name] != len(args):\n raise self.fail(\"function arity mismatch\", tok)\n return Node(\"call\", (name, len(args)), tuple(args))\n if tok.kind == \"(\": self.pos += 1; value = self.query(); self.expect(\")\"); return value\n if tok.kind == \"[\":\n self.pos += 1\n if self.accept(\"]\"): return Node(\"array\")\n value = self.query(); self.expect(\"]\"); return Node(\"array\", children=(value,))\n if tok.kind == \"{\": return self.object()\n if tok.kind == \"IF\": return self.if_expr()\n if tok.kind in {\"TRY\", \"REDUCE\", \"FOREACH\", \"LABEL\", \"BREAK\"}: return self.control()\n raise self.fail(\"expected expression\", tok)\n\n def string(self) -> Node:\n fmt = None\n if self.accept(\"FORMAT\"): fmt = self.tokens[self.pos - 1].value\n self.expect(\"QQSTRING_START\"); parts = []\n while self.current() and self.current().kind != \"QQSTRING_END\":\n text = self.accept(\"QQSTRING_TEXT\")\n if text: parts.append(Node(\"literal\", text.value)); continue\n if self.accept(\"QQSTRING_INTERP_START\"):\n parts.append(self.query()); self.expect(\"QQSTRING_INTERP_END\"); continue\n raise self.fail(\"invalid string interpolation\")\n self.expect(\"QQSTRING_END\"); return Node(\"string\", fmt, tuple(parts))\n\n def object(self) -> Node:\n self.expect(\"{\"); pairs = []\n if self.accept(\"}\"): return Node(\"object\")\n while True:\n### pyproject.toml\n[project]\nname = \"jq\"\nversion = \"0.1.0\"\nrequires-python = \">=3.11\"\ndependencies = []\n\n[tool.pytest.ini_options]\ntestpaths = [\"tests\"]\naddopts = \"-q\"\n### tests/conftest.py\n\"\"\"Make the source package importable when pytest is launched from any cwd.\"\"\"\n\nimport sys\nfrom pathlib import Path\n\nROOT = Path(__file__).resolve().parents[1]\nif str(ROOT) not in sys.path:\n sys.path.insert(0, str(ROOT))\n### tests/test_assignment.py\nimport pytest\n\nfrom jq_interpreter.errors import RuntimeError\nfrom jq_interpreter.evaluator import evaluate\nfrom jq_interpreter.parser import parse\n\n\ndef results(program, value):\n return list(evaluate(parse(program), value))\n\n\ndef test_setpath_creates_missing_objects_and_arrays_without_mutating_input():\n original = {\"kept\": True}\n assert results('setpath([\"foo\", 1]; 7)', original) == [\n {\"kept\": True, \"foo\": [None, 7]}\n ]\n assert original == {\"kept\": True}\n\n\ndef test_delpaths_deletes_multiple_array_locations_from_right_to_left():\n assert results(\"delpaths([[1], [3]])\", [0, 1, 2, 3, 4]) == [[0, 2, 4]]\n\n\ndef test_del_derives_paths_and_missing_paths_are_idempotent():\n value = {\"a\": 1, \"b\": 2}\n assert results(\"del(.a)\", value) == [{\"b\": 2}]\n assert results(\"del(.missing)\", value) == [value]\n\n\ndef test_plain_assignment_uses_original_input_for_each_rhs_result():\n assert results(\".a = (.b, .b + 1)\", {\"a\": 0, \"b\": 2}) == [\n {\"a\": 2, \"b\": 2}, {\"a\": 3, \"b\": 2}\n ]\n\n\ndef test_update_assignment_uses_first_result_and_deletes_on_empty():\n assert results(\".a |= (.+1, .+2)\", {\"a\": 2}) == [{\"a\": 3}]\n assert results(\".a |= empty\", {\"a\": 2}) == [{}]\n\n\ndef test_slice_assignment_replaces_the_selected_range():\n assert results('.[1:3] = [\"x\"]', [0, 1, 2, 3]) == [[0, \"x\", 3]]\n\n\n@pytest.mark.parametrize(\"program\", [\"setpath(0; 1)\", \"delpaths(0)\"])\ndef test_path_mutation_rejects_non_array_paths(program):\n with pytest.raises(RuntimeError):\n results(program, {})\n### tests/test_bindings.py\nfrom jq_interpreter.evaluator import evaluate\nfrom jq_interpreter.parser import parse\n\n\ndef results(program, value=None):\n return list(evaluate(parse(program), value))\n\n\ndef test_lexical_bindings_keep_original_input_and_generator_order():\n assert results(\"1 as $x | 2 as $y | [$x, $y, $x]\") == [[1, 2, 1]]\n\n\ndef test_array_and_object_patterns_fill_missing_values():\n assert results(\". as [$a, {c:$b, b:$c}] | [$a,$b,$c]\", [1, {\"c\": 3}]) == [[1, 3, None]]\n\n\ndef test_destructuring_alternatives_retry_after_pattern_failure():\n program = \". as {a:$a} ?// [$a] ?// $a | $a\"\n assert results(program, {\"a\": 4}) == [4]\n assert results(program, [7]) == [7]\n assert results(program, \"value\") == [\"value\"]\n\n\ndef test_filter_and_value_parameters_use_their_distinct_scopes():\n assert results(\"def twice($x): $x + $x; twice(3)\") == [6]\n assert results(\"def apply(f): f | f; apply(. + 1)\", 2) == [4]\n\n\ndef test_functions_capture_lexical_scope_and_recurse():\n assert results(\"def fac: if . == 1 then 1 else . * (. - 1 | fac) end; fac\", 5) == [120]\n### tests/test_collections.py\nimport pytest\n\nfrom jq_interpreter.errors import RuntimeError\nfrom jq_interpreter.evaluator import evaluate\nfrom jq_interpreter.parser import parse\n\n\ndef result(program, value):\n return list(evaluate(parse(program), value))\n\n\n@pytest.mark.parametrize(\"program,value,expected\", [\n (\"keys\", {\"z\": 1, \"a\": 2}, [[\"a\", \"z\"]]),\n (\"keys\", [\"a\", \"b\"], [[0, 1]]),\n (\"map(has(1))\", [[0], [0, 1]], [[False, True]]),\n (\"to_entries\", {\"a\": 1}, [[{\"key\": \"a\", \"value\": 1}]]),\n (\"from_entries\", [{\"Key\": \"a\", \"Value\": 1}], [{\"a\": 1}]),\n (\"map_values(.+1)\", [1, 2], [[2, 3]]),\n (\"map_values(if . == 1 then empty else . end)\", [1, 2], [[2]]),\n (\"sort\", [3, None, 1], [[None, 1, 3]]),\n (\"unique\", [2, 1, 2, 1], [[1, 2]]),\n (\"flatten(1)\", [0, [1, [2]]], [[0, 1, [2]]]),\n (\"transpose\", [[1], [2, 3]], [[[1, 2], [None, 3]]]),\n (\"contains({a: {b: 1}})\", {\"a\": {\"b\": 1, \"c\": 2}}, [True]),\n (\"add\", [1, 2, 3], [6]),\n (\"any(. > 2)\", [1, 3], [True]),\n (\"all(. > 0)\", [1, 3], [True]),\n (\"bsearch(2)\", [1, 3], [-2]),\n])\ndef test_collection_builtin_behavior(program, value, expected):\n assert result(program, value) == expected\n\n\ndef test_collection_builtins_reject_non_array_sort_input():\n with pytest.raises(RuntimeError):\n result(\"sort\", {\"a\": 1})\n### tests/test_conversion.py\nimport io\n\nimport pytest\n\nfrom jq_interpreter.command import main\nfrom jq_interpreter.errors import RuntimeError\nfrom jq_interpreter.evaluator import evaluate\nfrom jq_interpreter.parser import parse\n\n\ndef result(program, value):\n return list(evaluate(parse(program), value))\n\n\n@pytest.mark.parametrize(\n (\"program\", \"value\", \"expected\"),\n [\n (\"type\", None, \"null\"),\n (\"type\", True, \"boolean\"),\n (\"type\", 1, \"number\"),\n (\"type\", \"x\", \"string\"),\n (\"type\", [], \"array\"),\n (\"type\", {}, \"object\"),\n (\"length\", None, 0),\n (\"length\", -4, 4),\n (\"length\", \"μ\", 1),\n (\"length\", [1, 2], 2),\n (\"length\", {\"a\": 1}, 1),\n (\"utf8bytelength\", \"μ\", 2),\n (\"tonumber\", \" +5.43 \", 5.43),\n (\"toboolean\", \"false\", False),\n (\"tostring\", {\"a\": 1}, '{\"a\":1}'),\n (\"tojson\", \"x\", '\"x\"'),\n (\"fromjson\", '{\"a\":1}', {\"a\": 1}),\n (\"explode\", \"Aμ\", [65, 956]),\n (\"implode\", [65, 956], \"Aμ\"),\n ],\n)\ndef test_conversion_builtin_returns_expected_value(program, value, expected):\n assert result(program, value) == [expected]\n\n\ndef test_implode_replaces_invalid_codepoints_and_rounds_numbers_down():\n assert result(\"implode\", [-1, 1.9, 0xD800, 0x10FFFF + 1]) == [\"�\\x01��\"]\n\n\n@pytest.mark.parametrize(\n (\"program\", \"value\"),\n [\n (\"length\", True),\n (\"utf8bytelength\", 1),\n (\"tonumber\", \"not-a-number\"),\n (\"toboolean\", 1),\n (\"fromjson\", \"{'a': 1}\"),\n (\"explode\", []),\n (\"implode\", [\"a\"]),\n ],\n)\ndef test_conversion_builtin_rejects_invalid_input(program, value):\n with pytest.raises(RuntimeError):\n result(program, value)\n\n\ndef test_command_accepts_jq_special_numeric_input_and_serializes_nan_as_null():\n output = io.StringIO()\n assert main([\"-c\", \"tojson | fromjson\"], io.StringIO('{\"a\":nan}\\n'), output, io.StringIO()) == 0\n assert output.getvalue().splitlines() == ['{\"a\":null}']\n### tests/test_dates.py\nimport pytest\n\nfrom jq_interpreter.errors import RuntimeError\nfrom jq_interpreter.evaluator import evaluate\nfrom jq_interpreter.parser import parse\n\n\ndef values(program, input_value):\n return list(evaluate(parse(program), input_value))\n\n\ndef test_gmtime_preserves_fractional_epoch_seconds():\n assert values(\"gmtime\", 1425599507.25) == [[2015, 2, 5, 23, 51, 47.25, 4, 63]]\n\n\ndef test_strptime_and_mktime_round_trip_utc():\n program = 'strptime(\"%Y-%m-%dT%H:%M:%SZ\") | mktime'\n assert values(program, \"2015-03-05T23:51:47Z\") == [1425599507]\n\n\ndef test_strftime_accepts_short_broken_down_time():\n assert values('strftime(\"%Y-%m-%dT%H:%M:%SZ\")', [2024, 2, 15]) == [\"2024-03-15T00:00:00Z\"]\n\n\ndef test_iso8601_aliases_convert_both_directions():\n assert values(\"fromdateiso8601\", \"2015-03-05T23:51:47Z\") == [1425599507]\n assert values(\"todate\", 1425599507) == [\"2015-03-05T23:51:47Z\"]\n\n\n@pytest.mark.parametrize(\"program\", [\"gmtime\", \"localtime\", \"mktime\"])\ndef test_date_builtins_reject_unparsed_inputs(program):\n with pytest.raises(RuntimeError):\n values(program, \"not-a-date\")\n\n\ndef test_strptime_rejects_non_string_format():\n with pytest.raises(RuntimeError):\n values(\"strptime([])\", \"2015-03-05T23:51:47Z\")\n### tests/test_evaluator.py\nimport io\n\nimport pytest\n\nfrom jq_interpreter.command import main\nfrom jq_interpreter.errors import RuntimeError as JqRuntimeError\nfrom jq_interpreter.evaluator import evaluate\nfrom jq_interpreter.parser import parse\n\n\ndef test_literals_and_empty_are_generators():\n value = {\"item\": [1, 2]}\n assert list(evaluate(parse(\"true\"), value)) == [True]\n assert list(evaluate(parse(\"null\"), value)) == [None]\n assert list(evaluate(parse(\"1\"), value)) == [1]\n assert list(evaluate(parse(\"empty\"), value)) == []\n assert list(evaluate(parse(\"-1\"), value)) == [-1]\n\n\ndef test_comma_evaluates_each_branch_against_original_input():\n value = {\"item\": [1, 2]}\n assert list(evaluate(parse(\"., .\"), value)) == [value, value]\n assert list(evaluate(parse(\"1, 2\"), value)) == [1, 2]\n\n\ndef test_pipe_runs_downstream_once_per_upstream_value():\n assert list(evaluate(parse(\"1, 2 | .\"), 7)) == [1, 2]\n assert list(evaluate(parse(\"(1, 2) | empty\"), 7)) == []\n\n\ndef test_array_constructor_collects_all_outputs_and_empty():\n assert list(evaluate(parse(\"[1, 2, empty]\"), None)) == [[1, 2]]\n assert list(evaluate(parse(\"[empty]\"), None)) == [[]]\n\n\ndef test_object_constructor_uses_shorthand_and_generator_combinations():\n value = {\"a\": \"one\", \"b\": \"two\"}\n assert list(evaluate(parse(\"{a, b: .a}\"), value)) == [{\"a\": \"one\", \"b\": \"one\"}]\n assert list(evaluate(parse(\"{(.a, .b): 0}\"), value)) == [\n {\"one\": 0}, {\"two\": 0}\n ]\n\n\ndef test_collection_lookup_iteration_and_missing_values():\n value = {\"items\": [10, 20], \"name\": \"abc\"}\n assert list(evaluate(parse(\".items[1]\"), value)) == [20]\n assert list(evaluate(parse(\".items[-1]\"), value)) == [20]\n assert list(evaluate(parse(\".items[9]\"), value)) == [None]\n assert list(evaluate(parse(\".items[]\"), value)) == [10, 20]\n assert list(evaluate(parse(\".missing\"), value)) == [None]\n\n\ndef test_collection_slices_support_omitted_and_negative_bounds():\n value = [0, 1, 2, 3]\n assert list(evaluate(parse(\".[:2]\"), value)) == [[0, 1]]\n assert list(evaluate(parse(\".[-2:]\"), value)) == [[2, 3]]\n assert list(evaluate(parse(\".[1:3]\"), value)) == [[1, 2]]\n assert list(evaluate(parse(\"\\\"abcd\\\"[1:3]\"), None)) == [\"bc\"]\n\n\ndef test_generator_is_lazy_and_keeps_values_before_runtime_error():\n stream = iter(evaluate(parse(\"., error\"), 7))\n assert next(stream) == 7\n with pytest.raises(JqRuntimeError):\n next(stream)\n\n\ndef test_command_emits_compact_values_and_returns_runtime_status():\n output = io.StringIO()\n errors = io.StringIO()\n assert main([\"-c\", \"1, .\"], io.StringIO(\"7\\n\"), output, errors) == 0\n assert output.getvalue().splitlines() == [\"1\", \"7\"]\n\n output = io.StringIO()\n assert main([\"-c\", \"., error\"], io.StringIO(\"7\\n\"), output, errors) == 5\n assert output.getvalue().splitlines() == [\"7\"]\n\n\ndef test_command_accepts_a_leading_input_bom():\n output = io.StringIO()\n assert main([\"-c\", \".\"], io.StringIO('\\ufeff\"byte order mark\"\\n'), output, io.StringIO()) == 0\n assert output.getvalue().splitlines() == ['\"byte order mark\"']\n\n\ndef test_arithmetic_supports_jq_collection_and_null_rules():\n assert list(evaluate(parse(\"null + 2\"), None)) == [2]\n assert list(evaluate(parse(\"[1, 2] + [3]\"), None)) == [[1, 2, 3]]\n assert list(evaluate(parse('{\"a\": 1} + {\"b\": 2}'), None)) == [{\"a\": 1, \"b\": 2}]\n assert list(evaluate(parse(\"[1, 2, 1] - [1]\"), None)) == [[2]]\n assert list(evaluate(parse('\"ab\" * 3'), None)) == [\"ababab\"]\n\n\ndef test_comparison_distinguishes_boolean_and_numeric_values():\n assert list(evaluate(parse(\"1 == 1.0, true == 1, [1] == [1.0]\"), None)) == [True, False, True]\n assert list(evaluate(parse(\"null < false, false < 0, 0 < \\\"x\\\"\"), None)) == [True, True, True]\n assert list(evaluate(parse('{\"b\": 1} < {\"a\": 9}'), None)) == [False]\n\n\ndef test_binary_filters_form_combinations_in_jq_order():\n assert list(evaluate(parse(\"(1, 2) + (10, 20)\"), None)) == [11, 21, 12, 22]\n\n\ndef test_boolean_and_defined_or_short_circuit():\n assert list(evaluate(parse(\"false and error\"), None)) == [False]\n assert list(evaluate(parse(\"true or error\"), None)) == [True]\n assert list(evaluate(parse(\"null // 7\"), None)) == [7]\n assert list(evaluate(parse(\"4 // error\"), None)) == [4]\n\n\ndef test_if_selects_branches_for_each_condition_output_and_defaults_to_identity():\n assert list(evaluate(parse(\"[if 1,null,2 then 3 else 4 end]\"), None)) == [[3, 4, 3]]\n assert list(evaluate(parse(\"[if false then 3 end]\"), \"input\")) == [[\"input\"]]\n assert list(evaluate(parse(\"[if false then 3 elif true then 4 else 5 end]\"), None)) == [[4]]\n\n\ndef test_optional_suppresses_only_errors_and_alternative_uses_all_usable_values():\n assert list(evaluate(parse(\"error(0)?\"), None)) == []\n assert list(evaluate(parse(\"(null, false, 2) // 7\"), None)) == [2]\n assert list(evaluate(parse(\"(empty, null) // 7\"), None)) == [7]\n\n\ndef test_try_catch_preserves_partial_output_and_passes_error_value_to_handler():\n assert list(evaluate(parse(\"try (., error(0)) catch .\"), \"before\")) == [\"before\", 0]\n assert list(evaluate(parse(\"try error(0) // 1\"), None)) == [1]\n assert list(evaluate(parse(\"try error(\\\"boom\\\") catch .\"), None)) == [\"boom\"]\n assert list(evaluate(parse(\"try error catch .\"), \"input\")) == [\"input\"]\n\n\n@pytest.mark.parametrize(\"source\", [\"1 / 0\", '\"x\" + 1', \"1 % 0\"])\ndef test_invalid_operator_combinations_are_runtime_errors(source):\n with pytest.raises(JqRuntimeError):\n list(evaluate(parse(source), None))\n### tests/test_formats.py\nimport pytest\n\nfrom jq_interpreter.errors import RuntimeError\nfrom jq_interpreter.evaluator import evaluate\nfrom jq_interpreter.parser import parse\n\n\ndef result(program, value):\n return list(evaluate(parse(program), value))\n\n\n@pytest.mark.parametrize(\"program,value,expected\", [\n (\"@text\", {\"a\": 1}, ['{\"a\":1}']),\n (\"@json\", \"é\", ['\"é\"']),\n (\"@html\", \"!()<>&'\\\"\\t\", [\"!()<>&'"\\t\"]),\n (\"@uri\", \"μ\", [\"%CE%BC\"]),\n (\"@urid\", \"%CE%BC\", [\"μ\"]),\n (\"@csv\", [1, \"a\\\"b\", None], ['1,\"a\"\"b\",']),\n (\"@tsv\", [\"a\\tb\", \"c\\n\", None], [\"a\\\\tb\\tc\\\\n\\t\"]),\n (\"@sh\", [\"O'Hara\", \"x\"], [\"'O'\\\\''Hara' 'x'\"]),\n (\"@base64\", \"foóbar\\n\", [\"Zm/Ds2Jhcgo=\"]),\n (\"@base64d\", \"Zm/Ds2Jhcgo=\", [\"foóbar\\n\"]),\n])\ndef test_format_filters(program, value, expected):\n assert result(program, value) == expected\n\n\ndef test_formatted_string_keeps_literals_unescaped_and_escapes_interpolation():\n assert result('@uri \"https://example.test/?q=\\\\(.)\"', \"what is jq?\") == [\n \"https://example.test/?q=what%20is%20jq%3F\"\n ]\n\n\ndef test_format_preserves_interpolation_generator_order():\n assert result('@html \"x\\\\(.[])\"', [\"<\", \">\", \"&\"]) == [\n \"x<\", \"x>\", \"x&\"\n ]\n\n\n@pytest.mark.parametrize(\"program,value\", [(\"@csv\", \"x\"), (\"@tsv\", {}), (\"@urid\", \"%FF\"), (\"@base64d\", \"!\")])\ndef test_format_rejects_invalid_input(program, value):\n with pytest.raises(RuntimeError):\n result(program, value)\n### tests/test_foundation.py\nimport io\n\nimport pytest\n\nfrom jq_interpreter.errors import CompileError, RuntimeError as JqRuntimeError\nfrom jq_interpreter.evaluator import Environment, evaluate\nfrom jq_interpreter.lexer import Token, tokenize\nfrom jq_interpreter.parser import Program, parse\n\n\ndef test_foundation_errors_are_distinct_exception_types():\n assert issubclass(CompileError, Exception)\n assert issubclass(JqRuntimeError, Exception)\n assert CompileError is not JqRuntimeError\n assert not issubclass(CompileError, JqRuntimeError)\n assert not issubclass(JqRuntimeError, CompileError)\n\n\ndef test_tokenize_preserves_order_and_locations():\n assert list(tokenize(\"a\\n b\")) == [\n Token(\"IDENT\", \"a\", 1, 1),\n Token(\"IDENT\", \"b\", 2, 2),\n ]\n\n\ndef test_parse_returns_program_ast():\n ast = parse(\".\")\n assert isinstance(ast, Program)\n assert ast.source == \".\"\n assert [token.value for token in ast.tokens] == [\".\"]\n\n\ndef test_parse_rejects_non_text_source():\n with pytest.raises(CompileError):\n parse(None) # type: ignore[arg-type]\n\n\ndef test_environment_is_lexically_scoped_without_mutating_parent():\n parent = Environment({\"outer\": 1, \"shared\": \"parent\"})\n child = parent.child(shared=\"child\", inner=2)\n assert parent.get(\"shared\") == \"parent\"\n assert child.get(\"outer\") == 1\n assert child.get(\"shared\") == \"child\"\n assert child.get(\"inner\") == 2\n\n\ndef test_evaluate_returns_lazy_identity_stream():\n results = evaluate(parse(\".\"), {\"ok\": True})\n assert iter(results) is results\n assert list(results) == [{\"ok\": True}]\n\n\ndef test_command_boundary_is_importable():\n from jq_interpreter.command import main\n\n output = io.StringIO()\n assert main([\"-c\", \".\"], io.StringIO(\"1\\n\"), output, io.StringIO()) == 0\n assert output.getvalue() == \"1\\n\"\n### tests/test_generator_control.py\nimport pytest\n\nfrom jq_interpreter.errors import RuntimeError\nfrom jq_interpreter.evaluator import evaluate\nfrom jq_interpreter.parser import parse\n\n\ndef results(program, value):\n return list(evaluate(parse(program), value))\n\n\ndef test_reduce_accumulates_source_values_in_order():\n assert results(\"reduce .[] as $x (0; . + $x)\", [1, 2, 4]) == [7]\n\n\ndef test_reduce_keeps_multiple_initializer_and_update_states():\n assert results(\"reduce .[] as $x (0, 10; ., . + $x)\", [1]) == [0, 1, 10, 11]\n\n\ndef test_foreach_emits_each_intermediate_accumulator():\n assert results(\"foreach .[] as $x (0; . + $x)\", [1, 2, 3]) == [1, 3, 6]\n\n\ndef test_foreach_extracts_each_intermediate_state():\n assert results(\"foreach .[] as $x (0; . + $x; . * 2)\", [1, 2]) == [2, 6]\n\n\ndef test_label_break_stops_targeted_generator_and_preserves_prior_values():\n assert results(\"label $done | .[] | if . > 1 then break $done else . end\", [0, 1, 2, 3]) == [0, 1]\n\n\n@pytest.mark.parametrize(\n (\"program\", \"expected\"),\n [\n (\"limit(3; .[])\", [1, 2, 3]),\n (\"skip(2; .[])\", [3, 4]),\n (\"first(.[])\", [1]),\n (\"last(.[])\", [4]),\n (\"nth(2; .[])\", [3]),\n ],\n)\ndef test_bounded_generator_consumers(program, expected):\n assert results(program, [1, 2, 3, 4]) == expected\n\n\ndef test_bounded_consumers_do_not_evaluate_unneeded_source_values():\n assert results('first(1, error(\"unneeded\"))', None) == [1]\n assert results('nth(1; 0, 1, error(\"unneeded\"))', None) == [1]\n assert results(\"limit(0; error)\", None) == []\n\n\n@pytest.mark.parametrize(\"program\", [\"limit(-1; .)\", \"skip(-1; .)\", \"nth(-1; .)\"])\ndef test_bounded_consumers_reject_negative_counts(program):\n with pytest.raises(RuntimeError):\n results(program, 1)\n### tests/test_input_diagnostics.py\nimport io\n\nfrom jq_interpreter.command import main\n\n\ndef run(program, data, monkeypatch=None):\n output, errors = io.StringIO(), io.StringIO()\n if monkeypatch is not None:\n monkeypatch.setenv(\"JQ_IO_TEST\", \"startup\")\n status = main([\"-c\", program], io.StringIO(data), output, errors)\n return status, output.getvalue().splitlines(), errors.getvalue()\n\n\ndef test_input_and_inputs_share_the_remaining_record_stream():\n status, output, errors = run(\"., input, inputs\", \"1\\n2\\n3\\n\")\n assert (status, output, errors) == (0, [\"1\", \"2\", \"3\"], \"\")\n\n\ndef test_input_exhaustion_is_catchable():\n status, output, errors = run(\"try input catch .\", \"1\\n\")\n assert (status, output, errors) == (0, ['\"break\"'], \"\")\n\n\ndef test_environment_binding_and_filter_are_available(monkeypatch):\n status, output, errors = run(\"[$ENV.JQ_IO_TEST, env.JQ_IO_TEST]\", \"null\\n\", monkeypatch)\n assert status == 0\n assert output == ['[\"startup\",\"startup\"]']\n assert errors == \"\"\n\n\ndef test_location_reports_source_line():\n status, output, errors = run(\"1,\\n$__loc__\", \"null\\n\")\n assert (status, output, errors) == (0, [\"1\", '{\"file\":\"<top-level>\",\"line\":2}'], \"\")\n\n\ndef test_debug_and_stderr_preserve_values_and_use_stderr():\n status, output, errors = run(\"debug, stderr\", '{\"a\":1}\\n')\n assert status == 0\n assert output == ['{\"a\":1}', '{\"a\":1}']\n assert errors == '[\"DEBUG:\",{\"a\":1}]\\n{\"a\":1}'\n\n### tests/test_lexer.py\nimport pytest\n\nfrom jq_interpreter.errors import CompileError\nfrom jq_interpreter.lexer import Token, tokenize\n\n\ndef test_lexer_locations_ignore_comments_and_whitespace():\n tokens = list(tokenize(\"1 # comment\\n2\"))\n numbers = [token for token in tokens if token.kind == \"LITERAL\"]\n assert [token.value for token in numbers] == [1, 2]\n assert [(token.line, token.column) for token in numbers] == [(1, 1), (2, 1)]\n\n\ndef test_lexer_recognizes_keywords_operators_and_namespaced_bindings():\n tokens = list(tokenize(\"def f: .foo as $ns::value | .; reduce . as $x (0; .);\"))\n assert [token.kind for token in tokens] == [\n \"DEF\", \"IDENT\", \":\", \"FIELD\", \"AS\", \"BINDING\", \"|\", \".\", \";\",\n \"REDUCE\", \".\", \"AS\", \"BINDING\", \"(\", \"LITERAL\", \";\", \".\", \")\", \";\",\n ]\n assert tokens[3].value == \"foo\"\n assert tokens[5].value == \"ns::value\"\n\n\ndef test_lexer_decodes_numbers_formats_and_string_escapes():\n assert list(tokenize('@csv 1.25e2 \"line\\\\n\\\\u0041\"')) == [\n Token(\"FORMAT\", \"csv\", 1, 1),\n Token(\"LITERAL\", 125.0, 1, 6),\n Token(\"QQSTRING_START\", '\"', 1, 13),\n Token(\"QQSTRING_TEXT\", \"line\\nA\", 1, 14),\n Token(\"QQSTRING_END\", '\"', 1, 26),\n ]\n\n\ndef test_lexer_emits_interpolation_boundaries_and_nested_delimiters():\n tokens = list(tokenize('\"hello \\\\(.[0])!\"'))\n assert [(token.kind, token.value) for token in tokens] == [\n (\"QQSTRING_START\", '\"'), (\"QQSTRING_TEXT\", \"hello \"),\n (\"QQSTRING_INTERP_START\", \"\\\\(\"), (\".\", \".\"), (\"[\", \"[\"),\n (\"LITERAL\", 0), (\"]\", \"]\"), (\"QQSTRING_INTERP_END\", \")\"),\n (\"QQSTRING_TEXT\", \"!\"), (\"QQSTRING_END\", '\"'),\n ]\n\n\n@pytest.mark.parametrize(\"source\", [r'\"\\v\"', \"(\", \"]\", '\"bad\\\\u12\"', '\"unterminated'])\ndef test_lexer_rejects_invalid_escapes_strings_and_delimiters(source):\n with pytest.raises(CompileError):\n list(tokenize(source))\n\n\ndef test_lexer_supports_backslash_continued_comments():\n assert [token.value for token in tokenize(\"1 # ignored\\\\\\ncomment\\n2\")] == [1, 2]\n### tests/test_numeric.py\nfrom jq_interpreter.evaluator import evaluate\nfrom jq_interpreter.parser import parse\n\n\ndef result(program, value=None):\n return list(evaluate(parse(program), value))\n\n\ndef test_pipe_applies_to_every_value_in_comma_expression_inside_array():\n assert result(\"[1, 2 | tostring]\") == [[\"1\", \"2\"]]\n\n\ndef test_nan_modulo_preserves_nan_for_either_operand():\n assert result(\"[nan % 1, 1 % nan | isnan]\") == [[True, True]]\n\n\ndef test_nondecnum_overflow_is_clamped_before_serialization():\n assert result(\"[1E+1000,-1E+1000 | tojson]\") == [[\n \"1.7976931348623157e+308\", \"-1.7976931348623157e+308\"\n ]]\n### tests/test_parser.py\nimport pytest\n\nfrom jq_interpreter.errors import CompileError\nfrom jq_interpreter.parser import Node, Program, parse\n\n\ndef test_parser_accepts_composed_expression_without_evaluation():\n tree = parse(\"(1, 2) | .\")\n assert isinstance(tree, Program)\n assert tree.tree is not None\n assert tree.tree.kind == \"program\"\n assert tree.tree.children[0].kind == \"pipe\"\n\n\n@pytest.mark.parametrize(\"source\", [\"{\", \". as $x | $missing\", \"break $missing\"])\ndef test_parser_rejects_syntax_and_static_scope_errors(source):\n with pytest.raises(CompileError):\n parse(source)\n\n\ndef test_parser_preserves_precedence_and_generator_nodes():\n tree = parse(\".foo + 2 * 3\").tree\n assert tree is not None\n expression = tree.children[0]\n assert expression.kind == \"binary\" and expression.value == \"+\"\n assert expression.children[1].value == \"*\"\n\n\ndef test_parser_validates_labels_and_accepts_scoped_break():\n parse(\"label $done | foreach .[] as $item (.; break $done)\")\n with pytest.raises(CompileError):\n parse(\"break $done\")\n\n\ndef test_parser_validates_function_arity_and_patterns():\n parse(\"def twice($x): $x + $x; twice(2)\")\n with pytest.raises(CompileError):\n parse(\"def twice($x): $x + $x; twice(1; 2)\")\n parse(\". as [$first, $second] | {$first, $second}\")\n\n\ndef test_parser_handles_constructors_interpolation_and_directives():\n parse('module {\"name\": \"demo\"}; \"hello \\\\(.name)\"')\n parse('{\"value\": .foo, \"nested\": [.bar]}')\n\n\ndef test_parser_accepts_variable_object_keys():\n parse('. as $key | {($key): 1}')\n parse('. as $key | {$key: 1}')\n### tests/test_paths.py\nimport pytest\n\nfrom jq_interpreter.errors import RuntimeError\nfrom jq_interpreter.evaluator import evaluate\nfrom jq_interpreter.parser import parse\n\n\ndef results(program, value):\n return list(evaluate(parse(program), value))\n\n\ndef test_path_tracks_composed_indexes_in_generator_order():\n assert results(\"path(.foo[0,1])\", {\"foo\": [10, 20]}) == [[\"foo\", 0], [\"foo\", 1]]\n\n\ndef test_path_root_and_paths_exclude_root():\n value = [1, [[], {\"a\": 2}]]\n assert results(\"path(.)\", value) == [[]]\n assert results(\"paths\", value) == [[0], [1], [1, 0], [1, 1], [1, 1, \"a\"]]\n\n\ndef test_getpath_reads_existing_and_missing_locations():\n value = {\"foo\": [\"a\", \"b\"]}\n assert results('getpath([\"foo\",1])', value) == [\"b\"]\n assert results('getpath([\"foo\",9])', value) == [None]\n\n\ndef test_pick_reconstructs_the_selected_path_with_null_leaf():\n assert results(\"pick(.a.b.c)\", {\"a\": {\"b\": {\"c\": None}}}) == [\n {\"a\": {\"b\": {\"c\": None}}}\n ]\n\n\n@pytest.mark.parametrize(\"program\", [\"getpath(1)\", \"path(.foo | 1)\"])\ndef test_path_apis_reject_invalid_accesses(program):\n with pytest.raises(RuntimeError):\n results(program, {\"foo\": 1})\n### tests/test_sql_builtins.py\nfrom jq_interpreter.evaluator import evaluate\nfrom jq_interpreter.parser import parse\n\n\ndef results(program, value):\n return list(evaluate(parse(program), value))\n\n\ndef test_index_implicit_stream_indexes_each_input_element():\n assert results(\"INDEX(.id)\", [{\"id\": 1}, {\"id\": 2}]) == [\n {\"1\": {\"id\": 1}, \"2\": {\"id\": 2}}\n ]\n\n\ndef test_index_explicit_stream_preserves_index_expression_results():\n assert results('INDEX(range(3); [., \"x\\\\(.)\"] | .[0])', None) == [\n {\"0\": 0, \"1\": 1, \"2\": 2}\n ]\n\n\ndef test_join_two_arguments_collects_pairs_and_uses_null_for_missing_keys():\n assert results(\"JOIN({\\\"1\\\":\\\"one\\\"}; .id|tostring)\", [{\"id\": 1}, {\"id\": 2}]) == [\n [[{\"id\": 1}, \"one\"], [{\"id\": 2}, None]]\n ]\n\n\ndef test_join_three_and_four_arguments_stream_and_transform_pairs():\n program = 'JOIN({\"1\":\"one\"}; .[]; .id|tostring; .[0].id)'\n assert results(program, [{\"id\": 1}, {\"id\": 2}]) == [1, 2]\n\n\ndef test_in_one_and_two_argument_forms_use_jq_equality():\n assert results(\"IN(range(3))\", 2) == [True]\n assert results(\"IN(range(3))\", 4) == [False]\n assert results(\"IN(range(1;3); range(5))\", None) == [True]\n\n\ndef test_builtins_emits_name_arity_inventory():\n inventory = results(\"builtins\", None)[0]\n assert \"INDEX/1\" in inventory\n assert \"INDEX/2\" in inventory\n assert \"JOIN/4\" in inventory\n assert \"IN/2\" in inventory\n assert all(\"/\" in entry and int(entry.rsplit(\"/\", 1)[1]) >= 0 for entry in inventory)\n### tests/test_strings.py\nimport pytest\n\nfrom jq_interpreter.errors import RuntimeError\nfrom jq_interpreter.evaluator import evaluate\nfrom jq_interpreter.parser import parse\n\n\ndef result(program, value):\n return list(evaluate(parse(program), value))\n\n\n@pytest.mark.parametrize(\"program,value,expected\", [\n ('startswith(\"é\")', \"élan\", [True]),\n ('endswith(\"an\")', \"élan\", [True]),\n ('ltrimstr(\"foo\")', \"foobar\", [\"bar\"]),\n ('rtrimstr(\"bar\")', \"foobar\", [\"foo\"]),\n ('trimstr(\"foo\")', \"foobarfoo\", [\"bar\"]),\n ('trim', \" \\u00a0abc\\u3000 \", [\"abc\"]),\n ('ascii_downcase', \"AéZ\", [\"aéz\"]),\n ('join(\",\")', [\"a\", 1, True, None, False], [\"a,1,true,,false\"]),\n ('indices(\"o\")', \"🇬🇧oo\", [[2, 3]]),\n ('split(\"\")', \"é中\", [[\"é\", \"中\"]]),\n])\ndef test_string_builtin(program, value, expected):\n assert result(program, value) == expected\n\n\ndef test_string_builtin_type_error_is_runtime_error():\n with pytest.raises(RuntimeError):\n result('startswith(\"x\")', 1)\n\n\ndef test_regex_match_reports_codepoint_offsets_and_named_captures():\n matches = result('match(\"(?<word>é+)\")', \"xéé\")[0]\n assert matches[\"offset\"] == 1\n assert matches[\"length\"] == 2\n assert matches[\"captures\"] == [{\"offset\": 1, \"length\": 2, \"string\": \"éé\", \"name\": \"word\"}]\n\n\ndef test_regex_global_scan_and_case_insensitive_test():\n assert result('scan(\"a+\"; \"gi\")', \"Aaa ba\")[0] == \"Aaa\"\n assert result('test(\"foo\"; \"i\")', \"FOO\") == [True]\n\n\ndef test_regex_capture_and_substitution_use_named_captures():\n assert result('capture(\"(?<a>[a-z]+)-(?<n>[0-9]+)\")', \"xyz-14\") == [{\"a\": \"xyz\", \"n\": \"14\"}]\n assert result('gsub(\"(?<x>.)\"; \"+\\\\(.x)-\")', \"ab\") == [\"+a-+b-\"]\n\n\ndef test_regex_replacement_stream_preserves_multiple_outputs():\n assert result('gsub(\"p\"; \"a\", \"b\")', \"p\") == [\"a\", \"b\"]\n### tests/test_traversal.py\nimport pytest\n\nfrom jq_interpreter.errors import RuntimeError\nfrom jq_interpreter.evaluator import evaluate\nfrom jq_interpreter.parser import parse\n\n\ndef results(program, value):\n return list(evaluate(parse(program), value))\n\n\ndef test_recurse_emits_depth_first_values_and_handles_scalars():\n assert results(\"recurse\", {\"a\": [1, 2]}) == [{\"a\": [1, 2]}, [1, 2], 1, 2]\n assert results(\"..\", 7) == [7]\n\n\ndef test_recurse_filter_and_condition_preserve_multiple_branches():\n assert results(\"recurse(.[]?)\", [1, [2], 4]) == [[1, [2], 4], 1, [2], 2, 4]\n assert results(\"recurse(. + 1; . < 3)\", 1) == [1, 2]\n\n\ndef test_walk_is_post_order_and_drops_empty_object_members():\n assert results(\"walk(if type == \\\"array\\\" then sort else . end)\", [[3, 1], [2]]) == [[[1, 3], [2]]]\n assert results(\"walk(select(IN({}, []) | not))\", {\"a\": 1, \"b\": []}) == [{\"a\": 1}]\n\n\ndef test_tostream_emits_leaf_and_close_events_in_document_order():\n value = [0, [1, {\"a\": 2}], {}]\n assert results(\"tostream\", value) == [\n [[0], 0], [[1, 0], 1], [[1, 1, \"a\"], 2], [[1, 1]],\n [[1]], [[2], {}],\n ]\n\n\ndef test_fromstream_round_trip_and_truncate_stream():\n value = {\"a\": [1, {\"b\": 2}]}\n assert results(\". as $v | fromstream($v|tostream)\", value) == [value]\n assert results(\"1|truncate_stream([[0],\\\"a\\\"],[[1,0],\\\"b\\\"],[[1,0]],[[1]])\", None) == [\n [[0], \"b\"], [[0]],\n ]\n\n\n@pytest.mark.parametrize(\"program,value\", [\n (\"truncate_stream(-1; tostream)\", []),\n (\"fromstream(1)\", None),\n])\ndef test_stream_utilities_reject_invalid_stream_inputs(program, value):\n with pytest.raises(RuntimeError):\n results(program, value)\n### uv.lock\nversion = 1\nrevision = 3\nrequires-python = \">=3.11\"\n\n[[package]]\nname = \"jq\"\nversion = \"0.1.0\"\nsource = { virtual = \".\" }\n","exit_code":0,"status":"completed"}}
{"type":"item.started","item":{"id":"item_2","type":"command_execution","command":"/bin/bash -lc \"sed -n '1,220p' jq_interpreter/command.py; echo '--- command tests ---'; rg -n \\\"command|main\\\\(|runtime|invalid|partial|json\\\" tests; echo '--- pyproject ---'; sed -n '1,160p' pyproject.toml; echo '--- status ---'; git status --short\"","aggregated_output":"","exit_code":null,"status":"in_progress"}}
{"type":"item.completed","item":{"id":"item_2","type":"command_execution","command":"/bin/bash -lc \"sed -n '1,220p' jq_interpreter/command.py; echo '--- command tests ---'; rg -n \\\"command|main\\\\(|runtime|invalid|partial|json\\\" tests; echo '--- pyproject ---'; sed -n '1,160p' pyproject.toml; echo '--- status ---'; git status --short\"","aggregated_output":"\"\"\"Command-line boundary for the root ``jq`` executable.\"\"\"\n\nimport json\nimport re\nimport sys\nfrom collections.abc import Sequence\nfrom typing import TextIO\n\nfrom .builtins import json_text\nfrom .errors import CompileError, RuntimeError\nfrom .evaluator import RuntimeContext, Environment, evaluate\nfrom .parser import parse\n\n\n_SPECIAL_JSON_NUMBERS = re.compile(r\"(?<![A-Za-z0-9_])(-?infinite|nan)(?![A-Za-z0-9_])\")\n\n\ndef _parse_input(line: str) -> object:\n normalized = _SPECIAL_JSON_NUMBERS.sub(\n lambda match: {\"nan\": \"NaN\", \"infinite\": \"Infinity\", \"-infinite\": \"-Infinity\"}[match.group()],\n line,\n )\n return json.loads(normalized, parse_constant=lambda value: float(value))\n\n\ndef main(\n argv: Sequence[str] | None = None,\n stdin: TextIO | None = None,\n stdout: TextIO | None = None,\n stderr: TextIO | None = None,\n) -> int:\n \"\"\"Run jq and map compile/runtime failures to their specified statuses.\"\"\"\n\n args = list(sys.argv[1:] if argv is None else argv)\n input_stream = sys.stdin if stdin is None else stdin\n output_stream = sys.stdout if stdout is None else stdout\n error_stream = sys.stderr if stderr is None else stderr\n try:\n if len(args) != 2 or args[0] != \"-c\":\n raise CompileError(\"usage: jq -c PROGRAM\")\n ast = parse(args[1])\n def records():\n for line in input_stream:\n # jq accepts an optional UTF-8 BOM at the beginning of an input record.\n yield _parse_input(line.removeprefix(\"\\ufeff\"))\n\n shared = RuntimeContext(iter(records()), stderr=error_stream)\n environment = Environment(runtime=shared)\n for value in shared.records:\n for result in evaluate(ast, value, environment):\n output_stream.write(json_text(result) + \"\\n\")\n return 0\n except CompileError as exc:\n print(exc, file=error_stream)\n return 3\n except (RuntimeError, json.JSONDecodeError, OSError, TypeError, ValueError) as exc:\n print(exc, file=error_stream)\n return 5\n--- command tests ---\ntests/test_foundation.py:53:def test_command_boundary_is_importable():\ntests/test_foundation.py:54: from jq_interpreter.command import main\ntests/test_foundation.py:57: assert main([\"-c\", \".\"], io.StringIO(\"1\\n\"), output, io.StringIO()) == 0\ntests/test_traversal.py:47:def test_stream_utilities_reject_invalid_stream_inputs(program, value):\ntests/test_formats.py:14: (\"@json\", \"é\", ['\"é\"']),\ntests/test_formats.py:41:def test_format_rejects_invalid_input(program, value):\ntests/test_evaluator.py:5:from jq_interpreter.command import main\ntests/test_evaluator.py:61:def test_generator_is_lazy_and_keeps_values_before_runtime_error():\ntests/test_evaluator.py:68:def test_command_emits_compact_values_and_returns_runtime_status():\ntests/test_evaluator.py:71: assert main([\"-c\", \"1, .\"], io.StringIO(\"7\\n\"), output, errors) == 0\ntests/test_evaluator.py:75: assert main([\"-c\", \"., error\"], io.StringIO(\"7\\n\"), output, errors) == 5\ntests/test_evaluator.py:79:def test_command_accepts_a_leading_input_bom():\ntests/test_evaluator.py:81: assert main([\"-c\", \".\"], io.StringIO('\\ufeff\"byte order mark\"\\n'), output, io.StringIO()) == 0\ntests/test_evaluator.py:122:def test_try_catch_preserves_partial_output_and_passes_error_value_to_handler():\ntests/test_evaluator.py:130:def test_invalid_operator_combinations_are_runtime_errors(source):\ntests/test_conversion.py:5:from jq_interpreter.command import main\ntests/test_conversion.py:33: (\"tojson\", \"x\", '\"x\"'),\ntests/test_conversion.py:34: (\"fromjson\", '{\"a\":1}', {\"a\": 1}),\ntests/test_conversion.py:43:def test_implode_replaces_invalid_codepoints_and_rounds_numbers_down():\ntests/test_conversion.py:54: (\"fromjson\", \"{'a': 1}\"),\ntests/test_conversion.py:59:def test_conversion_builtin_rejects_invalid_input(program, value):\ntests/test_conversion.py:64:def test_command_accepts_jq_special_numeric_input_and_serializes_nan_as_null():\ntests/test_conversion.py:66: assert main([\"-c\", \"tojson | fromjson\"], io.StringIO('{\"a\":nan}\\n'), output, io.StringIO()) == 0\ntests/test_numeric.py:18: assert result(\"[1E+1000,-1E+1000 | tojson]\") == [[\ntests/test_paths.py:35:def test_path_apis_reject_invalid_accesses(program):\ntests/test_input_diagnostics.py:3:from jq_interpreter.command import main\ntests/test_input_diagnostics.py:10: status = main([\"-c\", program], io.StringIO(data), output, errors)\ntests/test_lexer.py:45:def test_lexer_rejects_invalid_escapes_strings_and_delimiters(source):\ntests/test_strings.py:28:def test_string_builtin_type_error_is_runtime_error():\n--- pyproject ---\n[project]\nname = \"jq\"\nversion = \"0.1.0\"\nrequires-python = \">=3.11\"\ndependencies = []\n\n[tool.pytest.ini_options]\ntestpaths = [\"tests\"]\naddopts = \"-q\"\n--- status ---\n","exit_code":0,"status":"completed"}}
{"type":"item.completed","item":{"id":"item_3","type":"agent_message","text":"The root launcher and `jq_interpreter.command` already exist and implement the required status mapping and streaming loop. I’m checking them against the project suite and the two declared subprocess behaviors now; I’ll patch only if a concrete interface defect appears."}}
{"type":"item.started","item":{"id":"item_4","type":"command_execution","command":"/bin/bash -lc 'pytest -q'","aggregated_output":"","exit_code":null,"status":"in_progress"}}
{"type":"item.completed","item":{"id":"item_4","type":"command_execution","command":"/bin/bash -lc 'pytest -q'","aggregated_output":"........................................................................ [ 39%]\n........................................................................ [ 78%]\n........................................ [100%]\n","exit_code":0,"status":"completed"}}
{"type":"item.started","item":{"id":"item_5","type":"command_execution","command":"/bin/bash -lc \"set +e\npython3 - <<'PY'\nimport json, subprocess\nvalues=[{\\\"a\\\":[1,2]},[3,4]]\npayload='\\\\n'.join(json.dumps(v) for v in values)+'\\\\n'\nr=subprocess.run(['./jq','-c','.'],input=payload,capture_output=True,text=True)\nprint('command-stream rc=',r.returncode,'values=',[json.loads(x) for x in r.stdout.splitlines()],'stderr=',repr(r.stderr))\nassert r.returncode == 0\nassert [json.loads(x) for x in r.stdout.splitlines()] == values\nassert all(x == json.dumps(json.loads(x),separators=(',',':')) for x in r.stdout.splitlines())\ninvalid=subprocess.run(['./jq','-c','{'],input='null',capture_output=True,text=True)\nprint('compile rc=',invalid.returncode)\nassert invalid.returncode == 3\nruntime=subprocess.run(['./jq','-c','., error'],input='7',capture_output=True,text=True)\nprint('runtime rc=',runtime.returncode,'stdout=',runtime.stdout.splitlines())\nassert runtime.returncode == 5\nassert [json.loads(x) for x in runtime.stdout.splitlines()] == [7]\nPY\nexit \"'$?'","aggregated_output":"","exit_code":null,"status":"in_progress"}}
{"type":"item.completed","item":{"id":"item_5","type":"command_execution","command":"/bin/bash -lc \"set +e\npython3 - <<'PY'\nimport json, subprocess\nvalues=[{\\\"a\\\":[1,2]},[3,4]]\npayload='\\\\n'.join(json.dumps(v) for v in values)+'\\\\n'\nr=subprocess.run(['./jq','-c','.'],input=payload,capture_output=True,text=True)\nprint('command-stream rc=',r.returncode,'values=',[json.loads(x) for x in r.stdout.splitlines()],'stderr=',repr(r.stderr))\nassert r.returncode == 0\nassert [json.loads(x) for x in r.stdout.splitlines()] == values\nassert all(x == json.dumps(json.loads(x),separators=(',',':')) for x in r.stdout.splitlines())\ninvalid=subprocess.run(['./jq','-c','{'],input='null',capture_output=True,text=True)\nprint('compile rc=',invalid.returncode)\nassert invalid.returncode == 3\nruntime=subprocess.run(['./jq','-c','., error'],input='7',capture_output=True,text=True)\nprint('runtime rc=',runtime.returncode,'stdout=',runtime.stdout.splitlines())\nassert runtime.returncode == 5\nassert [json.loads(x) for x in runtime.stdout.splitlines()] == [7]\nPY\nexit \"'$?'","aggregated_output":"command-stream rc= 0 values= [{'a': [1, 2]}, [3, 4]] stderr= ''\ncompile rc= 3\nruntime rc= 5 stdout= ['7']\n","exit_code":0,"status":"completed"}}
{"type":"item.completed","item":{"id":"item_6","type":"agent_message","text":"The command suite is green, and the declared stream/error checks pass with observed exit codes 0, 3, and 5; runtime failure preserves the prior `7` output. I’m running the scoped identity slice through the supplied harness as the final verification, without altering any staged source."}}
{"type":"item.started","item":{"id":"item_7","type":"command_execution","command":"/bin/bash -lc 'JQ=\"$PWD/jq\" python3 sources/run_conformance.py --select '\"'\"'^'\"\\\\.\"'$'\"' --json\"","aggregated_output":"","exit_code":null,"status":"in_progress"}}
{"type":"item.completed","item":{"id":"item_7","type":"command_execution","command":"/bin/bash -lc 'JQ=\"$PWD/jq\" python3 sources/run_conformance.py --select '\"'\"'^'\"\\\\.\"'$'\"' --json\"","aggregated_output":"{\n \"candidate\": [\n \"/mnt/c/Users/barlo/projects/drydock/uat/jq/runs/20261028.145919/build/jq/jq\"\n ],\n \"corpus\": \"jq.test\",\n \"summary\": {\n \"pass\": 2,\n \"fail\": 0,\n \"error\": 0,\n \"skip\": 0\n },\n \"cases\": []\n}\n","exit_code":0,"status":"completed"}}
{"type":"item.completed","item":{"id":"item_8","type":"agent_message","text":"RESULT: SUCCESS\n\nFILES CHANGED:\n- None; existing implementation satisfied the specification.\n\nSUMMARY:\nVerified command streaming, compact output, compile exit `3`, runtime exit `5`, partial output preservation, and scoped corpus conformance.\n\nChecks:\n- `pytest -q` — passed\n- Declared command checks — passed\n- Scoped harness — 2 passed, 0 failed, 0 errored\n\nBLOCKERS:\n- None"}}
{"type":"turn.completed","usage":{"input_tokens":200339,"cached_input_tokens":176896,"cache_write_input_tokens":0,"output_tokens":1401,"reasoning_output_tokens":299}}
Run artifact