=== BEGIN ARTIFACT ARCHITECTURE.md === # ARCHITECTURE: jq Interpreter | Field | Value | |-------|-------| | Version | 20261028 V1 | | Description | Defines the Python interpreter foundation and its shared execution boundaries. | | Provides | Python application foundation | ## Questions - None. ## Structure and contracts The application is a standalone Python interpreter. The root executable `jq` ultimately delegates argument handling and JSON input and output to the interpreter. Establish the package `jq_interpreter` with these shared interfaces: - `jq_interpreter.errors.CompileError` and `jq_interpreter.errors.RuntimeError` distinguish errors detected before execution from errors raised during evaluation. The latter is an interpreter exception and need not inherit from Python's built-in `RuntimeError`. - `jq_interpreter.lexer.tokenize(source)` returns an ordered iterable of tokens, each exposing `kind`, `value`, `line`, and `column`. - `jq_interpreter.parser.parse(source)` consumes the lexer contract and returns an abstract syntax tree or raises `CompileError`. - `jq_interpreter.evaluator.evaluate(ast, value, environment=None)` returns an iterator of results. It must not eagerly consume the result stream. Lexical environments carry bindings and function definitions without mutating an enclosing scope. - Builtins receive and produce values through the evaluator's generator model. The command entry point maps compile and runtime errors to their distinct exit statuses. The foundation establishes the package and error interfaces; subsequent stories implement the lexer, parser, evaluator, builtins, and executable. An evaluator may yield values before raising `RuntimeError`; callers must retain those values. ## Boundary ownership | Boundary | Owner | Allowed low-level access | |----------|-------|--------------------------| | Source text and tokenization | Lexer | Python text and Unicode facilities | | Grammar and static validation | Parser | Lexer token stream | | Evaluation and lexical scope | Evaluator | AST, environments, and builtin interfaces | | Builtins | Builtin modules | Python standard library and evaluator interfaces | | Command input and output | Command entry point | Standard input, output, error, and process arguments | | Persistence and external services | None | No persistent store or external service is required | ## Technology Stack Python 3.11 or newer provides the interpreter and its standard-library runtime. POSIX shell runs the supplied scoring entry point. No package installation or network access is required. ## Programmatic Acceptance === AC foundation-errors === Intent: The foundation exposes separate compile and runtime exception contracts for later interpreter stages. from jq_interpreter.errors import CompileError, RuntimeError as JqRuntimeError assert issubclass(CompileError, Exception) assert issubclass(JqRuntimeError, Exception) assert CompileError is not JqRuntimeError assert not issubclass(CompileError, JqRuntimeError) assert not issubclass(JqRuntimeError, CompileError) === END AC foundation-errors === ## User Acceptance - None. ## Guardrails - Use Python and the standard library only; do not install packages or use an external jq runtime. - Do not shell out to a system jq executable or use a third-party jq implementation or binding. - Preserve ordered lazy generation, lexical scope, and distinct compile and runtime failures in the interfaces built on this foundation. - Do not modify files under `sources/`. === END ARTIFACT === === BEGIN ARTIFACT FEATURE-CorpusStaging.md === # FEATURE: Conformance Asset Staging | Field | Value | |-------|-------| | Version | 20261028 V1 | | Description | Stages the supplied conformance and language reference assets unchanged. | | Depends On | ARCHITECTURE.md | | Provides | staged conformance assets | | Consumes | Python application foundation | ## Questions - None. ## Purpose and workflow Stage `jq-manual.txt`, `jq.test`, `parser.y`, `lexer.l`, `builtin.jq`, `run_conformance.py`, `full_test.sh`, and `exclusions.txt` unchanged under the application root's `sources/` directory. These are read-only reference and scoring inputs. The imported instructions are planning context and are not staged as an implementation asset. The staging gate imports the supplied runner as a module, parses the pinned corpus, and applies the exclusions. It does not launch the runner or claim interpreter behavior. An unmatched exclusion raises an error; the pinned corpus contains 550 cases and the exclusion application identifies 13 cases. ## Programmatic Acceptance === AC staging-consistency === Intent: The pinned corpus parses completely and every declared exclusion matches the corpus. import sys sys.path.insert(0, "sources") import run_conformance as harness cases = harness.parse_corpus(harness.CORPUS.read_text(encoding="utf-8")) excluded = harness.apply_exclusions(cases, harness.parse_exclusions(harness.EXCLUSIONS)) assert len(cases) == 550, len(cases) assert len(excluded) == 13, len(excluded) === END AC staging-consistency === ## User Acceptance - None. ## Guardrails - Do not modify, rewrite, trim, regenerate, or substitute any file under `sources/`. - Do not launch the conformance runner or the scoring script for this staging gate. === END ARTIFACT === === BEGIN ARTIFACT FEATURE-Lexer.md === # FEATURE: jq Lexer | Field | Value | |-------|-------| | Version | 20261028 V1 | | Description | Converts jq source text into located tokens and rejects lexical errors. | | Depends On | ARCHITECTURE.md, FEATURE-CorpusStaging.md | | Provides | jq token stream | | Consumes | Python application foundation, staged conformance assets | ## Questions - None. ## Behavior `jq_interpreter.lexer.tokenize(source)` returns tokens in source order, with `kind`, `value`, `line`, and `column` attributes. Use one-based source locations. Follow `sources/lexer.l` for operators, keywords, identifiers, bindings, numbers, punctuation, formats, and delimiter nesting. Recognize quoted strings, JSON escapes, and embedded jq expressions introduced by interpolation; retain enough structure for the parser to distinguish literal text from interpolated expressions. Ignore whitespace and comments, including the specified backslash continuation of comments. Invalid characters, invalid string escapes, unterminated strings, and mismatched delimiters raise `jq_interpreter.errors.CompileError`. The parser consumes this interface. Corpus cases that combine lexical behavior with evaluation are executed by later scoped integration after their required capabilities exist. ## Programmatic Acceptance === AC lexer-locations === Intent: The lexer ignores comments and retains the source locations of successive literal tokens. from jq_interpreter.lexer import tokenize tokens = list(tokenize("1 # comment\n2")) numbers = [token for token in tokens if token.value in (1, 2) and not isinstance(token.value, bool)] assert [token.value for token in numbers] == [1, 2] assert [(token.line, token.column) for token in numbers] == [(1, 1), (2, 1)] === END AC lexer-locations === === AC lexer-invalid === Intent: Invalid string escapes and unmatched delimiters are compile failures. from jq_interpreter.errors import CompileError from jq_interpreter.lexer import tokenize for source in (r'"\v"', "(", "]"): try: list(tokenize(source)) except CompileError: pass else: raise AssertionError(f"accepted invalid source: {source!r}") === END AC lexer-invalid === ## User Acceptance - None. ## Guardrails - Follow the supplied lexer and manual; do not modify staged sources. - Lexical errors are compile errors, not evaluation errors. === END ARTIFACT === === BEGIN ARTIFACT FEATURE-Parser.md === # FEATURE: jq Parser | Field | Value | |-------|-------| | Version | 20261028 V1 | | Description | Parses and statically validates jq programs into abstract syntax trees. | | Depends On | FEATURE-Lexer.md | | Provides | jq abstract syntax tree | | Consumes | jq token stream | ## Questions - None. ## Behavior `jq_interpreter.parser.parse(source)` uses the token stream to return an abstract syntax tree. Implement the grammar, precedence, and associativity in `sources/parser.y`, including expression composition, constructors, path expressions, assignments, control forms, bindings, functions, patterns, interpolation, and module directives. Perform static validation of lexical bindings, function references and arities, label visibility, constant object keys, and module metadata and import paths. Reject invalid syntax and static errors by raising `jq_interpreter.errors.CompileError`; never evaluate the program during parsing. Module grammar rejection does not require loading files. Valid constructs are represented in the AST even when a later story owns their evaluation. The early gate calls the parser directly. Corpus programs requiring the executable or evaluator are retained for executing scoped integration after those capabilities are available. ## Programmatic Acceptance === AC parser-valid === Intent: The parser accepts a composed expression and returns a syntax tree without evaluating it. from jq_interpreter.parser import parse tree = parse("(1, 2) | .") assert tree is not None === END AC parser-valid === === AC parser-invalid === Intent: Syntax and static scope errors are reported as compilation failures. from jq_interpreter.errors import CompileError from jq_interpreter.parser import parse for source in ("{", ". as $x | $missing", "break $missing"): try: parse(source) except CompileError: pass else: raise AssertionError(f"accepted invalid program: {source!r}") === END AC parser-invalid === ## User Acceptance - None. ## Guardrails - Use the staged grammar and lexer as the syntax authority and the manual for language behavior. - Reject invalid module grammar without accessing the filesystem. - Preserve the distinction between compile failures and runtime failures. === END ARTIFACT === === BEGIN ARTIFACT FEATURE-GeneratorCore.md === # FEATURE: Generator Evaluation Core | Field | Value | |-------|-------| | Version | 20261028 V1 | | Description | Evaluates basic jq filters as ordered, lazy streams of values. | | Depends On | FEATURE-Parser.md | | Provides | jq generator evaluation | | Consumes | jq abstract syntax tree | ## Questions - None. ## Behavior `jq_interpreter.evaluator.evaluate(ast, value, environment=None)` yields an ordered stream. Identity yields its input, literals yield their values, and `empty` yields no values. A comma evaluates both branches against the same input and concatenates their streams in order. A pipe evaluates its right side once for each value yielded by its left side. Nested generators preserve multiplicity and backtracking; evaluation must remain lazy so a consumer can stop without evaluating later results. Outputs already yielded remain observable if evaluation later raises a runtime error. Combining operands use the same original input. Provide the minimal root executable needed to run this story's scoped conformance cases: `./jq -c ''` reads JSON from standard input and writes one compact JSON value per output line. Distinguish compilation failure from runtime failure with exit statuses 3 and 5; successful completion exits 0. Later stories complete the command and language surface. ## Programmatic Acceptance === AC core-stream === Intent: Identity, comma, and pipe preserve input, ordering, and multiplicity through the evaluator. from jq_interpreter.evaluator import evaluate from jq_interpreter.parser import parse value = {"item": [1, 2]} assert list(evaluate(parse("."), value)) == [value] assert list(evaluate(parse("., . | ."), value)) == [value, value] assert list(evaluate(parse("empty"), value)) == [] === END AC core-stream === === AC core-lazy === Intent: A consumer can take the first generated result without evaluating a later runtime error. from jq_interpreter.evaluator import evaluate from jq_interpreter.parser import parse value = 7 stream = iter(evaluate(parse("., error"), value)) assert next(stream) == value === END AC core-lazy === === AC core-corpus === Intent: The basic literal and identity corpus cases execute successfully through the command interface. Suite: scoped Requires: executable=python3; scope=test import json import os import subprocess import sys SELECT = r"^(true|false|null|1|-1|\.|1,1|1,\.)$" result = subprocess.run( [sys.executable, "sources/run_conformance.py", "--select", SELECT, "--json"], capture_output=True, text=True, env={**os.environ, "JQ": os.path.abspath("jq")}, ) print(result.stdout) print(result.stderr, file=sys.stderr) report = json.loads(result.stdout) tally = report["summary"] print(f"{tally['pass']} passed, {tally['fail']} failed, {tally['error']} errored") assert sum(tally.values()) > 0, f"selector matched no case: {SELECT}" assert tally["fail"] == 0 and tally["error"] == 0, tally assert result.returncode == 0, result.returncode === END AC core-corpus === ## User Acceptance - None. ## Guardrails - Preserve stream order, multiplicity, laziness, and partial output on runtime failure. - Use only the Python standard library; do not invoke another jq implementation. - Do not modify the staged conformance assets. === END ARTIFACT ===