Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

perf(hogql): rust-py backend - direct PyO3 ast construction (#59573)

Robbie45e4f55a4aed
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index 3d696f1507ca..72277118b485 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -20989,8 +20989,15 @@
"type": "boolean"
},
"parserMode": {
- "description": "HogQL parser backend; absent → `cpp_only`. `*_shadow` modes return the primary result and sample-compare against the other parser, reporting divergences without failing the request.",
- "enum": ["cpp_only", "cpp_with_rust_shadow", "rust_with_cpp_shadow", "rust_only"],
+ "description": "HogQL parser backend; absent → `cpp_only`. `*_shadow` modes return the primary result and sample-compare against the other parser, reporting divergences without failing the request. The `rust_py_*` modes drive the same hand-rolled Rust parser as `rust_*` but build `posthog.hogql.ast` dataclass instances directly via PyO3, skipping the JSON round-trip.",
+ "enum": [
+ "cpp_only",
+ "cpp_with_rust_shadow",
+ "rust_with_cpp_shadow",
+ "rust_only",
+ "rust_py_only",
+ "rust_py_with_cpp_shadow"
+ ],
"type": "string"
},
"personsArgMaxVersion": {
diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.ts
index a6c1ff9d4673..b13f2c20529f 100644
--- a/frontend/src/queries/schema/schema-general.ts
+++ b/frontend/src/queries/schema/schema-general.ts
@@ -451,8 +451,14 @@ export interface HogQLQueryModifiers {
/** If these are provided, the query will fail if these skip indexes are not used */
forceClickhouseDataSkippingIndexes?: string[]
inlineCohortCalculation?: 'off' | 'auto' | 'always'
- /** HogQL parser backend; absent → `cpp_only`. `*_shadow` modes return the primary result and sample-compare against the other parser, reporting divergences without failing the request. */
- parserMode?: 'cpp_only' | 'cpp_with_rust_shadow' | 'rust_with_cpp_shadow' | 'rust_only'
+ /** HogQL parser backend; absent → `cpp_only`. `*_shadow` modes return the primary result and sample-compare against the other parser, reporting divergences without failing the request. The `rust_py_*` modes drive the same hand-rolled Rust parser as `rust_*` but build `posthog.hogql.ast` dataclass instances directly via PyO3, skipping the JSON round-trip. */
+ parserMode?:
+ | 'cpp_only'
+ | 'cpp_with_rust_shadow'
+ | 'rust_with_cpp_shadow'
+ | 'rust_only'
+ | 'rust_py_only'
+ | 'rust_py_with_cpp_shadow'
}
export interface DataWarehouseEventsModifier {
diff --git a/posthog/hogql/ast.py b/posthog/hogql/ast.py
index b6000e7b2cab..e91fa7350b8d 100644
--- a/posthog/hogql/ast.py
+++ b/posthog/hogql/ast.py
@@ -29,6 +29,8 @@ from posthog.hogql.errors import NotImplementedError, QueryError, ResolutionErro
# :NOTE: when you add new AST fields or nodes, add them to CloningVisitor and TraversingVisitor in visitor.py as well.
# :NOTE2: also search for ":TRICKY:" in "resolver.py" when modifying SelectQuery or JoinExpr
+# Allowlist for `OrderExpr.order`; the SQL printer interpolates it verbatim. Shared between `__post_init__` and the printer's defense-in-depth check.
+VALID_ORDER_DIRECTIONS = ("ASC", "DESC")
VALID_JOIN_CONSTRAINT_TYPES = get_args(Literal["ON", "USING"])
VALID_JOIN_TYPES = frozenset(
{
@@ -897,7 +899,7 @@ class OrderExpr(Expr):
with_fill: Optional[WithFillExpr] = None
def __post_init__(self):
- if self.order not in ("ASC", "DESC"):
+ if self.order not in VALID_ORDER_DIRECTIONS:
raise ValueError(f"Invalid order direction: {self.order}")
@@ -948,10 +950,26 @@ class Constant(Expr):
value: Any
+# Allowlist for `Keyword.name`; the SQL printer interpolates it verbatim (CH returns `name` directly, Postgres uppercases). Restricted to the Postgres-family time pseudo-functions from `resolver.POSTGRES_KEYWORD_TYPES` — a broader `str.isidentifier()` check would still admit arbitrary Python identifiers and let them emit as unquoted ClickHouse tokens.
+VALID_KEYWORD_NAMES = frozenset(
+ {
+ "current_date",
+ "current_time",
+ "current_timestamp",
+ "localtime",
+ "localtimestamp",
+ }
+)
+
+
@dataclass(kw_only=True, slots=True)
class Keyword(Expr):
name: str
+ def __post_init__(self):
+ if self.name not in VALID_KEYWORD_NAMES:
+ raise ValueError(f"Invalid Keyword name: {self.name!r}")
+
@dataclass(kw_only=True, slots=True)
class Field(Expr):
diff --git a/posthog/hogql/constants.py b/posthog/hogql/constants.py
index ae284dc92ed7..10232dbb00e3 100644
--- a/posthog/hogql/constants.py
+++ b/posthog/hogql/constants.py
@@ -48,7 +48,7 @@ BREAKDOWN_VALUE_MAX_LENGTH = 400
type HogQLDialect = Literal["hogql", "clickhouse", "postgres", "duckdb"]
-type HogQLParserBackend = Literal["python", "cpp-json", "rust-json"]
+type HogQLParserBackend = Literal["python", "cpp-json", "rust-json", "rust-py"]
class LimitContext(StrEnum):
diff --git a/posthog/hogql/parser.py b/posthog/hogql/parser.py
index 5b3995a00a09..f15463c6b91f 100644
--- a/posthog/hogql/parser.py
+++ b/posthog/hogql/parser.py
@@ -53,10 +53,15 @@ _RUST_PARSER_AVAILABLE = True
try:
from hogql_parser_rs import (
parse_expr_json as _parse_expr_json_rs,
+ parse_expr_py as _parse_expr_py_rs,
parse_full_template_string_json as _parse_full_template_string_json_rs,
+ parse_full_template_string_py as _parse_full_template_string_py_rs,
parse_order_expr_json as _parse_order_expr_json_rs,
+ parse_order_expr_py as _parse_order_expr_py_rs,
parse_program_json as _parse_program_json_rs,
+ parse_program_py as _parse_program_py_rs,
parse_select_json as _parse_select_json_rs,
+ parse_select_py as _parse_select_py_rs,
)
except ImportError as _import_err:
_RUST_PARSER_AVAILABLE = False
@@ -64,7 +69,7 @@ except ImportError as _import_err:
# the end of the except block, so the closure below would otherwise
# see an unbound `NameError` when called.
_RUST_IMPORT_ERROR_REPR = repr(_import_err)
- logger.exception("hogql_parser_rs import failed; rust-json backend disabled")
+ logger.exception("hogql_parser_rs import failed; rust-json and rust-py backends disabled")
capture_exception(
_import_err,
additional_properties={"hogql_parser_rs_import_error": _RUST_IMPORT_ERROR_REPR},
@@ -80,6 +85,11 @@ except ImportError as _import_err:
_parse_order_expr_json_rs = _rust_parser_unavailable
_parse_program_json_rs = _rust_parser_unavailable
_parse_select_json_rs = _rust_parser_unavailable
+ _parse_expr_py_rs = _rust_parser_unavailable
+ _parse_full_template_string_py_rs = _rust_parser_unavailable
+ _parse_order_expr_py_rs = _rust_parser_unavailable
+ _parse_program_py_rs = _rust_parser_unavailable
+ _parse_select_py_rs = _rust_parser_unavailable
class CacheOrigin(StrEnum):
@@ -164,6 +174,18 @@ RULE_TO_PARSE_FUNCTION: dict[HogQLParserBackend, dict[ParseRule, Callable]] = {
ParseRule.FULL_TEMPLATE_STRING: lambda string: deserialize_ast(_parse_full_template_string_json_rs(string)),
ParseRule.PROGRAM: lambda string: deserialize_ast(_parse_program_json_rs(string)),
},
+ # `rust-py` skips JSON serialise/deserialise on both sides: the parser
+ # builds a `serde_json::Value` (intermediate) and a Rust-side converter
+ # constructs the Python ast dataclass instances directly via PyO3. The
+ # `rust-json` path stays alongside for the future WASM build that can't
+ # link to CPython, and for tests that need to compare on the JSON shape.
+ "rust-py": {
+ ParseRule.EXPR: lambda string, start: _parse_expr_py_rs(string, is_internal=start is None),
+ ParseRule.ORDER_EXPR: _parse_order_expr_py_rs,
+ ParseRule.SELECT: _parse_select_py_rs,
+ ParseRule.FULL_TEMPLATE_STRING: _parse_full_template_string_py_rs,
+ ParseRule.PROGRAM: _parse_program_py_rs,
+ },
}
RULE_TO_HISTOGRAM: dict[ParseRule, Histogram] = {
@@ -187,6 +209,8 @@ _PARSER_MODE_BACKENDS: dict[ParserMode, tuple[HogQLParserBackend, HogQLParserBac
ParserMode.RUST_ONLY: ("rust-json", None),
ParserMode.CPP_WITH_RUST_SHADOW: ("cpp-json", "rust-json"),
ParserMode.RUST_WITH_CPP_SHADOW: ("rust-json", "cpp-json"),
+ ParserMode.RUST_PY_ONLY: ("rust-py", None),
+ ParserMode.RUST_PY_WITH_CPP_SHADOW: ("rust-py", "cpp-json"),
}
# Fraction of `*_shadow` parses that also run the secondary backend. Kept
diff --git a/posthog/hogql/printer/base.py b/posthog/hogql/printer/base.py
index 3653828c56df..81addc50076d 100644
--- a/posthog/hogql/printer/base.py
+++ b/posthog/hogql/printer/base.py
@@ -2,7 +2,7 @@ import re
from collections.abc import Iterable
from datetime import date, datetime
from difflib import get_close_matches
-from typing import Any, ClassVar, Literal, Optional, Union, cast
+from typing import Any, ClassVar, Literal, Optional, Union, cast, get_args
from uuid import UUID
from django.conf import settings as django_settings
@@ -113,6 +113,9 @@ class BasePrinter(Visitor[str]):
def _assert_set_operator_supported(self, set_operator: str) -> None:
"""Raise if this dialect does not support the given set operator. Postgres overrides to permit all."""
+ # Allowlist gate against `setattr`-bypass — the printer interpolates `set_operator` verbatim into emitted SQL.
+ if set_operator not in get_args(ast.SetOperator):
+ raise QueryError(f"Invalid set operator: {set_operator!r}")
if set_operator in ("INTERSECT ALL", "EXCEPT ALL"):
raise ImpossibleASTError(f"{set_operator} is not supported in the '{self.DIALECT_NAME}' dialect")
@@ -543,7 +546,14 @@ class BasePrinter(Visitor[str]):
join_strings = []
if node.join_type is not None:
- join_strings.append(node.join_type)
+ # Allowlist gate against `setattr`-bypass — the printer interpolates `join_type` verbatim into emitted SQL.
+ jt = node.join_type
+ if not (
+ jt in ast.VALID_JOIN_TYPES
+ or (jt.startswith("GLOBAL ") and jt.removeprefix("GLOBAL ") in ast.VALID_JOIN_TYPES)
+ ):
+ raise QueryError(f"Invalid join type: {jt!r}")
+ join_strings.append(jt)
if isinstance(node.type, (ast.TableAliasType, ast.ColumnAliasedTableType, ast.TableType)):
table_type: ast.TableType | ast.LazyTableType | ast.TableAliasType | ast.ColumnAliasedTableType = node.type
@@ -657,6 +667,9 @@ class BasePrinter(Visitor[str]):
join_strings.append(sample_clause)
if node.constraint is not None:
+ # Allowlist gate against `setattr`-bypass — the printer interpolates `constraint_type` verbatim.
+ if node.constraint.constraint_type not in ast.VALID_JOIN_CONSTRAINT_TYPES:
+ raise QueryError(f"Invalid join constraint type: {node.constraint.constraint_type!r}")
if team_id_for_on_clause is not None:
combined_constraint = ast.And(exprs=[team_id_for_on_clause, node.constraint.expr])
join_strings.append(f"{node.constraint.constraint_type} {self.visit(combined_constraint)}")
@@ -796,6 +809,9 @@ class BasePrinter(Visitor[str]):
return f"({', '.join(identifiers)}) -> {self.visit(node.expr)}"
def visit_order_expr(self, node: ast.OrderExpr):
+ # Allowlist gate against `setattr`-bypass — the printer interpolates `order` verbatim.
+ if node.order not in ast.VALID_ORDER_DIRECTIONS:
+ raise QueryError(f"Invalid order direction: {node.order!r}")
result = f"{self.visit(node.expr)} {node.order}"
if node.with_fill is not None:
result += f" {self.visit(node.with_fill)}"
@@ -895,7 +911,8 @@ class BasePrinter(Visitor[str]):
return self._print_escaped_string(node.value)
def visit_keyword(self, node: ast.Keyword):
- if not node.name.isidentifier():
+ # Allowlist gate against `setattr`-bypass — the printer returns `name` verbatim.
+ if node.name not in ast.VALID_KEYWORD_NAMES:
raise QueryError(f"Invalid keyword name: {node.name}")
return node.name
diff --git a/posthog/hogql/printer/postgres.py b/posthog/hogql/printer/postgres.py
index 52e36aca1900..b29227c6ab4e 100644
--- a/posthog/hogql/printer/postgres.py
+++ b/posthog/hogql/printer/postgres.py
@@ -97,7 +97,8 @@ class PostgresPrinter(BasePrinter):
return self.visit(node.type)
def visit_keyword(self, node: ast.Keyword):
- if not node.name.isidentifier():
+ # Allowlist gate against `setattr`-bypass — the printer returns `name.upper()` verbatim.
+ if node.name not in ast.VALID_KEYWORD_NAMES:
raise QueryError(f"Invalid keyword name: {node.name}")
return node.name.upper()
diff --git a/posthog/hogql/printer/test/test_printer.py b/posthog/hogql/printer/test/test_printer.py
index cde8ad3b2dd0..c370f8f8813d 100644
--- a/posthog/hogql/printer/test/test_printer.py
+++ b/posthog/hogql/printer/test/test_printer.py
@@ -1452,15 +1452,44 @@ class TestPrinter(BaseTest):
@parameterized.expand(
[
+ # Injection-shaped strings — whitespace / punctuation makes them obviously not identifiers.
("sql_injection", "; DROP TABLE events --"),
("union_injection", "current_date UNION SELECT 1"),
("whitespace", "current date"),
("special_chars", "now()"),
("empty_string", ""),
+ # Python-valid identifiers outside `VALID_KEYWORD_NAMES` — would emit unquoted as arbitrary ClickHouse tokens if the gate only checked `isidentifier()`.
+ ("python_identifier_but_not_keyword", "hello"),
+ ("looks_like_keyword_uppercase", "CURRENT_DATE"),
+ ("dunder_attr", "__class__"),
+ ("sql_keyword_select", "SELECT"),
]
)
def test_keyword_rejects_invalid_names(self, _name: str, keyword_name: str):
- node = ast.Keyword(name=keyword_name)
+ # `Keyword.__post_init__` rejects at construction; `visit_keyword` re-checks at print time (defense-in-depth catches the `setattr` bypass path).
+ with self.assertRaises((ValueError, QueryError)):
+ node = ast.Keyword(name=keyword_name)
+ context = HogQLContext(team_id=self.team.pk, enable_select_queries=True)
+ select_query = ast.SelectQuery(select=[node], select_from=ast.JoinExpr(table=ast.Field(chain=["events"])))
+ print_prepared_ast(node, context=context, dialect="clickhouse", stack=[select_query])
+
+ @parameterized.expand(
+ [
+ ("current_date",),
+ ("current_time",),
+ ("current_timestamp",),
+ ("localtime",),
+ ("localtimestamp",),
+ ]
+ )
+ def test_keyword_accepts_valid_names(self, keyword_name: str):
+ # The five names in `ast.VALID_KEYWORD_NAMES`, kept in sync with `resolver.POSTGRES_KEYWORD_TYPES` via import-time assert.
+ ast.Keyword(name=keyword_name)
+
+ def test_keyword_printer_rejects_setattr_bypass(self):
+ # `setattr`-after-construction skips `__post_init__`; the printer's allowlist re-check stops the bypass.
+ node = ast.Keyword(name="current_date")
+ node.name = "; DROP TABLE events --"
context = HogQLContext(team_id=self.team.pk, enable_select_queries=True)
select_query = ast.SelectQuery(select=[node], select_from=ast.JoinExpr(table=ast.Field(chain=["events"])))
with self.assertRaises(QueryError):
diff --git a/posthog/hogql/printer/test/test_sql_injection_defenses.py b/posthog/hogql/printer/test/test_sql_injection_defenses.py
new file mode 100644
index 000000000000..8dbd76424919
--- /dev/null
+++ b/posthog/hogql/printer/test/test_sql_injection_defenses.py
@@ -0,0 +1,224 @@
+"""SQL-injection-defense regression suite for the HogQL printer.
+
+Trust model: every AST string field that reaches printer output is either escape-wrapped (via `_print_identifier`, `_print_escaped_string`, or `context.add_value` parameterization) or interpolated verbatim against an allowlist enforced at both construction (`__post_init__`) and print time. Hog-only nodes compile to HogVM bytecode and never reach a SQL printer; out of scope here.
+
+Tests cover (1) construction-time rejection, (2) printer-side rejection when a value is `setattr`-written past `__post_init__`, (3) branch-only print-time allowlists for fields without a `__post_init__` gate, (4) parser → printer round-trip escape preservation under malicious-looking source content, and (5) cross-backend parser uniformity on grammar quirks that produce out-of-allowlist values.
+"""
+
+from typing import Optional
+
+from posthog.test.base import BaseTest
+
+from parameterized import parameterized
+
+from posthog.hogql import ast
+from posthog.hogql.constants import HogQLDialect
+from posthog.hogql.context import HogQLContext
+from posthog.hogql.errors import ExposedHogQLError, ImpossibleASTError, QueryError
+from posthog.hogql.parser import parse_select
+from posthog.hogql.printer import prepare_and_print_ast
+
+
+def _print(
+ self_: BaseTest, query: ast.SelectQuery | ast.SelectSetQuery, *, dialect: HogQLDialect = "clickhouse"
+) -> tuple[str, HogQLContext]:
+ """Resolve + print, return (sql, context). Inspect `context.values` for parameterized string content."""
+ context = HogQLContext(team_id=self_.team.pk, enable_select_queries=True)
+ sql, _ = prepare_and_print_ast(query, context, dialect)
+ return sql, context
+
+
+def _select_parse_resolve_mutate_print(
+ self_: BaseTest,
+ base_query: str,
+ mutate_fn,
+) -> Optional[str]:
+ """Parse + type-resolve a base query, apply `mutate_fn` to the resolved AST, then print. The resolve step is needed because the printer asserts on unresolved FROM-clause types."""
+ parsed = parse_select(base_query)
+ context = HogQLContext(team_id=self_.team.pk, enable_select_queries=True)
+ from posthog.hogql.printer.utils import prepare_ast_for_printing, print_prepared_ast
+
+ prepared = prepare_ast_for_printing(parsed, context=context, dialect="clickhouse")
+ assert prepared is not None
+ mutate_fn(prepared)
+ return print_prepared_ast(prepared, context=context, dialect="clickhouse")
+
+
+class TestVerbatimFieldConstructionRejection(BaseTest):
+ """Group 1: `__post_init__` rejects out-of-allowlist values at construction."""
+
+ @parameterized.expand(
+ [
+ ("sql_injection", "; DROP TABLE events --"),
+ ("union_injection", "JOIN UNION SELECT 1"),
+ ("not_in_allowlist", "WEIRD JOIN"),
+ ("uppercase_no_join", "LEFT"),
+ ]
+ )
+ def test_join_type_rejects_invalid(self, _name: str, value: str):
+ with self.assertRaises(ValueError):
+ ast.JoinExpr(table=ast.Field(chain=["events"]), join_type=value)
+
+ @parameterized.expand(
+ [
+ ("sql_injection", "ASC; DROP TABLE events --"),
+ ("wrong_case", "asc"),
+ ("not_an_order", "RANDOM"),
+ ("empty", ""),
+ ]
+ )
+ def test_order_rejects_invalid(self, _name: str, value: str):
+ with self.assertRaises(ValueError):
+ # The whole point: pass an out-of-Literal value and verify `__post_init__` rejects it.
+ ast.OrderExpr(expr=ast.Constant(value=1), order=value) # type: ignore[arg-type]
+
+ @parameterized.expand(
+ [
+ ("sql_injection", "ON; DROP TABLE events --"),
+ ("wrong_case", "on"),
+ ("not_a_type", "WHERE"),
+ ("empty", ""),
+ ]
+ )
+ def test_constraint_type_rejects_invalid(self, _name: str, value: str):
+ with self.assertRaises(ValueError):
+ ast.JoinConstraint(expr=ast.Constant(value=True), constraint_type=value) # type: ignore[arg-type]
+
+ @parameterized.expand(
+ [
+ ("sql_injection", "UNION ALL; DROP TABLE events --"),
+ ("not_a_set_op", "JOIN"),
+ ("empty", ""),
+ ("lowercase", "union all"),
+ ]
+ )
+ def test_set_operator_rejects_invalid(self, _name: str, value: str):
+ with self.assertRaises(ValueError):
+ ast.SelectSetNode(
+ select_query=ast.SelectQuery(select=[ast.Constant(value=1)]),
+ set_operator=value, # type: ignore[arg-type]
+ )
+
+
+class TestVerbatimFieldPrinterDefenseInDepth(BaseTest):
+ """Group 2: printer rejects malicious values written via `setattr` past `__post_init__`."""
+
+ def test_join_type_setattr_bypass_rejected_by_printer(self):
+ # Parse with the JOIN already present so type resolution attaches a JoinType to next_join; the mutation targets the resolved field directly.
+ def mutate(node: ast.SelectQuery) -> None:
+ assert node.select_from is not None and node.select_from.next_join is not None
+ node.select_from.next_join.join_type = "LEFT JOIN; DROP TABLE events --"
+
+ with self.assertRaises(QueryError):
+ _select_parse_resolve_mutate_print(
+ self,
+ "SELECT 1 FROM events LEFT JOIN events e2 ON 1 = 1",
+ mutate,
+ )
+
+ def test_order_setattr_bypass_rejected_by_printer(self):
+ def mutate(node: ast.SelectQuery) -> None:
+ assert node.order_by is not None
+ # Deliberate bypass of the `Literal["ASC", "DESC"]` type; the printer's allowlist is what this test exercises.
+ node.order_by[0].order = "ASC; DROP TABLE events --" # type: ignore[assignment] # ty: ignore[invalid-assignment]
+
+ with self.assertRaises(QueryError):
+ _select_parse_resolve_mutate_print(self, "SELECT 1 FROM events ORDER BY 1 ASC", mutate)
+
+ def test_constraint_type_setattr_bypass_rejected_by_printer(self):
+ def mutate(node: ast.SelectQuery) -> None:
+ assert node.select_from is not None and node.select_from.next_join is not None
+ assert node.select_from.next_join.constraint is not None
+ # Deliberate bypass of the `Literal["ON", "USING"]` type.
+ node.select_from.next_join.constraint.constraint_type = "ON; DROP TABLE events --" # type: ignore[assignment] # ty: ignore[invalid-assignment]
+
+ with self.assertRaises(QueryError):
+ _select_parse_resolve_mutate_print(
+ self,
+ "SELECT 1 FROM events LEFT JOIN events e2 ON 1 = 1",
+ mutate,
+ )
+
+ def test_set_operator_setattr_bypass_rejected_by_printer(self):
+ def mutate(node) -> None:
+ assert isinstance(node, ast.SelectSetQuery) # `... UNION ALL ...` parses to a SelectSetQuery
+ # Deliberate bypass of the `SetOperator` Literal type.
+ node.subsequent_select_queries[0].set_operator = "UNION ALL; DROP TABLE events --" # type: ignore[assignment]
+
+ with self.assertRaises(QueryError):
+ _select_parse_resolve_mutate_print(
+ self,
+ "SELECT 1 FROM events UNION ALL SELECT 2 FROM events",
+ mutate,
+ )
+
+
+class TestPrintTimeOnlyAllowlists(BaseTest):
+ """Group 3: fields without `__post_init__`; the printer's branch check is the only allowlist gate."""
+
+ def test_array_join_op_invalid_rejected_at_print_time(self):
+ def mutate(node: ast.SelectQuery) -> None:
+ node.array_join_op = "ARRAY JOIN; DROP TABLE events --"
+ node.array_join_list = [ast.Field(chain=["x"])]
+
+ with self.assertRaises(ImpossibleASTError):
+ _select_parse_resolve_mutate_print(self, "SELECT 1 FROM events", mutate)
+
+ def test_window_frame_type_invalid_rejected_at_print_time(self):
+ # `WindowFrameExpr.frame_type` has no `__post_init__`; the printer branch falls through to `ImpossibleASTError` on values outside `Literal["CURRENT ROW", "PRECEDING", "FOLLOWING"]`.
+ def mutate(node: ast.SelectQuery) -> None:
+ call = node.select[0]
+ assert isinstance(call, ast.WindowFunction) and call.over_expr is not None
+ assert call.over_expr.frame_start is not None
+ call.over_expr.frame_start.frame_type = "FOLLOWING; DROP TABLE--" # type: ignore[assignment] # ty: ignore[invalid-assignment]
+
+ with self.assertRaises(ImpossibleASTError):
+ _select_parse_resolve_mutate_print(
+ self,
+ "SELECT count() OVER (ROWS BETWEEN 1 PRECEDING AND CURRENT ROW) FROM events",
+ mutate,
+ )
+
+
+class TestEscapePreservationOnParserOutput(BaseTest):
+ """Group 4: escape-wrapped paths preserve attacker-controlled content as escaped literals — `Constant.value` (str) lands in `context.values` (CH driver binds it), `Field.chain` identifiers backtick-wrap with embedded-backtick escape via `escape_clickhouse_identifier`."""
+
+ def test_string_constant_with_injection_chars_is_parameterized_not_inlined(self):
+ # Dangerous string content lands in `context.values` (a parameter slot, escaped at bind time by the CH driver), not in the SQL body itself.
+ sql, context = _print(self, parse_select("SELECT 'evil''; DROP TABLE events; --'"))
+ self.assertNotIn("DROP TABLE", sql)
+ self.assertIn("evil'; DROP TABLE events; --", context.values.values())
+
+ def test_string_constant_with_control_chars_does_not_leak_into_sql(self):
+ # Whatever subset of `\n` / `\t` / `\0` survives the HogQL parser must end up in `context.values`, not embedded in the emitted SQL where a raw newline / tab could terminate the statement.
+ sql, context = _print(self, parse_select("SELECT '\\n\\t\\0'"))
+ self.assertNotIn("\n", sql)
+ self.assertNotIn("\t", sql)
+ self.assertNotIn("\0", sql)
+ self.assertGreaterEqual(len(context.values), 1)
+
+ def test_identifier_with_backtick_is_backtick_escaped(self):
+ # HogQL accepts backtick-quoted identifiers with doubled inner backticks; printer re-emits backtick-wrapped with the inner backtick backslash-escaped.
+ sql, _ = _print(self, parse_select("SELECT 1 AS `weird``name` FROM events"))
+ self.assertIn("`weird\\`name`", sql)
+
+ def test_identifier_with_percent_rejected(self):
+ # `%` is reserved for parameter placeholders downstream; every identifier escape path rejects it.
+ with self.assertRaises((QueryError, ExposedHogQLError)):
+ _print(self, parse_select("SELECT 1 AS `bad%percent` FROM events"))
+
+ def test_identifier_with_semicolon_in_backticks_escaped_not_executed(self):
+ # A semicolon inside a backtick-wrapped identifier lexes as part of the identifier — the backtick scope keeps it from terminating the statement.
+ sql, _ = _print(self, parse_select("SELECT 1 AS `id; DROP TABLE events; --`"))
+ self.assertIn("`id; DROP TABLE events; --`", sql)
+
+
+class TestParserPathProducesOnlyAllowlistedVerbatimValues(BaseTest):
+ """Group 5: every parser backend rejects grammar-quirk inputs that would produce out-of-allowlist verbatim-printed values."""
+
+ def test_left_outer_semi_join_rejected_by_all_paths(self):
+ # `LEFT OUTER SEMI JOIN` passes the rust grammar's per-keyword checks but isn't in `VALID_JOIN_TYPES`; cpp / rust-json reject via the JSON deserializer's `cls(**kwargs)`, rust-py rejects via `PyEmitter::set_field` re-running `__post_init__`.
+ q = "SELECT 1 FROM a LEFT OUTER SEMI JOIN b ON a.x = b.x"
+ for backend in ("cpp-json", "rust-json", "rust-py"):
+ with self.assertRaises((ValueError, ExposedHogQLError)):
+ parse_select(q, backend=backend)
diff --git a/posthog/hogql/resolver.py b/posthog/hogql/resolver.py
index 455e8641e118..0877f99961ae 100644
--- a/posthog/hogql/resolver.py
+++ b/posthog/hogql/resolver.py
@@ -67,6 +67,11 @@ POSTGRES_KEYWORD_TYPES: dict[str, PostgresKeywordType] = {
"localtimestamp": ast.DateTimeType,
}
+# Lock the resolver's keyword catalog to `ast.Keyword.__post_init__`'s allowlist; drift in either direction is a silent injection vector or a construction-time crash, so the two sets must move together.
+assert POSTGRES_KEYWORD_TYPES.keys() == ast.VALID_KEYWORD_NAMES, (
+ "POSTGRES_KEYWORD_TYPES and ast.VALID_KEYWORD_NAMES are out of sync — update both."
+)
+
# Dialects that share Postgres's SQL surface (feature support, keyword set, syntax quirks).
# DuckDB is Postgres-wire compatible and accepts nearly all PG-specific constructs, so it
# takes the PG code path in the resolver.
diff --git a/posthog/hogql/scripts/parser_bench.py b/posthog/hogql/scripts/parser_bench.py
index 47e2974257bf..e7d169717c1e 100644
--- a/posthog/hogql/scripts/parser_bench.py
+++ b/posthog/hogql/scripts/parser_bench.py
@@ -21,15 +21,45 @@ Queries the candidate can't parse are flagged and the row is skipped.
For comparable queries the script reports per-call microseconds and a
`oracle/candidate` ratio.
+Statistical rigor: each query is timed across `--repeat` batches of
+`--n` iterations each. Min / median / max are reported so noise can
+be told apart from real changes — the default repeat count is sized
+to surface clear medians without ballooning wall-clock.
+
+**Noise floor caveat.** Empirically, back-to-back runs of the SAME
+binary on the SAME machine drift by 5–7% on the per-rule sum, even at
+N=1000 × 7 batches. The within-run min/max bands are tight (~1–2% of
+median), but the between-run drift is larger — thermal, scheduler,
+GC, and other system effects don't cancel out within a single bench
+invocation. Treat single-run deltas under ~7% as inconclusive; for
+optimization tracking, run the bench at least twice and look for
+consistent direction across both runs. The ★★★ significance flag is
+within-run noise-floor only and doesn't account for between-run
+drift.
+
+For tracking optimization gains, write results to JSON via
+`--json-output PATH`, then re-run with `--compare PATH` to see the
+per-query delta.
+
+For deeper profiling, run the bench under `samply` or `py-spy`:
+
+ samply record -- python posthog/hogql/scripts/parser_bench.py \\
+ --candidate rust-py --n 5000 --repeat 1
+
+Then open the resulting profile.json in samply's UI (https://profiler.firefox.com).
+
The script is intentionally dependency-free beyond what's already in
the backend environment so it can stay around as a quick perf sanity
check as parser implementations evolve.
"""
import argparse
+import json
import os
+import statistics
import sys
import timeit
+from pathlib import Path
from typing import Any
import django
@@ -40,7 +70,8 @@ django.setup()
from posthog.hogql.parser import clear_parse_caches, parse_expr, parse_select
from posthog.hogql.scripts._diagnostic_common import _probe_backend
-DEFAULT_N = 1_000 # iterations per row; override with --n
+DEFAULT_N = 1_000 # iterations per batch; override with --n
+DEFAULT_REPEAT = 5 # batches per query; override with --repeat
# Per-query iteration ceilings for queries cpp parses too slowly for
# the default N. Total wall-clock per row should stay well under a
@@ -227,85 +258,234 @@ SELECT_QUERIES: dict[str, str] = {
}
-def run(parse_fn, n: int) -> float:
- """Per-call microseconds for `n` iterations of `parse_fn()`. The
- caller is expected to pre-bind the query (and backend) via a
- closure so this stays a single-arity callable. Clears the cache
- before each invocation so we measure cold parse cost rather than
- the cache hit path."""
+# ============================================================================
+# Statistics
+# ============================================================================
+
+
+class RowStat:
+ """Per-(query, backend) timing summary across multiple batches."""
+
+ __slots__ = ("samples_us", "n_per_batch")
+
+ def __init__(self, samples_us: list[float], n_per_batch: int) -> None:
+ # `samples_us` is one mean-per-call value per batch (already divided by the batch's iteration count). Kept around for downstream min / median / max / IQR / comparison.
+ self.samples_us = samples_us
+ self.n_per_batch = n_per_batch
+
+ @property
+ def median(self) -> float:
+ return statistics.median(self.samples_us)
+
+ @property
+ def min(self) -> float:
+ return min(self.samples_us)
+
+ @property
+ def max(self) -> float:
+ return max(self.samples_us)
+
+ @property
+ def mean(self) -> float:
+ return statistics.fmean(self.samples_us)
+
+ def to_json(self) -> dict[str, Any]:
+ return {
+ "samples_us": self.samples_us,
+ "n_per_batch": self.n_per_batch,
+ }
+
+ @classmethod
+ def from_json(cls, data: dict[str, Any]) -> "RowStat":
+ return cls(samples_us=list(data["samples_us"]), n_per_batch=int(data["n_per_batch"]))
+
+
+def _format_us(us: float) -> str:
+ """Per-call µs formatted for the human-readable table — wide enough to keep the column aligned across the corpus' three orders of magnitude (a few µs for `int_literal`, thousands for `pathological_deep`)."""
+ return f"{us:>10.3f}"
+
+
+# ============================================================================
+# Bench runner
+# ============================================================================
+
+
+def time_one(parse_fn, n: int) -> float:
+ """Per-call microseconds for `n` iterations of `parse_fn()`. The caller pre-binds query/backend via closure so this stays single-arity. Clears the cache before each invocation so we measure cold parse cost, not the cache hit path."""
def body() -> Any:
clear_parse_caches()
return parse_fn()
- # Warm up to surface errors before we time.
- body()
secs = timeit.timeit(body, number=n)
return secs / n * 1e6
+def run_query(parse_fn, q: str, backend: str, n: int, repeat: int) -> RowStat:
+ """Run `parse_fn(q, backend=backend)` for `repeat` batches of `n` iterations each. One warm-up call up front to surface errors before timing.
+
+ Returns a `RowStat` with one sample per batch (each sample is a per-call µs mean) so callers can inspect min/median/max + raw distribution. Re-clears the parse cache inside each batch via `time_one`'s body wrapper."""
+ parse_fn(q, backend=backend)
+ samples = [time_one(lambda: parse_fn(q, backend=backend), n) for _ in range(repeat)]
+ return RowStat(samples_us=samples, n_per_batch=n)
+
+
+# ============================================================================
+# Single-run report
+# ============================================================================
+
+
def bench(
label: str,
parse_fn,
queries: dict[str, str],
n: int,
+ repeat: int,
oracle: str,
candidate: str,
-) -> int:
- # Some rows have per-query iteration overrides (slow cpp queries
- # would otherwise burn minutes), so make that explicit in the
- # header — a reader correlating header `N` to a row's µs needs to
- # know the row may have used a different N.
- # Show only overrides that actually take effect at this `n` — with a
- # small `--n` the `min(override, n)` ceiling collapses to `n`, so the
- # override is a no-op and listing it would mislead.
+) -> tuple[int, dict[str, dict[str, Any]]]:
+ """Run the bench for one rule across the whole corpus.
+
+ Returns `(comparable_count, results_dict)` where `results_dict` maps query name → {oracle: RowStat.to_json(), candidate: RowStat.to_json(), chars: int, error: optional[str]}. The caller assembles the rule-keyed top-level dict for JSON serialisation.
+ """
+ # Per-query iteration overrides (slow cpp queries would otherwise burn minutes) — surface them in the header so readers correlating header `N` to a row's µs know the row may have used a different N.
+ # Show only overrides that actually take effect at this `n` — with a small `--n` the `min(override, n)` ceiling collapses to `n` and the override becomes a no-op.
overrides_in_use = {
name: min(N_PER_QUERY[name], n) for name in queries if name in N_PER_QUERY and N_PER_QUERY[name] < n
}
override_note = f", overrides: {overrides_in_use}" if overrides_in_use else ""
- print(f"\n{label} (N={n} per row, oracle={oracle}, candidate={candidate}{override_note})")
- print(f"{'query':<30} {'chars':>6} {'oracle(us)':>12} {'candidate(us)':>14} {'oracle/cand':>12}")
- print("-" * 78)
+ print(f"\n{label} (N={n} per batch × {repeat} batches, oracle={oracle}, candidate={candidate}{override_note})")
+ print(
+ f"{'query':<30} {'chars':>6} "
+ f"{'oracle median':>14} {'(min..max)':>15} "
+ f"{'cand median':>13} {'(min..max)':>15} "
+ f"{'ratio':>7}"
+ )
+ print("-" * 105)
+ results: dict[str, dict[str, Any]] = {}
oracle_total, cand_total, comparable = 0.0, 0.0, 0
for name, q in queries.items():
nq = min(N_PER_QUERY.get(name, n), n)
- # Annotate the row name when its N differs from the header so a
- # reader doesn't have to cross-reference the override map to
- # interpret the µs value.
row_label = name if nq == n else f"{name} [N={nq}]"
+ row: dict[str, Any] = {"chars": len(q)}
try:
- oracle_us = run(lambda q=q: parse_fn(q, backend=oracle), nq)
+ oracle_stat = run_query(parse_fn, q, oracle, nq, repeat)
+ row["oracle"] = oracle_stat.to_json()
except Exception as e:
- print(f"{row_label:<30} {len(q):>6} {'ERROR':>12} {'-':>14} {'-':>12} ({oracle}: {e})")
+ row["error"] = f"oracle ({oracle}): {e}"
+ results[name] = row
+ print(f"{row_label:<30} {len(q):>6} ERROR ({oracle}: {e})")
continue
try:
- cand_us = run(lambda q=q: parse_fn(q, backend=candidate), nq)
+ cand_stat = run_query(parse_fn, q, candidate, nq, repeat)
+ row["candidate"] = cand_stat.to_json()
except Exception as e:
- print(f"{row_label:<30} {len(q):>6} {oracle_us:>12.3f} {'(skip)':>14} {'-':>12} ({candidate}: {e})")
+ row["error"] = f"candidate ({candidate}): {e}"
+ results[name] = row
+ print(f"{row_label:<30} {len(q):>6} {_format_us(oracle_stat.median)} (skip) ({candidate}: {e})")
continue
- ratio = oracle_us / cand_us if cand_us > 0 else float("nan")
- print(f"{row_label:<30} {len(q):>6} {oracle_us:>12.3f} {cand_us:>14.3f} {ratio:>11.1f}x")
- oracle_total += oracle_us
- cand_total += cand_us
+ ratio = oracle_stat.median / cand_stat.median if cand_stat.median > 0 else float("nan")
+ print(
+ f"{row_label:<30} {len(q):>6} "
+ f"{_format_us(oracle_stat.median)} "
+ f"({oracle_stat.min:>6.1f}..{oracle_stat.max:<6.1f}) "
+ f"{_format_us(cand_stat.median)} "
+ f"({cand_stat.min:>6.1f}..{cand_stat.max:<6.1f}) "
+ f"{ratio:>6.1f}x"
+ )
+ oracle_total += oracle_stat.median
+ cand_total += cand_stat.median
comparable += 1
+ results[name] = row
- print("-" * 78)
+ print("-" * 105)
if comparable:
- # The time columns ARE arithmetic means of per-row times.
- # The ratio column is the ratio of those means
- # (equivalently `sum(oracle) / sum(cand)`), which weights each
- # row by absolute time spent — the right metric for an
- # "overall speedup" reading. Note this is NOT the arithmetic
- # mean of per-row ratios; on a corpus with vastly different
- # absolute times, that mean would over-weight cheap rows.
+ # Mean cells use per-row medians; overall ratio is `sum(oracle_median) / sum(cand_median)`, weighting each row by absolute time — the right metric for "overall speedup", since averaging per-row ratios would let cheap rows drown out expensive ones.
overall = oracle_total / cand_total if cand_total > 0 else float("nan")
print(
- f"{'mean (per-call µs)':<30} {'':>6} {oracle_total / comparable:>12.3f} "
- f"{cand_total / comparable:>14.3f} {overall:>11.1f}x "
+ f"{'mean (per-call µs)':<30} {'':>6} "
+ f"{oracle_total / comparable:>14.3f} {'':>15} "
+ f"{cand_total / comparable:>13.3f} {'':>15} "
+ f"{overall:>6.1f}x "
f"(ratio sum-weighted; {comparable}/{len(queries)} comparable)"
)
- return comparable
+ return comparable, results
+
+
+# ============================================================================
+# Compare-mode report
+# ============================================================================
+
+
+def _significant(a: RowStat, b: RowStat) -> bool:
+ """Significance gate: non-overlapping [min..max] ranges AND ≥5% relative delta. The 5% threshold sits at the upper edge of the 5–7% same-binary noise floor observed across repeat runs. Single-sample stats fall back to the relative-threshold-only check since they can't drive the non-overlap test."""
+ if len(a.samples_us) <= 1 or len(b.samples_us) <= 1:
+ return abs(a.median - b.median) / max(a.median, b.median, 1e-9) > 0.05
+ non_overlap = a.max < b.min or b.max < a.min
+ rel_delta = abs(a.median - b.median) / max(a.median, b.median, 1e-9)
+ return non_overlap and rel_delta > 0.05
+
+
+def _delta_str(before: float, after: float) -> str:
+ """`+12.3%` / `-12.3%` for a row delta; falls back to `nan` if the baseline value was zero."""
+ if before <= 0:
+ return "nan"
+ pct = (after - before) / before * 100
+ sign = "+" if pct >= 0 else ""
+ return f"{sign}{pct:.1f}%"
+
+
+def compare(baseline_path: Path, current_data: dict[str, Any], candidate: str) -> None:
+ """Diff a previous JSON result against the current run. Per-row delta + significance flag; sum-weighted-mean delta for each rule.
+
+ `current_data` is the in-memory result dict the live run just built (rules → query → row). `baseline_path` points at a previous `--json-output` file; we compare candidate stats only — oracle stats are typically the same backend across runs, and even when they're not, a "candidate before vs candidate after" diff is what optimization runs want."""
+ print(f"\n=== Compare candidate {candidate!r} vs baseline {baseline_path.as_posix()} ===\n")
+
+ baseline_raw = json.loads(baseline_path.read_text())
+ base_candidate = baseline_raw.get("meta", {}).get("candidate", "<unknown>")
+ if base_candidate != candidate:
+ print(
+ f"NOTE: baseline candidate {base_candidate!r} differs from current {candidate!r} — "
+ f"deltas compare two DIFFERENT backends, not the same backend before/after.\n"
+ )
+
+ for rule in ("parse_expr", "parse_select"):
+ baseline_rows = baseline_raw.get("rules", {}).get(rule, {})
+ current_rows = current_data.get("rules", {}).get(rule, {})
+ if not baseline_rows or not current_rows:
+ continue
+ print(f"\n{rule} (candidate diff)")
+ print(f"{'query':<30} {'before':>10} {'after':>10} {'delta':>10} flag")
+ print("-" * 75)
+ before_total, after_total = 0.0, 0.0
+ for name in current_rows:
+ before_row = baseline_rows.get(name)
+ after_row = current_rows.get(name)
+ if before_row is None or "candidate" not in before_row or "candidate" not in after_row:
+ continue
+ before = RowStat.from_json(before_row["candidate"])
+ after = RowStat.from_json(after_row["candidate"])
+ flag = "★★★" if _significant(before, after) else ""
+ improvement = before.median > after.median
+ flag_color = flag + (" (faster)" if improvement and flag else (" (slower)" if flag else ""))
+ print(
+ f"{name:<30} {_format_us(before.median):>10} {_format_us(after.median):>10} "
+ f"{_delta_str(before.median, after.median):>10} {flag_color}"
+ )
+ before_total += before.median
+ after_total += after.median
+ print("-" * 75)
+ if before_total > 0 and after_total > 0:
+ print(
+ f"{'sum (per-call µs)':<30} {before_total:>10.3f} {after_total:>10.3f} "
+ f"{_delta_str(before_total, after_total):>10}"
+ )
+
+
+# ============================================================================
+# CLI plumbing
+# ============================================================================
def main() -> int:
@@ -332,15 +512,51 @@ def main() -> int:
type=int,
default=DEFAULT_N,
help=(
- f"Iterations per row (default: {DEFAULT_N}). Lower it for a quick "
+ f"Iterations per batch (default: {DEFAULT_N}). Lower it for a quick "
f"sanity check during grinding, e.g. --n 50. Per-query ceilings in "
f"N_PER_QUERY still apply as min(ceiling, --n)."
),
)
+ parser.add_argument(
+ "--repeat",
+ type=int,
+ default=DEFAULT_REPEAT,
+ help=(
+ f"Batches per query (default: {DEFAULT_REPEAT}). Each batch is "
+ f"`--n` iterations; we report median / min / max across the "
+ f"batches so noise can be told apart from real changes. Set to 1 "
+ f"for a quick run, 10+ for an optimization-tracking baseline."
+ ),
+ )
+ parser.add_argument(
+ "--json-output",
+ type=Path,
+ default=None,
+ help=(
+ "Write the full result corpus to PATH as JSON. The file shape is "
+ "`{meta: {…}, rules: {parse_expr: {query: {oracle, candidate, chars}}, "
+ "parse_select: {…}}}`. Use with `--compare` on a future run to "
+ "diff the two."
+ ),
+ )
+ parser.add_argument(
+ "--compare",
+ type=Path,
+ default=None,
+ help=(
+ "After running the bench, load a previous `--json-output` file at "
+ "PATH and print a per-row delta with a significance flag (★★★ when "
+ "the two runs' [min..max] ranges don't overlap, i.e., the change "
+ "is larger than the noise floor)."
+ ),
+ )
args = parser.parse_args()
if args.n < 1:
print("ERROR: --n must be at least 1")
return 2
+ if args.repeat < 1:
+ print("ERROR: --repeat must be at least 1")
+ return 2
if not args.candidate:
print(
"ERROR: --candidate is required (no default). The Python "
@@ -364,8 +580,17 @@ def main() -> int:
return 2
comparable = 0
- comparable += bench("parse_expr", parse_expr, EXPR_QUERIES, args.n, args.oracle, args.candidate)
- comparable += bench("parse_select", parse_select, SELECT_QUERIES, args.n, args.oracle, args.candidate)
+ rules_data: dict[str, dict[str, Any]] = {}
+ expr_comparable, expr_rows = bench(
+ "parse_expr", parse_expr, EXPR_QUERIES, args.n, args.repeat, args.oracle, args.candidate
+ )
+ select_comparable, select_rows = bench(
+ "parse_select", parse_select, SELECT_QUERIES, args.n, args.repeat, args.oracle, args.candidate
+ )
+ comparable = expr_comparable + select_comparable
+ rules_data["parse_expr"] = expr_rows
+ rules_data["parse_select"] = select_rows
+
if comparable == 0:
print(
f"\nERROR: zero comparable rows — candidate {args.candidate!r} "
@@ -374,6 +599,25 @@ def main() -> int:
f"config issue."
)
return 1
+
+ current_data = {
+ "meta": {
+ "oracle": args.oracle,
+ "candidate": args.candidate,
+ "n_per_batch": args.n,
+ "repeats": args.repeat,
+ },
+ "rules": rules_data,
+ }
+
+ if args.json_output:
+ args.json_output.parent.mkdir(parents=True, exist_ok=True)
+ args.json_output.write_text(json.dumps(current_data, indent=2))
+ print(f"\nWrote results to {args.json_output}")
+
+ if args.compare:
+ compare(args.compare, current_data, args.candidate)
+
return 0
diff --git a/posthog/hogql/test/_test_parser.py b/posthog/hogql/test/_test_parser.py
index 882c23ecf55a..4d7faad8a5ad 100644
--- a/posthog/hogql/test/_test_parser.py
+++ b/posthog/hogql/test/_test_parser.py
@@ -2716,6 +2716,31 @@ def parser_test_factory(backend: HogQLParserBackend):
),
)
+ def test_grammar_quirk_invalid_join_type_rejected_on_all_backends(self):
+ # `LEFT OUTER SEMI JOIN` passes the rust grammar's per-keyword checks (no rule forbids the combination) but isn't in `VALID_JOIN_TYPES`. Every backend must reject via `JoinExpr.__post_init__`; the rust-py path covers this via `PyEmitter::set_field` re-firing `__post_init__` because `join_type` is written post-construction by `chain_join`.
+ q = "SELECT 1 FROM a LEFT OUTER SEMI JOIN b ON a.x = b.x"
+ with self.assertRaises((ValueError, ExposedHogQLError)) as cm:
+ self._select(q)
+ self.assertIn("Invalid join type", str(cm.exception))
+
+ def test_deeply_nested_expression_does_not_stack_overflow(self):
+ # Deep paren input must surface a clean `SyntaxError`, not stack-OOM in the recursive-descent loop. Cap lives at `MAX_EXPR_RECURSION_DEPTH = 1000`, mirrors ClickHouse's `max_parser_depth`. cpp / python paths have their own stack characteristics so the assertion is rust-specific.
+ if backend not in ("rust-json", "rust-py"):
+ self.skipTest("rust-specific recursion cap")
+ deep = "(" * 1500 + "1" + ")" * 1500
+ with self.assertRaises(SyntaxError) as cm:
+ self._expr(deep)
+ self.assertIn("too deeply nested", str(cm.exception).lower())
+
+ def test_ctes_inject_into_paren_wrapped_inner_with(self):
+ # An outer WITH attached to a paren-wrapped inner that already has its own WITH must surface both CTEs, with the outer's appended after the inner's (matches cpp's `VISIT(SelectStmtWithParens)` ordering).
+ node = cast(
+ ast.SelectQuery,
+ self._select("WITH a AS (SELECT 1) (WITH b AS (SELECT 2) SELECT * FROM b)"),
+ )
+ assert isinstance(node.ctes, dict)
+ self.assertEqual(list(node.ctes.keys()), ["b", "a"])
+
def test_ctes_preserve_declaration_order(self):
node = cast(
ast.SelectQuery,
diff --git a/posthog/hogql/test/test_parser_mode.py b/posthog/hogql/test/test_parser_mode.py
index 8916cd4f739e..fb2229d6ef7a 100644
--- a/posthog/hogql/test/test_parser_mode.py
+++ b/posthog/hogql/test/test_parser_mode.py
@@ -20,6 +20,8 @@ class TestParserMode(BaseTest):
(ParserMode.RUST_ONLY, ("rust-json", None)),
(ParserMode.CPP_WITH_RUST_SHADOW, ("cpp-json", "rust-json")),
(ParserMode.RUST_WITH_CPP_SHADOW, ("rust-json", "cpp-json")),
+ (ParserMode.RUST_PY_ONLY, ("rust-py", None)),
+ (ParserMode.RUST_PY_WITH_CPP_SHADOW, ("rust-py", "cpp-json")),
]
)
def test_resolve_parser_mode(self, mode, expected):
diff --git a/posthog/hogql/test/test_parser_rust_py.py b/posthog/hogql/test/test_parser_rust_py.py
new file mode 100644
index 000000000000..907ba773563d
--- /dev/null
+++ b/posthog/hogql/test/test_parser_rust_py.py
@@ -0,0 +1,46 @@
+"""Tests for the hand-rolled Rust HogQL parser via the direct-Python-object path (`rust-py`).
+
+The full parser-behaviour suite lives in `_test_parser.py` and runs
+against every backend via `parser_test_factory`. This file only wires
+the `rust-py` backend into that suite. Same parser core as `rust-json`;
+only difference is how the result lands in Python (PyO3 builds the
+dataclass instances directly, skipping the JSON round-trip).
+"""
+
+from unittest.mock import patch
+
+from posthog.hogql import ast
+from posthog.hogql.errors import BaseHogQLError
+from posthog.hogql.parser import parse_select
+
+from ._test_parser import parser_test_factory
+
+# Same deferral as `rust-json`: PyEmitter's `with_pos` chain doesn't yet
+# propagate positions onto the promoted assignment target node. Underlying
+# parser logic is shared, so the gap is wired in `with_pos` rather than
+# in the per-backend AST shape.
+_DEFERRED_EXACT: set[str] = {
+ "test_promoted_assignment_target_carries_position",
+}
+
+
+class TestParserRustPy(parser_test_factory("rust-py")): # type: ignore
+ def setUp(self) -> None:
+ super().setUp()
+ if self._testMethodName in _DEFERRED_EXACT:
+ self.skipTest("not yet matched by rust-py")
+
+ def test_empty(self):
+ # this test only exists to make pycharm recognise this class as a test class
+ # the actual tests are in the parent class
+ pass
+
+ def test_dataclass_post_init_failure_surfaces_as_hogql_error(self):
+ # PyEmitter.build calls `class(**kwargs)`; a dataclass `__post_init__` that raises lands as a Rust panic. `run_py`'s `catch_unwind` converts it to a `BaseHogQLError`, which production handlers catch; without the wrap PyO3 would surface `PanicException` (a `BaseException`, not in the HogQL error family).
+ def always_reject(_self: ast.JoinExpr) -> None:
+ raise ValueError("synthetic post_init failure for test")
+
+ with patch.object(ast.JoinExpr, "__post_init__", always_reject):
+ with self.assertRaises(BaseHogQLError) as caught:
+ parse_select("SELECT 1 FROM a JOIN b ON a.x = b.x", backend="rust-py")
+ self.assertIn("synthetic post_init failure", str(caught.exception))
diff --git a/posthog/schema.py b/posthog/schema.py
index b179a1e0097e..8be6a872f0bf 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -2591,6 +2591,8 @@ class ParserMode(StrEnum):
CPP_WITH_RUST_SHADOW = "cpp_with_rust_shadow"
RUST_WITH_CPP_SHADOW = "rust_with_cpp_shadow"
RUST_ONLY = "rust_only"
+ RUST_PY_ONLY = "rust_py_only"
+ RUST_PY_WITH_CPP_SHADOW = "rust_py_with_cpp_shadow"
class PersonsArgMaxVersion(StrEnum):
@@ -7312,7 +7314,9 @@ class HogQLQueryModifiers(BaseModel):
description=(
"HogQL parser backend; absent → `cpp_only`. `*_shadow` modes return the"
" primary result and sample-compare against the other parser, reporting"
- " divergences without failing the request."
+ " divergences without failing the request. The `rust_py_*` modes drive the"
+ " same hand-rolled Rust parser as `rust_*` but build `posthog.hogql.ast`"
+ " dataclass instances directly via PyO3, skipping the JSON round-trip."
),
)
personsArgMaxVersion: PersonsArgMaxVersion | None = None
diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.ts
index c78a24d7ff43..f5a1a1944138 100644
--- a/products/product_analytics/frontend/generated/api.schemas.ts
+++ b/products/product_analytics/frontend/generated/api.schemas.ts
@@ -358,6 +358,8 @@ export const ParserModeApi = {
CppWithRustShadow: 'cpp_with_rust_shadow',
RustWithCppShadow: 'rust_with_cpp_shadow',
RustOnly: 'rust_only',
+ RustPyOnly: 'rust_py_only',
+ RustPyWithCppShadow: 'rust_py_with_cpp_shadow',
} as const
export type PersonsArgMaxVersionApi = (typeof PersonsArgMaxVersionApi)[keyof typeof PersonsArgMaxVersionApi]
@@ -424,7 +426,7 @@ export interface HogQLQueryModifiersApi {
materializedColumnsOptimizationMode?: MaterializedColumnsOptimizationModeApi | null
optimizeJoinedFilters?: boolean | null
optimizeProjections?: boolean | null
- /** HogQL parser backend; absent → `cpp_only`. `*_shadow` modes return the primary result and sample-compare against the other parser, reporting divergences without failing the request. */
+ /** HogQL parser backend; absent → `cpp_only`. `*_shadow` modes return the primary result and sample-compare against the other parser, reporting divergences without failing the request. The `rust_py_*` modes drive the same hand-rolled Rust parser as `rust_*` but build `posthog.hogql.ast` dataclass instances directly via PyO3, skipping the JSON round-trip. */
parserMode?: ParserModeApi | null
personsArgMaxVersion?: PersonsArgMaxVersionApi | null
personsJoinMode?: PersonsJoinModeApi | null
diff --git a/pyproject.toml b/pyproject.toml
index d8467ef630fa..5de6be29c701 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -68,7 +68,7 @@ dependencies = [
"grpcio~=1.71.0",
"gspread==6.2.1",
"hogql-parser==1.3.65",
- "hogql-parser-rs==1.3.69", # built from rust/hogql/parser via the build-hogql-parser-rs workflow + published to PyPI; rebuild locally with `uv pip install -e rust/hogql/parser` when iterating
+ "hogql-parser-rs==1.3.71", # built from rust/hogql/parser via the build-hogql-parser-rs workflow + published to PyPI; rebuild locally with `uv pip install -e rust/hogql/parser` when iterating
"humanize~=4.12.3",
"infi-clickhouse-orm",
"jsonref==1.1.0",
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index 07866fff2746..17a84fc75ea1 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -4142,7 +4142,7 @@ dependencies = [
[[package]]
name = "hogql_parser_rs"
-version = "1.3.69"
+version = "1.3.71"
dependencies = [
"pyo3",
"serde_json",
diff --git a/rust/hogql/parser/Cargo.toml b/rust/hogql/parser/Cargo.toml
index 9cd88412cb5c..dcf08bea0c88 100644
--- a/rust/hogql/parser/Cargo.toml
+++ b/rust/hogql/parser/Cargo.toml
@@ -3,7 +3,7 @@ name = "hogql_parser_rs"
# Track the cpp parser in `common/hogql_parser/setup.py` — both ship as
# wheels named after the same HogQL grammar revision, so versions move in
# lockstep.
-version = "1.3.69"
+version = "1.3.71"
edition = "2021"
publish = false
diff --git a/rust/hogql/parser/pyproject.toml b/rust/hogql/parser/pyproject.toml
index 42a23dcac5f6..8569eb335608 100644
--- a/rust/hogql/parser/pyproject.toml
+++ b/rust/hogql/parser/pyproject.toml
@@ -10,7 +10,7 @@ build-backend = "maturin"
name = "hogql_parser_rs"
# Mirrors `rust/hogql/parser/Cargo.toml` and `common/hogql_parser/setup.py`.
# All three move in lockstep on every HogQL grammar change.
-version = "1.3.69"
+version = "1.3.71"
description = "Hand-rolled Rust HogQL parser with C++-parity AST output"
readme = "README.md"
requires-python = ">=3.12"
diff --git a/rust/hogql/parser/src/emit.rs b/rust/hogql/parser/src/emit.rs
index 2bf3a4c99209..2a8eb9943da0 100644
--- a/rust/hogql/parser/src/emit.rs
+++ b/rust/hogql/parser/src/emit.rs
@@ -1,313 +1,880 @@
-//! JSON node builders matching the AST dataclasses at
-//! [`posthog/hogql/ast.py`].
+//! The `Emitter` trait abstracts AST node construction so the parser can emit either `serde_json::Value` (via `JsonEmitter`, used by `parse_*_json` entry points + the future WASM build) or Python `posthog.hogql.ast` dataclass instances directly during parse (via `PyEmitter` in `emit_py.rs`, used by `parse_*_py`).
//!
-//! The Python deserialiser at [`posthog/hogql/json_ast.py`] builds the
-//! dataclass from each JSON object's fields and falls back to dataclass
-//! defaults for anything missing. So we can emit a minimal shape (just the
-//! fields we have a value for) and still produce equivalent objects to the
-//! C++ visitor's more verbose output. Tests compare via
-//! `assertEqual(parse(...), ast.Foo(...))` which invokes the dataclass
-//! `__eq__`; default-equal fields pass either way.
+//! Field names and shapes mirror the dataclasses at [`posthog/hogql/ast.py`]. The Python deserialiser at [`posthog/hogql/json_ast.py`] also builds these dataclasses from the JSON shape, so the two backends produce `__eq__`-equivalent objects.
use serde_json::{json, Value};
-
-pub fn constant(value: Value) -> Value {
- json!({"node": "Constant", "value": value})
-}
-
-/// `inf`, `-inf`, `nan` go through as a string with `value_type: "number"`
-/// envelope. Mirrors the C++ visitor which uses `nlohmann::json` strings for
-/// non-finite floats since standard JSON doesn't represent them.
-pub fn constant_special_number(name: &'static str) -> Value {
- json!({"node": "Constant", "value": name, "value_type": "number"})
-}
-
-/// An integer-literal Constant whose magnitude exceeds `i64`. The exact
-/// digit text (decimal, or `0x…` hex, with an optional leading `-`) is
-/// carried in the same `value_type: "number"` string envelope; the
-/// deserialiser rebuilds an arbitrary-precision Python `int` from it.
-/// `serde_json::Value` can't hold an integer wider than `u64`, so the
-/// literal can't round-trip as a native JSON number.
-pub fn constant_number_string(text: String) -> Value {
- json!({"node": "Constant", "value": text, "value_type": "number"})
-}
-
-pub fn field(chain: Vec<Value>) -> Value {
- json!({"node": "Field", "chain": chain})
-}
-
-pub fn arith(left: Value, op: &str, right: Value) -> Value {
- json!({"node": "ArithmeticOperation", "left": left, "right": right, "op": op})
-}
-
-pub fn compare(left: Value, op: &str, right: Value) -> Value {
- json!({"node": "CompareOperation", "left": left, "right": right, "op": op})
-}
-
-pub fn compare_is_null(left: Value, negated: bool) -> Value {
- json!({
- "node": "CompareOperation",
- "left": left,
- "right": Value::Null.tagged_constant(),
- "op": if negated { "!=" } else { "==" },
- "is_null_comparison_style": true,
- })
-}
-
-pub fn is_distinct_from(left: Value, right: Value, negated: bool) -> Value {
- json!({"node": "IsDistinctFrom", "left": left, "right": right, "negated": negated})
-}
-
-pub fn between(expr: Value, low: Value, high: Value, negated: bool) -> Value {
- json!({"node": "BetweenExpr", "expr": expr, "low": low, "high": high, "negated": negated})
-}
-
-pub fn not_(expr: Value) -> Value {
- json!({"node": "Not", "expr": expr})
-}
-
-pub fn and_(exprs: Vec<Value>) -> Value {
- json!({"node": "And", "exprs": exprs})
-}
-
-pub fn or_(exprs: Vec<Value>) -> Value {
- json!({"node": "Or", "exprs": exprs})
-}
-
-pub fn tuple_(exprs: Vec<Value>) -> Value {
- json!({"node": "Tuple", "exprs": exprs})
-}
-
-pub fn array_(exprs: Vec<Value>) -> Value {
- json!({"node": "Array", "exprs": exprs})
-}
-
-pub fn array_access(array: Value, property: Value, nullish: bool) -> Value {
- if nullish {
- json!({"node": "ArrayAccess", "array": array, "property": property, "nullish": true})
- } else {
- json!({"node": "ArrayAccess", "array": array, "property": property})
+use std::borrow::Cow;
+
+/// AST node + value constructor surface. Every construction site in the parser routes through this trait so the same parse logic can produce `serde_json::Value` (kept for WASM and tests) or Python dataclass instances directly via PyO3.
+///
+/// Inspection methods (`node_kind`, `get_field`, …) cover the parser's post-construction AST-surgery patterns: split-and-hoist for nested BETWEEN, AND/OR chain folding, position propagation, and concat merging. JSON impls read the underlying map directly; the Python impl uses PyO3 `getattr` against the dataclass attrs.
+pub trait Emitter {
+ /// AST tree handle. Cheap to clone (Json: refcount via Value::clone; Py: `Bound::clone_ref` on the underlying PyObject).
+ type Value: Clone;
+
+ // ===== Primitive value constructors =====
+ /// `None`-equivalent (Json null / Py None). Sentinel for "no value" slots that the deserialiser maps to dataclass-field `None` defaults.
+ fn null(&self) -> Self::Value;
+ fn bool(&self, v: bool) -> Self::Value;
+ fn int(&self, v: i64) -> Self::Value;
+ fn string(&self, v: &str) -> Self::Value;
+ /// Finite float as `Value::Number` (Json) / Python float (Py). Non-finite (NaN, ±Inf) routes through `constant_special_number` instead.
+ fn float(&self, v: f64) -> Self::Value;
+ /// Unsigned integer beyond i64 range. JSON emits as `Value::Number` via `u64` (preserving magnitude); Py emits as a Python int.
+ fn uint(&self, v: u64) -> Self::Value;
+ /// Raw map value (JSON object / Python dict) keyed by string. Used for AST fields whose JSON shape is `{key: child_node, …}` rather than a list: `window_exprs`, `ctes` (dict-form), `replace`. The deserialiser respects this via `_DICT_FIELDS`.
+ fn string_keyed_map(&self, pairs: Vec<(String, Self::Value)>) -> Self::Value;
+ /// Raw list value (JSON array / Python list). Distinct from the `Array(...)` AST node — used for fields whose value is a plain list, e.g. `HogQLXAttribute.children`.
+ fn list_value(&self, items: Vec<Self::Value>) -> Self::Value;
+
+ // ===== AST node builders =====
+ fn constant(&self, value: Self::Value) -> Self::Value;
+ /// `inf` / `-inf` / `nan` shipped as a string with `value_type: "number"`. Mirrors cpp's nlohmann::json-string encoding for non-finite floats.
+ fn constant_special_number(&self, name: &'static str) -> Self::Value;
+ /// Integer-literal Constant whose magnitude exceeds i64. Exact decimal or `0x…` hex digits with optional leading `-`; deserialiser rebuilds an arbitrary-precision Python int.
+ fn constant_number_string(&self, text: String) -> Self::Value;
+ fn field(&self, chain: Vec<Self::Value>) -> Self::Value;
+ fn arith(&self, left: Self::Value, op: &str, right: Self::Value) -> Self::Value;
+ fn compare(&self, left: Self::Value, op: &str, right: Self::Value) -> Self::Value;
+ fn compare_is_null(&self, left: Self::Value, negated: bool) -> Self::Value;
+ fn is_distinct_from(&self, left: Self::Value, right: Self::Value, negated: bool)
+ -> Self::Value;
+ fn between(
+ &self,
+ expr: Self::Value,
+ low: Self::Value,
+ high: Self::Value,
+ negated: bool,
+ ) -> Self::Value;
+ fn not_(&self, expr: Self::Value) -> Self::Value;
+ fn and_(&self, exprs: Vec<Self::Value>) -> Self::Value;
+ fn or_(&self, exprs: Vec<Self::Value>) -> Self::Value;
+ fn tuple_(&self, exprs: Vec<Self::Value>) -> Self::Value;
+ fn array_(&self, exprs: Vec<Self::Value>) -> Self::Value;
+ fn array_access(&self, array: Self::Value, property: Self::Value, nullish: bool)
+ -> Self::Value;
+ fn tuple_access(&self, tuple_: Self::Value, index: i64, nullish: bool) -> Self::Value;
+ fn alias(&self, expr: Self::Value, name: &str) -> Self::Value;
+ fn call(&self, name: &str, args: Vec<Self::Value>) -> Self::Value;
+ #[allow(clippy::too_many_arguments)]
+ fn call_full(
+ &self,
+ name: &str,
+ params: Option<Vec<Self::Value>>,
+ args: Vec<Self::Value>,
+ distinct: bool,
+ order_by: Option<Vec<Self::Value>>,
+ filter_expr: Option<Self::Value>,
+ within_group: Option<Vec<Self::Value>>,
+ ) -> Self::Value;
+ fn lambda(&self, args: Vec<String>, expr: Self::Value) -> Self::Value;
+ /// `ExprCall(expr, args)` — call where the head is an arbitrary expression rather than a function name. Emitted by `ColumnExprCall` (always) and `ColumnExprCallSelect` (when LHS isn't a single-element Field chain).
+ fn expr_call(&self, expr: Self::Value, args: Vec<Self::Value>) -> Self::Value;
+ fn type_cast(&self, expr: Self::Value, type_name: &str) -> Self::Value;
+ fn try_cast(&self, expr: Self::Value, type_name: &str) -> Self::Value;
+ fn array_slice(
+ &self,
+ array: Self::Value,
+ start: Option<Self::Value>,
+ end: Option<Self::Value>,
+ ) -> Self::Value;
+ fn dict_(&self, items: Vec<(Self::Value, Self::Value)>) -> Self::Value;
+ fn placeholder(&self, expr: Self::Value) -> Self::Value;
+ fn named_argument(&self, name: &str, value: Self::Value) -> Self::Value;
+ /// `e IGNORE NULLS` is dropped by the C++ visitor — the expression returns as-is. Kept as a named helper to leave room for richer behaviour later.
+ fn ignore_nulls(&self, expr: Self::Value) -> Self::Value {
+ expr
}
-}
-
-pub fn tuple_access(tuple_: Value, index: i64, nullish: bool) -> Value {
- if nullish {
- json!({"node": "TupleAccess", "tuple": tuple_, "index": index, "nullish": true})
- } else {
- json!({"node": "TupleAccess", "tuple": tuple_, "index": index})
+ fn order_expr(
+ &self,
+ expr: Self::Value,
+ order: &str,
+ with_fill: Option<Self::Value>,
+ ) -> Self::Value;
+ fn columns_expr(
+ &self,
+ regex: Option<String>,
+ columns: Option<Vec<Self::Value>>,
+ all_columns: bool,
+ exclude: Option<Vec<String>>,
+ replace: Option<Vec<(String, Self::Value)>>,
+ ) -> Self::Value;
+ fn spread_expr(&self, expr: Self::Value) -> Self::Value;
+ /// `{positional_ref: index}` — the `$N` form inside Hog blocks. Mirrors cpp's `PositionalRef` node.
+ fn positional_ref(&self, index: i64) -> Self::Value;
+
+ /// `Program(declarations)`.
+ fn program(&self, declarations: Vec<Self::Value>) -> Self::Value;
+ /// `Block(declarations)`.
+ fn block(&self, declarations: Vec<Self::Value>) -> Self::Value;
+ /// `ExprStatement(expr)`.
+ fn expr_statement(&self, expr: Self::Value) -> Self::Value;
+ /// `IfStatement(expr, then, else_)`.
+ fn if_statement(&self, cond: Self::Value, then: Self::Value, else_: Self::Value)
+ -> Self::Value;
+ /// `WhileStatement(expr, body)`.
+ fn while_statement(&self, cond: Self::Value, body: Self::Value) -> Self::Value;
+ /// `ForInStatement(keyVar, valueVar, expr, body)`.
+ fn for_in_statement(
+ &self,
+ key_var: Self::Value,
+ value_var: Self::Value,
+ expr: Self::Value,
+ body: Self::Value,
+ ) -> Self::Value;
+ /// `ForStatement(initializer, condition, increment, body)`.
+ fn for_statement(
+ &self,
+ initializer: Self::Value,
+ condition: Self::Value,
+ increment: Self::Value,
+ body: Self::Value,
+ ) -> Self::Value;
+ /// `Function(name, params, body)`.
+ fn function_(&self, name: &str, params: Vec<Self::Value>, body: Self::Value) -> Self::Value;
+ /// `VariableAssignment(left, right)`.
+ fn variable_assignment(&self, left: Self::Value, right: Self::Value) -> Self::Value;
+ /// `ReturnStatement(expr)`. `expr` may be null for `return;`.
+ fn return_statement(&self, expr: Self::Value) -> Self::Value;
+ /// `TryCatchStatement(try_stmt, catches, finally_stmt)`. Each catch is itself a `[var, type, body]` tuple — encoded as a list value.
+ fn try_catch_statement(
+ &self,
+ try_stmt: Self::Value,
+ catches: Vec<Self::Value>,
+ finally_stmt: Self::Value,
+ ) -> Self::Value;
+ /// `ThrowStatement(expr)`.
+ fn throw_statement(&self, expr: Self::Value) -> Self::Value;
+ /// `VariableDeclaration(name, expr)`.
+ fn variable_declaration(&self, name: &str, expr: Self::Value) -> Self::Value;
+ /// One element of a `try_catch` `catches` list: `[var, type, body]` — array of three values matching cpp's nlohmann::json shape.
+ fn catch_clause(&self, var: Self::Value, ty: Self::Value, body: Self::Value) -> Self::Value;
+
+ // ===== Query / clause builders =====
+ /// `CTE(name, expr, cte_type)`. `cte_type` is "column" / "subquery".
+ fn cte(&self, name: &str, expr: Self::Value, cte_type: &str) -> Self::Value;
+ /// Subquery CTE with optional columns/using_key/materialized flags.
+ fn cte_subquery(
+ &self,
+ name: &str,
+ expr: Self::Value,
+ columns: Option<Vec<String>>,
+ using_key: Option<Vec<String>>,
+ materialized: Option<bool>,
+ ) -> Self::Value;
+ /// `JoinConstraint(expr, constraint_type)`. constraint_type is "ON"/"USING".
+ fn join_constraint(&self, expr: Self::Value, constraint_type: &str) -> Self::Value;
+ /// `ValuesQuery(rows)`.
+ fn values_query(&self, rows: Vec<Self::Value>) -> Self::Value;
+ /// `PivotColumn(column, values)`.
+ fn pivot_column(&self, column: Self::Value, values: Vec<Self::Value>) -> Self::Value;
+ /// `UnpivotColumn(value_columns, name_columns, unpivot_values)`.
+ fn unpivot_column(
+ &self,
+ value_columns: Self::Value,
+ name_columns: Self::Value,
+ unpivot_values: Vec<Self::Value>,
+ ) -> Self::Value;
+ /// `GroupingSet(exprs)`.
+ fn grouping_set(&self, exprs: Vec<Self::Value>) -> Self::Value;
+ /// `HogQLXTag(kind, attributes)`.
+ fn hogqlx_tag(&self, kind: &str, attributes: Vec<Self::Value>) -> Self::Value;
+ /// `HogQLXAttribute(name, value)`.
+ fn hogqlx_attribute(&self, name: &str, value: Self::Value) -> Self::Value;
+ /// `SelectSetQuery(initial_select_query, subsequent_select_queries)`.
+ fn select_set_query(&self, initial: Self::Value, subsequent: Vec<Self::Value>) -> Self::Value;
+ /// Empty `WindowExpr` shell — caller adds fields via `set_field`.
+ fn window_expr_empty(&self) -> Self::Value;
+ /// `WindowFrameExpr(frame_type, frame_value)`. `frame_value` may be null (CURRENT ROW / UNBOUNDED forms) or a Constant / expr.
+ fn window_frame_bound(&self, frame_type: &str, frame_value: Self::Value) -> Self::Value;
+ /// `InterpolateExpr(expr, value?)`.
+ fn interpolate_expr(&self, expr: Self::Value, value: Option<Self::Value>) -> Self::Value;
+ /// `LimitByExpr(n, exprs, offset_value?)`.
+ fn limit_by_expr(
+ &self,
+ n: Self::Value,
+ exprs: Vec<Self::Value>,
+ offset_value: Option<Self::Value>,
+ ) -> Self::Value;
+ /// Empty `SelectQuery` shell — caller adds fields via `set_field`. Used by the SELECT-clause builder; surfacing every optional field as a constructor argument would balloon the trait method count.
+ fn select_query_empty(&self) -> Self::Value;
+ /// `SelectSetNode(select_query, set_operator)`. Used inside `SelectSetQuery.subsequent_select_queries`.
+ fn select_set_node(&self, select_query: Self::Value, set_operator: Option<&str>)
+ -> Self::Value;
+ /// `SampleExpr(sample_value, offset_value?)`.
+ fn sample_expr(
+ &self,
+ sample_value: Self::Value,
+ offset_value: Option<Self::Value>,
+ ) -> Self::Value;
+ /// `RatioExpr(left, right?)`.
+ fn ratio_expr(&self, left: Self::Value, right: Option<Self::Value>) -> Self::Value;
+ /// `PivotExpr(table, aggregates, columns, group_by?)`.
+ fn pivot_expr(
+ &self,
+ table: Self::Value,
+ aggregates: Vec<Self::Value>,
+ columns: Vec<Self::Value>,
+ group_by: Option<Vec<Self::Value>>,
+ ) -> Self::Value;
+ /// `UnpivotExpr(table, columns, include_nulls)`.
+ fn unpivot_expr(
+ &self,
+ table: Self::Value,
+ columns: Vec<Self::Value>,
+ include_nulls: bool,
+ ) -> Self::Value;
+ /// `JoinExpr(table, alias?, table_args?, column_aliases?, table_final?, sample?)`.
+ fn join_expr(
+ &self,
+ table: Self::Value,
+ alias: Option<String>,
+ table_args: Option<Self::Value>,
+ column_aliases: Option<Vec<String>>,
+ table_final: bool,
+ sample: Option<Self::Value>,
+ ) -> Self::Value;
+ /// `WindowFunction(name, exprs, args, over_expr, over_identifier)`. `over_expr` and `over_identifier` are alternatives — only one is set per node. `args` defaults to empty list (NOT None) so the deserialiser's `__eq__` distinguishes from non-window calls.
+ fn window_function(
+ &self,
+ name: &str,
+ exprs: Vec<Self::Value>,
+ args: Vec<Self::Value>,
+ over_expr: Option<Self::Value>,
+ over_identifier: Option<String>,
+ ) -> Self::Value;
+ /// `WithFillExpr(from_value?, to_value?, step_value?)`.
+ fn with_fill_expr(
+ &self,
+ from_value: Option<Self::Value>,
+ to_value: Option<Self::Value>,
+ step_value: Option<Self::Value>,
+ ) -> Self::Value;
+
+ // ===== Position machinery =====
+ /// `{line, column, offset}` per cpp's visitor — line is 1-based, column is 0-based, offset is the character position.
+ fn position(&self, line: u32, column: u32, offset: usize) -> Self::Value;
+ /// Inject `start` / `end` position objects. Idempotent: if `start` is already set (or explicitly null-poisoned by `no_pos`), existing values are kept — this is how cpp's paren wrap `(expr)` preserves the inner expression's positions.
+ fn with_pos(&self, value: Self::Value, start: Self::Value, end: Self::Value) -> Self::Value;
+ /// Mark a node as position-less so downstream `with_pos` calls leave it bare. Mirrors cpp visitors that emit a node without `addPositionInfo(json, ctx)` — Python AST shows dataclass defaults (None). Example: `NamedArgument`.
+ fn no_pos(&self, value: Self::Value) -> Self::Value;
+ /// Override existing `start` / `end` keys, unlike the idempotent `with_pos`. Used when the outer span needs to include tokens the inner expression's wrap didn't see.
+ fn replace_pos(&self, value: Self::Value, start: Self::Value, end: Self::Value) -> Self::Value;
+
+ // ===== Inspection =====
+ /// Get the AST node kind ("Constant", "ArithmeticOperation", …) or `None` for non-node values (primitives, lists, positions).
+ fn node_kind<'a>(&self, v: &'a Self::Value) -> Option<Cow<'a, str>>;
+ /// Get a named field value. Returns `None` if the field is missing or the value isn't a node. Returned value is owned (cloned).
+ fn get_field(&self, v: &Self::Value, name: &str) -> Option<Self::Value>;
+ /// True if the field is present at all (even if its value is null). Distinguishes "field not set" from "field explicitly null" — the `no_pos` + `with_pos` idempotency relies on this.
+ fn has_field(&self, v: &Self::Value, name: &str) -> bool;
+ /// `Value::is_null` analogue.
+ fn is_null(&self, v: &Self::Value) -> bool;
+ /// Extract a string body if `v` is a string value.
+ fn as_str<'a>(&self, v: &'a Self::Value) -> Option<Cow<'a, str>>;
+ /// Extract the list elements if `v` is a list/array value.
+ fn as_list(&self, v: &Self::Value) -> Option<Vec<Self::Value>>;
+ /// Extract a boolean if `v` is a boolean value.
+ fn as_bool(&self, v: &Self::Value) -> Option<bool>;
+ /// Extract an `i64` if `v` is an integer value.
+ fn as_i64(&self, v: &Self::Value) -> Option<i64>;
+
+ // ===== Mutation =====
+ /// Remove a named field from a node, returning the previous value (or None when absent). Used to drop sentinel keys before the node leaves the parser, e.g. `__rust_offset_liftable`.
+ fn remove_field(&self, v: &mut Self::Value, name: &str) -> Option<Self::Value>;
+ /// Set / overwrite a named field on a node. Used by AST-surgery sites that copy a node and tweak one field — primarily BETWEEN-split recursion, merge-select-decorators, and CTE injection. JSON inserts into the underlying `Map`; Py calls `obj.setattr(name, value)`.
+ fn set_field(&self, v: &mut Self::Value, name: &str, value: Self::Value);
+}
+
+// ============================================================================
+// JsonEmitter — `serde_json::Value` impl, mirrors the previous free `emit::xxx` functions. Used by `parse_*_json` entry points and the future WASM build.
+// ============================================================================
+
+#[derive(Default, Clone, Copy)]
+pub struct JsonEmitter;
+
+impl Emitter for JsonEmitter {
+ type Value = Value;
+
+ fn null(&self) -> Value {
+ Value::Null
}
-}
-
-pub fn alias(expr: Value, name: &str) -> Value {
- json!({"node": "Alias", "expr": expr, "alias": name})
-}
-
-/// Synthetic `Call` — ternary `?:` (→ `if`), `||` (→ `concat`), `??` (→
-/// `ifNull`), and other rewrites. The C++ visitor emits these without the
-/// four extra fields (`distinct`, `filter_expr`, `order_by`, `params`),
-/// which dataclass defaults absorb on the Python side.
-pub fn call(name: &str, args: Vec<Value>) -> Value {
- json!({"node": "Call", "name": name, "args": args})
-}
-
-/// Function call carrying every optional shape the grammar's
-/// `ColumnExprFunction` can produce: parametric `name(params)(args)`,
-/// `DISTINCT`, in-arg `ORDER BY`, and trailing `FILTER (WHERE …)`.
-/// Each None / empty field is omitted; the Python dataclass picks up its
-/// default (None / False / empty) on deserialise.
-#[allow(clippy::too_many_arguments)]
-pub fn call_full(
- name: &str,
- params: Option<Vec<Value>>,
- args: Vec<Value>,
- distinct: bool,
- order_by: Option<Vec<Value>>,
- filter_expr: Option<Value>,
- within_group: Option<Vec<Value>>,
-) -> Value {
- let mut obj = serde_json::Map::new();
- obj.insert("node".into(), Value::String("Call".into()));
- obj.insert("name".into(), Value::String(name.into()));
- obj.insert("args".into(), Value::Array(args));
- if let Some(p) = params {
- obj.insert("params".into(), Value::Array(p));
- }
- if distinct {
- obj.insert("distinct".into(), Value::Bool(true));
- }
- if let Some(ob) = order_by {
- obj.insert("order_by".into(), Value::Array(ob));
- }
- if let Some(fe) = filter_expr {
- obj.insert("filter_expr".into(), fe);
- }
- if let Some(wg) = within_group {
- obj.insert("within_group".into(), Value::Array(wg));
- }
- Value::Object(obj)
-}
-
-pub fn lambda(args: Vec<String>, expr: Value) -> Value {
- let args_json: Vec<Value> = args.into_iter().map(Value::String).collect();
- json!({"node": "Lambda", "args": args_json, "expr": expr})
-}
-
-pub fn type_cast(expr: Value, type_name: &str) -> Value {
- json!({"node": "TypeCast", "expr": expr, "type_name": type_name})
-}
-
-pub fn try_cast(expr: Value, type_name: &str) -> Value {
- json!({"node": "TryCast", "expr": expr, "type_name": type_name})
-}
-
-pub fn array_slice(array: Value, start: Option<Value>, end: Option<Value>) -> Value {
- let mut obj = serde_json::Map::new();
- obj.insert("node".into(), Value::String("ArraySlice".into()));
- obj.insert("array".into(), array);
- if let Some(s) = start {
- obj.insert("start_expr".into(), s);
+ fn bool(&self, v: bool) -> Value {
+ Value::Bool(v)
}
- if let Some(e) = end {
- obj.insert("end_expr".into(), e);
+ fn int(&self, v: i64) -> Value {
+ Value::Number(v.into())
+ }
+ fn string(&self, v: &str) -> Value {
+ Value::String(v.into())
+ }
+ fn float(&self, v: f64) -> Value {
+ serde_json::Number::from_f64(v)
+ .map(Value::Number)
+ .unwrap_or(Value::Null)
+ }
+ fn uint(&self, v: u64) -> Value {
+ Value::Number(v.into())
+ }
+ fn list_value(&self, items: Vec<Value>) -> Value {
+ Value::Array(items)
+ }
+ fn string_keyed_map(&self, pairs: Vec<(String, Value)>) -> Value {
+ let mut obj = serde_json::Map::new();
+ for (k, v) in pairs {
+ obj.insert(k, v);
+ }
+ Value::Object(obj)
}
- Value::Object(obj)
-}
-
-pub fn dict_(items: Vec<(Value, Value)>) -> Value {
- let items_json: Vec<Value> = items
- .into_iter()
- .map(|(k, v)| Value::Array(vec![k, v]))
- .collect();
- json!({"node": "Dict", "items": items_json})
-}
-
-pub fn placeholder(expr: Value) -> Value {
- json!({"node": "Placeholder", "expr": expr})
-}
-
-pub fn named_argument(name: &str, value: Value) -> Value {
- // cpp's `ColumnExprNamedArg` visitor omits `addPositionInfo`, so
- // NamedArgument is always position-less. `no_pos` reserves the
- // `start`/`end` keys so the outer pratt-loop wrap leaves it bare.
- no_pos(json!({"node": "NamedArgument", "name": name, "value": value}))
-}
-
-pub fn ignore_nulls(expr: Value) -> Value {
- // `e IGNORE NULLS` is dropped by the C++ visitor — the expression
- // returns as-is. Kept as a named helper to make the call site readable
- // and to leave room for richer behaviour later.
- expr
-}
-
-pub fn order_expr(expr: Value, order: &str, with_fill: Option<Value>) -> Value {
- let mut obj = serde_json::Map::new();
- obj.insert("node".into(), Value::String("OrderExpr".into()));
- obj.insert("expr".into(), expr);
- obj.insert("order".into(), Value::String(order.into()));
- if let Some(wf) = with_fill {
- obj.insert("with_fill".into(), wf);
- }
- Value::Object(obj)
-}
-
-/// `ColumnsExpr` covering the COLUMNS('regex') / COLUMNS(expr,...) /
-/// (*|TABLE.*) EXCLUDE (...) REPLACE (...) family. Every field is optional;
-/// the Python dataclass defaults None/False fill in.
-pub fn columns_expr(
- regex: Option<String>,
- columns: Option<Vec<Value>>,
- all_columns: bool,
- exclude: Option<Vec<String>>,
- replace: Option<Vec<(String, Value)>>,
-) -> Value {
- let mut obj = serde_json::Map::new();
- obj.insert("node".into(), Value::String("ColumnsExpr".into()));
- if let Some(r) = regex {
- obj.insert("regex".into(), Value::String(r));
- }
- if let Some(c) = columns {
- obj.insert("columns".into(), Value::Array(c));
- }
- if all_columns {
- obj.insert("all_columns".into(), Value::Bool(true));
- }
- if let Some(e) = exclude {
- obj.insert(
- "exclude".into(),
- Value::Array(e.into_iter().map(Value::String).collect()),
- );
- }
- if let Some(r) = replace {
- // C++ emits `replace` as an object keyed by name -> Expr.
- let mut m = serde_json::Map::new();
- for (k, v) in r {
- m.insert(k, v);
- }
- obj.insert("replace".into(), Value::Object(m));
- }
- Value::Object(obj)
-}
-pub fn spread_expr(expr: Value) -> Value {
- json!({"node": "SpreadExpr", "expr": expr})
-}
+ fn constant(&self, value: Value) -> Value {
+ json!({"node": "Constant", "value": value})
+ }
+ fn constant_special_number(&self, name: &'static str) -> Value {
+ json!({"node": "Constant", "value": name, "value_type": "number"})
+ }
+ fn constant_number_string(&self, text: String) -> Value {
+ json!({"node": "Constant", "value": text, "value_type": "number"})
+ }
+ fn field(&self, chain: Vec<Value>) -> Value {
+ json!({"node": "Field", "chain": chain})
+ }
+ fn arith(&self, left: Value, op: &str, right: Value) -> Value {
+ json!({"node": "ArithmeticOperation", "left": left, "right": right, "op": op})
+ }
+ fn compare(&self, left: Value, op: &str, right: Value) -> Value {
+ json!({"node": "CompareOperation", "left": left, "right": right, "op": op})
+ }
+ fn compare_is_null(&self, left: Value, negated: bool) -> Value {
+ json!({
+ "node": "CompareOperation",
+ "left": left,
+ "right": json!({"node": "Constant", "value": Value::Null}),
+ "op": if negated { "!=" } else { "==" },
+ "is_null_comparison_style": true,
+ })
+ }
+ fn is_distinct_from(&self, left: Value, right: Value, negated: bool) -> Value {
+ json!({"node": "IsDistinctFrom", "left": left, "right": right, "negated": negated})
+ }
+ fn between(&self, expr: Value, low: Value, high: Value, negated: bool) -> Value {
+ json!({"node": "BetweenExpr", "expr": expr, "low": low, "high": high, "negated": negated})
+ }
+ fn not_(&self, expr: Value) -> Value {
+ json!({"node": "Not", "expr": expr})
+ }
+ fn and_(&self, exprs: Vec<Value>) -> Value {
+ json!({"node": "And", "exprs": exprs})
+ }
+ fn or_(&self, exprs: Vec<Value>) -> Value {
+ json!({"node": "Or", "exprs": exprs})
+ }
+ fn tuple_(&self, exprs: Vec<Value>) -> Value {
+ json!({"node": "Tuple", "exprs": exprs})
+ }
+ fn array_(&self, exprs: Vec<Value>) -> Value {
+ json!({"node": "Array", "exprs": exprs})
+ }
+ fn array_access(&self, array: Value, property: Value, nullish: bool) -> Value {
+ if nullish {
+ json!({"node": "ArrayAccess", "array": array, "property": property, "nullish": true})
+ } else {
+ json!({"node": "ArrayAccess", "array": array, "property": property})
+ }
+ }
+ fn tuple_access(&self, tuple_: Value, index: i64, nullish: bool) -> Value {
+ if nullish {
+ json!({"node": "TupleAccess", "tuple": tuple_, "index": index, "nullish": true})
+ } else {
+ json!({"node": "TupleAccess", "tuple": tuple_, "index": index})
+ }
+ }
+ fn alias(&self, expr: Value, name: &str) -> Value {
+ json!({"node": "Alias", "expr": expr, "alias": name})
+ }
+ fn call(&self, name: &str, args: Vec<Value>) -> Value {
+ json!({"node": "Call", "name": name, "args": args})
+ }
+ fn call_full(
+ &self,
+ name: &str,
+ params: Option<Vec<Value>>,
+ args: Vec<Value>,
+ distinct: bool,
+ order_by: Option<Vec<Value>>,
+ filter_expr: Option<Value>,
+ within_group: Option<Vec<Value>>,
+ ) -> Value {
+ let mut obj = serde_json::Map::new();
+ obj.insert("node".into(), Value::String("Call".into()));
+ obj.insert("name".into(), Value::String(name.into()));
+ obj.insert("args".into(), Value::Array(args));
+ if let Some(p) = params {
+ obj.insert("params".into(), Value::Array(p));
+ }
+ if distinct {
+ obj.insert("distinct".into(), Value::Bool(true));
+ }
+ if let Some(ob) = order_by {
+ obj.insert("order_by".into(), Value::Array(ob));
+ }
+ if let Some(fe) = filter_expr {
+ obj.insert("filter_expr".into(), fe);
+ }
+ if let Some(wg) = within_group {
+ obj.insert("within_group".into(), Value::Array(wg));
+ }
+ Value::Object(obj)
+ }
+ fn lambda(&self, args: Vec<String>, expr: Value) -> Value {
+ let args_json: Vec<Value> = args.into_iter().map(Value::String).collect();
+ json!({"node": "Lambda", "args": args_json, "expr": expr})
+ }
+ fn expr_call(&self, expr: Value, args: Vec<Value>) -> Value {
+ json!({"node": "ExprCall", "expr": expr, "args": args})
+ }
+ fn type_cast(&self, expr: Value, type_name: &str) -> Value {
+ json!({"node": "TypeCast", "expr": expr, "type_name": type_name})
+ }
+ fn try_cast(&self, expr: Value, type_name: &str) -> Value {
+ json!({"node": "TryCast", "expr": expr, "type_name": type_name})
+ }
+ fn array_slice(&self, array: Value, start: Option<Value>, end: Option<Value>) -> Value {
+ let mut obj = serde_json::Map::new();
+ obj.insert("node".into(), Value::String("ArraySlice".into()));
+ obj.insert("array".into(), array);
+ if let Some(s) = start {
+ obj.insert("start_expr".into(), s);
+ }
+ if let Some(e) = end {
+ obj.insert("end_expr".into(), e);
+ }
+ Value::Object(obj)
+ }
+ fn dict_(&self, items: Vec<(Value, Value)>) -> Value {
+ let items_json: Vec<Value> = items
+ .into_iter()
+ .map(|(k, v)| Value::Array(vec![k, v]))
+ .collect();
+ json!({"node": "Dict", "items": items_json})
+ }
+ fn placeholder(&self, expr: Value) -> Value {
+ json!({"node": "Placeholder", "expr": expr})
+ }
+ fn named_argument(&self, name: &str, value: Value) -> Value {
+ self.no_pos(json!({"node": "NamedArgument", "name": name, "value": value}))
+ }
+ fn order_expr(&self, expr: Value, order: &str, with_fill: Option<Value>) -> Value {
+ let mut obj = serde_json::Map::new();
+ obj.insert("node".into(), Value::String("OrderExpr".into()));
+ obj.insert("expr".into(), expr);
+ obj.insert("order".into(), Value::String(order.into()));
+ if let Some(wf) = with_fill {
+ obj.insert("with_fill".into(), wf);
+ }
+ Value::Object(obj)
+ }
+ fn columns_expr(
+ &self,
+ regex: Option<String>,
+ columns: Option<Vec<Value>>,
+ all_columns: bool,
+ exclude: Option<Vec<String>>,
+ replace: Option<Vec<(String, Value)>>,
+ ) -> Value {
+ let mut obj = serde_json::Map::new();
+ obj.insert("node".into(), Value::String("ColumnsExpr".into()));
+ if let Some(r) = regex {
+ obj.insert("regex".into(), Value::String(r));
+ }
+ if let Some(c) = columns {
+ obj.insert("columns".into(), Value::Array(c));
+ }
+ if all_columns {
+ obj.insert("all_columns".into(), Value::Bool(true));
+ }
+ if let Some(e) = exclude {
+ obj.insert(
+ "exclude".into(),
+ Value::Array(e.into_iter().map(Value::String).collect()),
+ );
+ }
+ if let Some(r) = replace {
+ let mut m = serde_json::Map::new();
+ for (k, v) in r {
+ m.insert(k, v);
+ }
+ obj.insert("replace".into(), Value::Object(m));
+ }
+ Value::Object(obj)
+ }
+ fn spread_expr(&self, expr: Value) -> Value {
+ json!({"node": "SpreadExpr", "expr": expr})
+ }
+ fn positional_ref(&self, index: i64) -> Value {
+ json!({"node": "PositionalRef", "index": index})
+ }
-/// `{line, column, offset}` per cpp's visitor — line is 1-based, column is
-/// 0-based, offset is the byte position in the source. `LineColMap` builds
-/// the line-start index once per parse for O(log N) offset → (line, col).
-pub fn position(line: u32, column: u32, offset: usize) -> Value {
- json!({"line": line, "column": column, "offset": offset})
-}
+ fn program(&self, declarations: Vec<Value>) -> Value {
+ json!({"node": "Program", "declarations": declarations})
+ }
+ fn block(&self, declarations: Vec<Value>) -> Value {
+ json!({"node": "Block", "declarations": declarations})
+ }
+ fn expr_statement(&self, expr: Value) -> Value {
+ json!({"node": "ExprStatement", "expr": expr})
+ }
+ fn if_statement(&self, cond: Value, then: Value, else_: Value) -> Value {
+ json!({"node": "IfStatement", "expr": cond, "then": then, "else_": else_})
+ }
+ fn while_statement(&self, cond: Value, body: Value) -> Value {
+ json!({"node": "WhileStatement", "expr": cond, "body": body})
+ }
+ fn for_in_statement(
+ &self,
+ key_var: Value,
+ value_var: Value,
+ expr: Value,
+ body: Value,
+ ) -> Value {
+ json!({
+ "node": "ForInStatement",
+ "keyVar": key_var,
+ "valueVar": value_var,
+ "expr": expr,
+ "body": body,
+ })
+ }
+ fn for_statement(
+ &self,
+ initializer: Value,
+ condition: Value,
+ increment: Value,
+ body: Value,
+ ) -> Value {
+ json!({
+ "node": "ForStatement",
+ "initializer": initializer,
+ "condition": condition,
+ "increment": increment,
+ "body": body,
+ })
+ }
+ fn function_(&self, name: &str, params: Vec<Value>, body: Value) -> Value {
+ json!({"node": "Function", "name": name, "params": params, "body": body})
+ }
+ fn variable_assignment(&self, left: Value, right: Value) -> Value {
+ json!({"node": "VariableAssignment", "left": left, "right": right})
+ }
+ fn return_statement(&self, expr: Value) -> Value {
+ let mut obj = serde_json::Map::new();
+ obj.insert("node".into(), Value::String("ReturnStatement".into()));
+ obj.insert("expr".into(), expr);
+ Value::Object(obj)
+ }
+ fn try_catch_statement(
+ &self,
+ try_stmt: Value,
+ catches: Vec<Value>,
+ finally_stmt: Value,
+ ) -> Value {
+ json!({
+ "node": "TryCatchStatement",
+ "try_stmt": try_stmt,
+ "catches": catches,
+ "finally_stmt": finally_stmt,
+ })
+ }
+ fn throw_statement(&self, expr: Value) -> Value {
+ json!({"node": "ThrowStatement", "expr": expr})
+ }
+ fn variable_declaration(&self, name: &str, expr: Value) -> Value {
+ json!({"node": "VariableDeclaration", "name": name, "expr": expr})
+ }
+ fn catch_clause(&self, var: Value, ty: Value, body: Value) -> Value {
+ json!([var, ty, body])
+ }
+ fn cte(&self, name: &str, expr: Value, cte_type: &str) -> Value {
+ json!({"node": "CTE", "name": name, "expr": expr, "cte_type": cte_type})
+ }
+ fn cte_subquery(
+ &self,
+ name: &str,
+ expr: Value,
+ columns: Option<Vec<String>>,
+ using_key: Option<Vec<String>>,
+ materialized: Option<bool>,
+ ) -> Value {
+ let mut obj = serde_json::Map::new();
+ obj.insert("node".into(), Value::String("CTE".into()));
+ obj.insert("name".into(), Value::String(name.into()));
+ obj.insert("expr".into(), expr);
+ obj.insert("cte_type".into(), Value::String("subquery".into()));
+ if let Some(c) = columns {
+ obj.insert(
+ "columns".into(),
+ Value::Array(c.into_iter().map(Value::String).collect()),
+ );
+ }
+ if let Some(uk) = using_key {
+ obj.insert(
+ "using_key".into(),
+ Value::Array(uk.into_iter().map(Value::String).collect()),
+ );
+ }
+ if let Some(m) = materialized {
+ obj.insert("materialized".into(), Value::Bool(m));
+ }
+ Value::Object(obj)
+ }
+ fn join_constraint(&self, expr: Value, constraint_type: &str) -> Value {
+ json!({"node": "JoinConstraint", "expr": expr, "constraint_type": constraint_type})
+ }
+ fn values_query(&self, rows: Vec<Value>) -> Value {
+ json!({"node": "ValuesQuery", "rows": rows})
+ }
+ fn pivot_column(&self, column: Value, values: Vec<Value>) -> Value {
+ json!({"node": "PivotColumn", "column": column, "values": values})
+ }
+ fn unpivot_column(
+ &self,
+ value_columns: Value,
+ name_columns: Value,
+ unpivot_values: Vec<Value>,
+ ) -> Value {
+ json!({
+ "node": "UnpivotColumn",
+ "value_columns": value_columns,
+ "name_columns": name_columns,
+ "unpivot_values": unpivot_values,
+ })
+ }
+ fn grouping_set(&self, exprs: Vec<Value>) -> Value {
+ json!({"node": "GroupingSet", "exprs": exprs})
+ }
+ fn hogqlx_tag(&self, kind: &str, attributes: Vec<Value>) -> Value {
+ json!({"node": "HogQLXTag", "kind": kind, "attributes": attributes})
+ }
+ fn hogqlx_attribute(&self, name: &str, value: Value) -> Value {
+ json!({"node": "HogQLXAttribute", "name": name, "value": value})
+ }
+ fn window_function(
+ &self,
+ name: &str,
+ exprs: Vec<Value>,
+ args: Vec<Value>,
+ over_expr: Option<Value>,
+ over_identifier: Option<String>,
+ ) -> Value {
+ let mut obj = serde_json::Map::new();
+ obj.insert("node".into(), Value::String("WindowFunction".into()));
+ obj.insert("name".into(), Value::String(name.into()));
+ obj.insert("exprs".into(), Value::Array(exprs));
+ obj.insert("args".into(), Value::Array(args));
+ if let Some(we) = over_expr {
+ obj.insert("over_expr".into(), we);
+ }
+ if let Some(id) = over_identifier {
+ obj.insert("over_identifier".into(), Value::String(id));
+ }
+ Value::Object(obj)
+ }
+ fn with_fill_expr(
+ &self,
+ from_value: Option<Value>,
+ to_value: Option<Value>,
+ step_value: Option<Value>,
+ ) -> Value {
+ let mut obj = serde_json::Map::new();
+ obj.insert("node".into(), Value::String("WithFillExpr".into()));
+ if let Some(v) = from_value {
+ obj.insert("from_value".into(), v);
+ }
+ if let Some(v) = to_value {
+ obj.insert("to_value".into(), v);
+ }
+ if let Some(v) = step_value {
+ obj.insert("step_value".into(), v);
+ }
+ Value::Object(obj)
+ }
+ fn sample_expr(&self, sample_value: Value, offset_value: Option<Value>) -> Value {
+ let mut obj = serde_json::Map::new();
+ obj.insert("node".into(), Value::String("SampleExpr".into()));
+ obj.insert("sample_value".into(), sample_value);
+ if let Some(o) = offset_value {
+ obj.insert("offset_value".into(), o);
+ }
+ Value::Object(obj)
+ }
+ fn ratio_expr(&self, left: Value, right: Option<Value>) -> Value {
+ let mut obj = serde_json::Map::new();
+ obj.insert("node".into(), Value::String("RatioExpr".into()));
+ obj.insert("left".into(), left);
+ if let Some(r) = right {
+ obj.insert("right".into(), r);
+ }
+ Value::Object(obj)
+ }
+ fn pivot_expr(
+ &self,
+ table: Value,
+ aggregates: Vec<Value>,
+ columns: Vec<Value>,
+ group_by: Option<Vec<Value>>,
+ ) -> Value {
+ let mut obj = serde_json::Map::new();
+ obj.insert("node".into(), Value::String("PivotExpr".into()));
+ obj.insert("table".into(), table);
+ obj.insert("aggregates".into(), Value::Array(aggregates));
+ obj.insert("columns".into(), Value::Array(columns));
+ if let Some(g) = group_by {
+ obj.insert("group_by".into(), Value::Array(g));
+ }
+ Value::Object(obj)
+ }
+ fn unpivot_expr(&self, table: Value, columns: Vec<Value>, include_nulls: bool) -> Value {
+ let mut obj = serde_json::Map::new();
+ obj.insert("node".into(), Value::String("UnpivotExpr".into()));
+ obj.insert("table".into(), table);
+ obj.insert("columns".into(), Value::Array(columns));
+ obj.insert("include_nulls".into(), Value::Bool(include_nulls));
+ Value::Object(obj)
+ }
+ fn join_expr(
+ &self,
+ table: Value,
+ alias: Option<String>,
+ table_args: Option<Value>,
+ column_aliases: Option<Vec<String>>,
+ table_final: bool,
+ sample: Option<Value>,
+ ) -> Value {
+ let mut obj = serde_json::Map::new();
+ obj.insert("node".into(), Value::String("JoinExpr".into()));
+ obj.insert("table".into(), table);
+ if let Some(ta) = table_args {
+ obj.insert("table_args".into(), ta);
+ }
+ if let Some(a) = alias {
+ obj.insert("alias".into(), Value::String(a));
+ }
+ if table_final {
+ obj.insert("table_final".into(), Value::Bool(true));
+ }
+ if let Some(s) = sample {
+ obj.insert("sample".into(), s);
+ }
+ if let Some(ca) = column_aliases {
+ obj.insert(
+ "column_aliases".into(),
+ Value::Array(ca.into_iter().map(Value::String).collect()),
+ );
+ }
+ Value::Object(obj)
+ }
+ fn select_set_query(&self, initial: Value, subsequent: Vec<Value>) -> Value {
+ json!({
+ "node": "SelectSetQuery",
+ "initial_select_query": initial,
+ "subsequent_select_queries": subsequent,
+ })
+ }
+ fn window_expr_empty(&self) -> Value {
+ json!({"node": "WindowExpr"})
+ }
+ fn window_frame_bound(&self, frame_type: &str, frame_value: Value) -> Value {
+ json!({"node": "WindowFrameExpr", "frame_type": frame_type, "frame_value": frame_value})
+ }
+ fn interpolate_expr(&self, expr: Value, value: Option<Value>) -> Value {
+ let mut obj = serde_json::Map::new();
+ obj.insert("node".into(), Value::String("InterpolateExpr".into()));
+ obj.insert("expr".into(), expr);
+ if let Some(v) = value {
+ obj.insert("value".into(), v);
+ }
+ Value::Object(obj)
+ }
+ fn limit_by_expr(&self, n: Value, exprs: Vec<Value>, offset_value: Option<Value>) -> Value {
+ let mut obj = serde_json::Map::new();
+ obj.insert("node".into(), Value::String("LimitByExpr".into()));
+ obj.insert("n".into(), n);
+ obj.insert("exprs".into(), Value::Array(exprs));
+ if let Some(o) = offset_value {
+ obj.insert("offset_value".into(), o);
+ }
+ Value::Object(obj)
+ }
+ fn select_query_empty(&self) -> Value {
+ json!({"node": "SelectQuery"})
+ }
+ fn select_set_node(&self, select_query: Value, set_operator: Option<&str>) -> Value {
+ let mut obj = serde_json::Map::new();
+ obj.insert("node".into(), Value::String("SelectSetNode".into()));
+ obj.insert("select_query".into(), select_query);
+ if let Some(op) = set_operator {
+ obj.insert("set_operator".into(), Value::String(op.into()));
+ }
+ Value::Object(obj)
+ }
-/// Inject `start` / `end` position objects on an emitted AST node. Mirrors
-/// the cpp visitor's per-node span emission. Idempotent: if `start` is
-/// already present, leave both keys untouched — this is how cpp's paren
-/// wrap (`(expr)`) keeps the inner expression's positions instead of
-/// overwriting with the outer parens span.
-pub fn with_pos(mut value: Value, start: Value, end: Value) -> Value {
- if let Some(obj) = value.as_object_mut() {
- if !obj.contains_key("start") {
+ fn position(&self, line: u32, column: u32, offset: usize) -> Value {
+ json!({"line": line, "column": column, "offset": offset})
+ }
+ fn with_pos(&self, mut value: Value, start: Value, end: Value) -> Value {
+ if let Some(obj) = value.as_object_mut() {
+ if !obj.contains_key("start") {
+ obj.insert("start".into(), start);
+ obj.insert("end".into(), end);
+ }
+ }
+ value
+ }
+ fn no_pos(&self, mut value: Value) -> Value {
+ if let Some(obj) = value.as_object_mut() {
+ obj.insert("start".into(), Value::Null);
+ obj.insert("end".into(), Value::Null);
+ }
+ value
+ }
+ fn replace_pos(&self, mut value: Value, start: Value, end: Value) -> Value {
+ if let Some(obj) = value.as_object_mut() {
obj.insert("start".into(), start);
obj.insert("end".into(), end);
}
+ value
}
- value
-}
-
-/// Mark a node as position-less so that downstream `with_pos` calls leave
-/// it bare. Pre-inserts explicit `null` `start` / `end` keys, which `with_pos`
-/// treats the same as "already positioned" via its `contains_key` check.
-/// Mirrors cpp visitors that emit a node without `addPositionInfo(json, ctx)` —
-/// the cpp `Json` then never gets `start` / `end` and the Python AST shows
-/// the dataclass defaults (`None`). Examples: `ColumnExprNamedArg` (NamedArgument).
-pub fn no_pos(mut value: Value) -> Value {
- if let Some(obj) = value.as_object_mut() {
- obj.insert("start".into(), Value::Null);
- obj.insert("end".into(), Value::Null);
- }
- value
-}
-/// Override existing `start` / `end` keys with new positions, unlike the
-/// idempotent `with_pos`. Used by call sites that know the outer span
-/// must include tokens the inner expression's wrap did not see — e.g.
-/// the `LPAREN ASTERISK REPLACE(...) RPAREN` ColumnsExpr alt where the
-/// inner ColumnsExpr was wrapped at the `*` position but cpp's
-/// grammar-rule ctx includes the outer parens too.
-pub fn replace_pos(mut value: Value, start: Value, end: Value) -> Value {
- if let Some(obj) = value.as_object_mut() {
- obj.insert("start".into(), start);
- obj.insert("end".into(), end);
- }
- value
-}
-
-trait ConstantExt {
- fn tagged_constant(self) -> Value;
-}
-
-impl ConstantExt for Value {
- fn tagged_constant(self) -> Value {
- json!({"node": "Constant", "value": self})
+ fn node_kind<'a>(&self, v: &'a Value) -> Option<Cow<'a, str>> {
+ v.get("node").and_then(Value::as_str).map(Cow::Borrowed)
+ }
+ fn get_field(&self, v: &Value, name: &str) -> Option<Value> {
+ v.get(name).cloned()
+ }
+ fn has_field(&self, v: &Value, name: &str) -> bool {
+ v.as_object().is_some_and(|m| m.contains_key(name))
+ }
+ fn is_null(&self, v: &Value) -> bool {
+ v.is_null()
+ }
+ fn as_str<'a>(&self, v: &'a Value) -> Option<Cow<'a, str>> {
+ v.as_str().map(Cow::Borrowed)
+ }
+ fn as_list(&self, v: &Value) -> Option<Vec<Value>> {
+ v.as_array().cloned()
+ }
+ fn as_bool(&self, v: &Value) -> Option<bool> {
+ v.as_bool()
+ }
+ fn as_i64(&self, v: &Value) -> Option<i64> {
+ v.as_i64()
+ }
+ fn remove_field(&self, v: &mut Value, name: &str) -> Option<Value> {
+ v.as_object_mut().and_then(|obj| obj.remove(name))
+ }
+ fn set_field(&self, v: &mut Value, name: &str, value: Value) {
+ if let Some(obj) = v.as_object_mut() {
+ obj.insert(name.into(), value);
+ }
}
}
diff --git a/rust/hogql/parser/src/emit_py.rs b/rust/hogql/parser/src/emit_py.rs
new file mode 100644
index 000000000000..7fee1a68e465
--- /dev/null
+++ b/rust/hogql/parser/src/emit_py.rs
@@ -0,0 +1,1241 @@
+//! `PyEmitter` — `Emitter` impl that constructs `posthog.hogql.ast` dataclasses directly during parsing, bypassing the `serde_json::Value` intermediate tree.
+//!
+//! Used by the `parse_*_py` PyO3 entry points in [`crate::lib`]. The `parse_*_json` entry points stay on `JsonEmitter` for the future WASM build (no CPython link) and for tests that compare on JSON shape.
+//!
+//! Construction strategy:
+//! - All `posthog.hogql.ast` classes are looked up *once* at [`PyEmitter::new`] and stored as `Bound<'py, PyAny>` references — a `getattr(ast_module, "Constant")` per node would dominate runtime over the json round-trip we're trying to beat.
+//! - Each emitter method builds a `PyDict` of kwargs and calls `class.call((), Some(&kwargs))`. The constructed object is wrapped in [`PyAst`] (which also tracks `positions_locked` for idempotent `with_pos` / `no_pos` semantics).
+//!
+//! Position handling:
+//! - `position()` returns a plain `PyInt` (the offset). Lines/columns aren't used by the Python side — `AST.start` / `AST.end` are `Optional[int]`. Mirrors the post-walk extraction done by `pyobject::Converter` on the `*_json` path.
+//! - `with_pos` / `no_pos` / `replace_pos` mirror cpp's idempotent semantics:
+//! * `with_pos(v, start, end)`: set `v.start = start, v.end = end` only if `v.start` is currently `None` AND `positions_locked` isn't set.
+//! * `no_pos(v)`: marks the wrapper with `positions_locked = true`. The underlying object's `start` / `end` stay at dataclass defaults (`None`).
+//! * `replace_pos(v, start, end)`: unconditionally writes (subject to `positions_locked`). Used for outer-span overrides.
+
+use pyo3::prelude::*;
+use pyo3::types::{PyDict, PyList, PyTuple};
+use std::borrow::Cow;
+use std::collections::HashMap;
+
+use crate::emit::Emitter;
+
+// ============================================================================
+// PyAst — AST value wrapper.
+// ============================================================================
+
+/// Wrapper around a Python AST object plus the out-of-band `positions_locked` flag. The underlying `posthog.hogql.ast.*` dataclasses use `slots=True` so they can't carry an arbitrary "positions locked" attribute; the wrapper carries it instead.
+///
+/// `obj` is unbound (`Py<PyAny>`, no GIL lifetime) so the wrapper can live alongside `Parser` without dragging a 'py through the parser's type signatures. Re-attach via `obj.bind(py)` inside emitter methods where `py: Python<'_>` is available.
+pub struct PyAst {
+ pub obj: Py<PyAny>,
+ pub positions_locked: bool,
+ /// Side-channel for parser-internal `__rust_*` sentinel keys — the JSON path stores these on the underlying `Value::Object` Map, but slots=True dataclasses reject setattr for unknown attrs, so PyEmitter routes them here.
+ /// `Option<Box<HashMap>>` over inline HashMap keeps PyAst at 24 bytes instead of ~64 (HashMap is ~48 bytes inline) — >99% of nodes never carry a sentinel, so the Box is null. Clippy's `box_collection` lint flags this as wasteful (HashMap is already heap-allocated) but it doesn't account for the niche-optimized `Option<Box>` size advantage at the PyAst struct level, where we allocate millions per parse. Lazy-init via `sentinels_mut()`.
+ #[allow(clippy::box_collection)]
+ pub rust_sentinels: Option<Box<HashMap<String, Py<PyAny>>>>,
+}
+
+impl PyAst {
+ /// Lazy accessor for the sentinel map — allocates the inner box on first access. Used by the rare `set_field` site routing a `__rust_*` sentinel.
+ fn sentinels_mut(&mut self) -> &mut HashMap<String, Py<PyAny>> {
+ self.rust_sentinels
+ .get_or_insert_with(|| Box::new(HashMap::new()))
+ }
+}
+
+impl Clone for PyAst {
+ fn clone(&self) -> Self {
+ // `Py<T>::clone_ref` needs the GIL; the parse loop always holds it via the outer #[pyfunction], so `with_gil` is a free re-borrow of the already-acquired token.
+ Python::with_gil(|py| Self {
+ obj: self.obj.clone_ref(py),
+ positions_locked: self.positions_locked,
+ // Skip the allocation entirely when the source had no sentinels (the common case).
+ rust_sentinels: self.rust_sentinels.as_ref().map(|m| {
+ Box::new(
+ m.iter()
+ .map(|(k, v)| (k.clone(), v.clone_ref(py)))
+ .collect(),
+ )
+ }),
+ })
+ }
+}
+
+// ============================================================================
+// PyEmitter — caches AST class references and constructs nodes via class.call.
+// ============================================================================
+
+/// Constructs `posthog.hogql.ast` instances directly. Holds the GIL token + cached class references for the full duration of one parse.
+///
+/// `Clone` is required by the Emitter trait bound — the parser clones the emitter into a sub-`Parser` for `f'{…}'` template blocks. Each `Bound<'py, _>` clone is just a refcount bump, so cloning the whole struct is ~60 refcount bumps — cheap compared to a parse round.
+#[derive(Clone)]
+pub struct PyEmitter<'py> {
+ py: Python<'py>,
+ // ===== Expression node classes (28) =====
+ cls_constant: Bound<'py, PyAny>,
+ cls_field: Bound<'py, PyAny>,
+ cls_arith_op: Bound<'py, PyAny>,
+ cls_compare_op: Bound<'py, PyAny>,
+ cls_is_distinct_from: Bound<'py, PyAny>,
+ cls_between_expr: Bound<'py, PyAny>,
+ cls_not: Bound<'py, PyAny>,
+ cls_and: Bound<'py, PyAny>,
+ cls_or: Bound<'py, PyAny>,
+ cls_tuple: Bound<'py, PyAny>,
+ cls_array: Bound<'py, PyAny>,
+ cls_array_access: Bound<'py, PyAny>,
+ cls_tuple_access: Bound<'py, PyAny>,
+ cls_alias: Bound<'py, PyAny>,
+ cls_call: Bound<'py, PyAny>,
+ cls_expr_call: Bound<'py, PyAny>,
+ cls_lambda: Bound<'py, PyAny>,
+ cls_type_cast: Bound<'py, PyAny>,
+ cls_try_cast: Bound<'py, PyAny>,
+ cls_array_slice: Bound<'py, PyAny>,
+ cls_dict: Bound<'py, PyAny>,
+ cls_placeholder: Bound<'py, PyAny>,
+ cls_named_argument: Bound<'py, PyAny>,
+ cls_order_expr: Bound<'py, PyAny>,
+ cls_columns_expr: Bound<'py, PyAny>,
+ cls_spread_expr: Bound<'py, PyAny>,
+ cls_positional_ref: Bound<'py, PyAny>,
+ // ===== Statement / program classes (13) =====
+ cls_program: Bound<'py, PyAny>,
+ cls_block: Bound<'py, PyAny>,
+ cls_expr_statement: Bound<'py, PyAny>,
+ cls_if_statement: Bound<'py, PyAny>,
+ cls_while_statement: Bound<'py, PyAny>,
+ cls_for_in_statement: Bound<'py, PyAny>,
+ cls_for_statement: Bound<'py, PyAny>,
+ cls_function: Bound<'py, PyAny>,
+ cls_variable_assignment: Bound<'py, PyAny>,
+ cls_return_statement: Bound<'py, PyAny>,
+ cls_try_catch_statement: Bound<'py, PyAny>,
+ cls_throw_statement: Bound<'py, PyAny>,
+ cls_variable_declaration: Bound<'py, PyAny>,
+ // ===== Query / clause classes =====
+ cls_cte: Bound<'py, PyAny>,
+ cls_join_constraint: Bound<'py, PyAny>,
+ cls_values_query: Bound<'py, PyAny>,
+ cls_pivot_column: Bound<'py, PyAny>,
+ cls_unpivot_column: Bound<'py, PyAny>,
+ cls_grouping_set: Bound<'py, PyAny>,
+ cls_hogqlx_tag: Bound<'py, PyAny>,
+ cls_hogqlx_attribute: Bound<'py, PyAny>,
+ cls_window_frame_expr: Bound<'py, PyAny>,
+ cls_select_set_query: Bound<'py, PyAny>,
+ cls_select_query: Bound<'py, PyAny>,
+ cls_select_set_node: Bound<'py, PyAny>,
+ cls_sample_expr: Bound<'py, PyAny>,
+ cls_ratio_expr: Bound<'py, PyAny>,
+ cls_pivot_expr: Bound<'py, PyAny>,
+ cls_unpivot_expr: Bound<'py, PyAny>,
+ cls_join_expr: Bound<'py, PyAny>,
+ cls_window_function: Bound<'py, PyAny>,
+ cls_with_fill_expr: Bound<'py, PyAny>,
+ cls_window_expr: Bound<'py, PyAny>,
+ cls_interpolate_expr: Bound<'py, PyAny>,
+ cls_limit_by_expr: Bound<'py, PyAny>,
+ /// Python builtin `int` class — used by `constant_number_string` for arbitrary-precision integer literals (i64-wider hex/decimal). Cached once instead of `py.eval_bound("int", ...)` per call.
+ cls_int: Bound<'py, PyAny>,
+ // ===== Op enum members (pre-resolved at construction) =====
+ // Previous impl did `cls.get_item(op)` per arith/compare call — a PyDict lookup against the StrEnum class. Caching saves millions of lookups across the factory suite; each entry is one refcount-bumped `Bound`.
+ arith_op_add: Bound<'py, PyAny>,
+ arith_op_sub: Bound<'py, PyAny>,
+ arith_op_mult: Bound<'py, PyAny>,
+ arith_op_div: Bound<'py, PyAny>,
+ arith_op_mod: Bound<'py, PyAny>,
+ compare_op_eq: Bound<'py, PyAny>,
+ compare_op_not_eq: Bound<'py, PyAny>,
+ compare_op_gt: Bound<'py, PyAny>,
+ compare_op_gt_eq: Bound<'py, PyAny>,
+ compare_op_lt: Bound<'py, PyAny>,
+ compare_op_lt_eq: Bound<'py, PyAny>,
+ compare_op_like: Bound<'py, PyAny>,
+ compare_op_ilike: Bound<'py, PyAny>,
+ compare_op_not_like: Bound<'py, PyAny>,
+ compare_op_not_ilike: Bound<'py, PyAny>,
+ compare_op_in: Bound<'py, PyAny>,
+ compare_op_global_in: Bound<'py, PyAny>,
+ compare_op_not_in: Bound<'py, PyAny>,
+ compare_op_global_not_in: Bound<'py, PyAny>,
+ compare_op_in_cohort: Bound<'py, PyAny>,
+ compare_op_not_in_cohort: Bound<'py, PyAny>,
+ compare_op_regex: Bound<'py, PyAny>,
+ compare_op_iregex: Bound<'py, PyAny>,
+ compare_op_not_regex: Bound<'py, PyAny>,
+ compare_op_not_iregex: Bound<'py, PyAny>,
+}
+
+impl<'py> PyEmitter<'py> {
+ pub fn new(py: Python<'py>) -> PyResult<Self> {
+ let ast_module = py.import_bound("posthog.hogql.ast")?;
+ // Bind the StrEnum classes once for readability — not stored on the struct since the enum classes themselves are never read again after member extraction.
+ let arith_enum = ast_module.getattr("ArithmeticOperationOp")?;
+ let compare_enum = ast_module.getattr("CompareOperationOp")?;
+ Ok(Self {
+ cls_constant: ast_module.getattr("Constant")?,
+ cls_field: ast_module.getattr("Field")?,
+ cls_arith_op: ast_module.getattr("ArithmeticOperation")?,
+ cls_compare_op: ast_module.getattr("CompareOperation")?,
+ cls_is_distinct_from: ast_module.getattr("IsDistinctFrom")?,
+ cls_between_expr: ast_module.getattr("BetweenExpr")?,
+ cls_not: ast_module.getattr("Not")?,
+ cls_and: ast_module.getattr("And")?,
+ cls_or: ast_module.getattr("Or")?,
+ cls_tuple: ast_module.getattr("Tuple")?,
+ cls_array: ast_module.getattr("Array")?,
+ cls_array_access: ast_module.getattr("ArrayAccess")?,
+ cls_tuple_access: ast_module.getattr("TupleAccess")?,
+ cls_alias: ast_module.getattr("Alias")?,
+ cls_call: ast_module.getattr("Call")?,
+ cls_expr_call: ast_module.getattr("ExprCall")?,
+ cls_lambda: ast_module.getattr("Lambda")?,
+ cls_type_cast: ast_module.getattr("TypeCast")?,
+ cls_try_cast: ast_module.getattr("TryCast")?,
+ cls_array_slice: ast_module.getattr("ArraySlice")?,
+ cls_dict: ast_module.getattr("Dict")?,
+ cls_placeholder: ast_module.getattr("Placeholder")?,
+ cls_named_argument: ast_module.getattr("NamedArgument")?,
+ cls_order_expr: ast_module.getattr("OrderExpr")?,
+ cls_columns_expr: ast_module.getattr("ColumnsExpr")?,
+ cls_spread_expr: ast_module.getattr("SpreadExpr")?,
+ cls_positional_ref: ast_module.getattr("PositionalRef")?,
+ cls_program: ast_module.getattr("Program")?,
+ cls_block: ast_module.getattr("Block")?,
+ cls_expr_statement: ast_module.getattr("ExprStatement")?,
+ cls_if_statement: ast_module.getattr("IfStatement")?,
+ cls_while_statement: ast_module.getattr("WhileStatement")?,
+ cls_for_in_statement: ast_module.getattr("ForInStatement")?,
+ cls_for_statement: ast_module.getattr("ForStatement")?,
+ cls_function: ast_module.getattr("Function")?,
+ cls_variable_assignment: ast_module.getattr("VariableAssignment")?,
+ cls_return_statement: ast_module.getattr("ReturnStatement")?,
+ cls_try_catch_statement: ast_module.getattr("TryCatchStatement")?,
+ cls_throw_statement: ast_module.getattr("ThrowStatement")?,
+ cls_variable_declaration: ast_module.getattr("VariableDeclaration")?,
+ cls_cte: ast_module.getattr("CTE")?,
+ cls_join_constraint: ast_module.getattr("JoinConstraint")?,
+ cls_values_query: ast_module.getattr("ValuesQuery")?,
+ cls_pivot_column: ast_module.getattr("PivotColumn")?,
+ cls_unpivot_column: ast_module.getattr("UnpivotColumn")?,
+ cls_grouping_set: ast_module.getattr("GroupingSet")?,
+ cls_hogqlx_tag: ast_module.getattr("HogQLXTag")?,
+ cls_hogqlx_attribute: ast_module.getattr("HogQLXAttribute")?,
+ cls_window_frame_expr: ast_module.getattr("WindowFrameExpr")?,
+ cls_select_set_query: ast_module.getattr("SelectSetQuery")?,
+ cls_select_query: ast_module.getattr("SelectQuery")?,
+ cls_select_set_node: ast_module.getattr("SelectSetNode")?,
+ cls_sample_expr: ast_module.getattr("SampleExpr")?,
+ cls_ratio_expr: ast_module.getattr("RatioExpr")?,
+ cls_pivot_expr: ast_module.getattr("PivotExpr")?,
+ cls_unpivot_expr: ast_module.getattr("UnpivotExpr")?,
+ cls_join_expr: ast_module.getattr("JoinExpr")?,
+ cls_window_function: ast_module.getattr("WindowFunction")?,
+ cls_with_fill_expr: ast_module.getattr("WithFillExpr")?,
+ cls_window_expr: ast_module.getattr("WindowExpr")?,
+ cls_interpolate_expr: ast_module.getattr("InterpolateExpr")?,
+ cls_limit_by_expr: ast_module.getattr("LimitByExpr")?,
+ cls_int: py.import_bound("builtins")?.getattr("int")?,
+ // Pre-resolve enum members by NAME — StrEnum classes are subscriptable by member-name (`cls["Add"]`), not by value (`cls["+"]` fails).
+ arith_op_add: arith_enum.get_item("Add")?,
+ arith_op_sub: arith_enum.get_item("Sub")?,
+ arith_op_mult: arith_enum.get_item("Mult")?,
+ arith_op_div: arith_enum.get_item("Div")?,
+ arith_op_mod: arith_enum.get_item("Mod")?,
+ compare_op_eq: compare_enum.get_item("Eq")?,
+ compare_op_not_eq: compare_enum.get_item("NotEq")?,
+ compare_op_gt: compare_enum.get_item("Gt")?,
+ compare_op_gt_eq: compare_enum.get_item("GtEq")?,
+ compare_op_lt: compare_enum.get_item("Lt")?,
+ compare_op_lt_eq: compare_enum.get_item("LtEq")?,
+ compare_op_like: compare_enum.get_item("Like")?,
+ compare_op_ilike: compare_enum.get_item("ILike")?,
+ compare_op_not_like: compare_enum.get_item("NotLike")?,
+ compare_op_not_ilike: compare_enum.get_item("NotILike")?,
+ compare_op_in: compare_enum.get_item("In")?,
+ compare_op_global_in: compare_enum.get_item("GlobalIn")?,
+ compare_op_not_in: compare_enum.get_item("NotIn")?,
+ compare_op_global_not_in: compare_enum.get_item("GlobalNotIn")?,
+ compare_op_in_cohort: compare_enum.get_item("InCohort")?,
+ compare_op_not_in_cohort: compare_enum.get_item("NotInCohort")?,
+ compare_op_regex: compare_enum.get_item("Regex")?,
+ compare_op_iregex: compare_enum.get_item("IRegex")?,
+ compare_op_not_regex: compare_enum.get_item("NotRegex")?,
+ compare_op_not_iregex: compare_enum.get_item("NotIRegex")?,
+ py,
+ })
+ }
+
+ /// Map an arithmetic op symbol to the cached `ArithmeticOperationOp` StrEnum member — compiles to a jump table (one branch + return ref).
+ fn arith_op(&self, op: &str) -> &Bound<'py, PyAny> {
+ match op {
+ "+" => &self.arith_op_add,
+ "-" => &self.arith_op_sub,
+ "*" => &self.arith_op_mult,
+ "/" => &self.arith_op_div,
+ "%" => &self.arith_op_mod,
+ other => panic!("unknown arith op symbol `{other}`"),
+ }
+ }
+
+ /// Map a comparison op symbol to the cached `CompareOperationOp` StrEnum member.
+ fn compare_op(&self, op: &str) -> &Bound<'py, PyAny> {
+ match op {
+ "==" => &self.compare_op_eq,
+ "!=" => &self.compare_op_not_eq,
+ ">" => &self.compare_op_gt,
+ ">=" => &self.compare_op_gt_eq,
+ "<" => &self.compare_op_lt,
+ "<=" => &self.compare_op_lt_eq,
+ "like" => &self.compare_op_like,
+ "ilike" => &self.compare_op_ilike,
+ "not like" => &self.compare_op_not_like,
+ "not ilike" => &self.compare_op_not_ilike,
+ "in" => &self.compare_op_in,
+ "global in" => &self.compare_op_global_in,
+ "not in" => &self.compare_op_not_in,
+ "global not in" => &self.compare_op_global_not_in,
+ "in cohort" => &self.compare_op_in_cohort,
+ "not in cohort" => &self.compare_op_not_in_cohort,
+ "=~" => &self.compare_op_regex,
+ "=~*" => &self.compare_op_iregex,
+ "!~" => &self.compare_op_not_regex,
+ "!~*" => &self.compare_op_not_iregex,
+ other => panic!("unknown compare op symbol `{other}`"),
+ }
+ }
+
+ /// Construct a node by invoking `class(**kwargs)`. Wraps the result in [`PyAst`] with `positions_locked = false`.
+ fn build(&self, class: &Bound<'py, PyAny>, kwargs: &Bound<'py, PyDict>) -> PyAst {
+ let obj = class
+ .call(PyTuple::empty_bound(self.py), Some(kwargs))
+ .expect("ast class construction failed (validate kwargs / class shape)")
+ .unbind();
+ PyAst {
+ obj,
+ positions_locked: false,
+ rust_sentinels: None,
+ }
+ }
+
+ /// Helper: wrap a non-AST primitive (None, bool, int, str, list) in PyAst so it flows through the parser as `Self::Value`.
+ fn wrap_prim(&self, obj: PyObject) -> PyAst {
+ PyAst {
+ obj,
+ positions_locked: false,
+ rust_sentinels: None,
+ }
+ }
+}
+
+// ============================================================================
+// Emitter impl
+// ============================================================================
+
+impl<'py> Emitter for PyEmitter<'py> {
+ type Value = PyAst;
+
+ // ===== Primitive constructors =====
+
+ fn null(&self) -> PyAst {
+ self.wrap_prim(self.py.None())
+ }
+ fn bool(&self, v: bool) -> PyAst {
+ self.wrap_prim(v.into_py(self.py))
+ }
+ fn int(&self, v: i64) -> PyAst {
+ self.wrap_prim(v.into_py(self.py))
+ }
+ fn string(&self, v: &str) -> PyAst {
+ self.wrap_prim(v.into_py(self.py))
+ }
+ fn float(&self, v: f64) -> PyAst {
+ self.wrap_prim(v.into_py(self.py))
+ }
+ fn uint(&self, v: u64) -> PyAst {
+ self.wrap_prim(v.into_py(self.py))
+ }
+ fn list_value(&self, items: Vec<PyAst>) -> PyAst {
+ let list = PyList::empty_bound(self.py);
+ for item in items {
+ list.append(item.obj).unwrap();
+ }
+ self.wrap_prim(list.into_any().unbind())
+ }
+ fn string_keyed_map(&self, pairs: Vec<(String, PyAst)>) -> PyAst {
+ let dict = PyDict::new_bound(self.py);
+ for (k, v) in pairs {
+ dict.set_item(k, v.obj.bind(self.py)).unwrap();
+ }
+ self.wrap_prim(dict.into_any().unbind())
+ }
+
+ // ===== AST node constructors =====
+
+ fn constant(&self, value: PyAst) -> PyAst {
+ let kw = PyDict::new_bound(self.py);
+ kw.set_item("value", value.obj.bind(self.py)).unwrap();
+ self.build(&self.cls_constant, &kw)
+ }
+ fn constant_special_number(&self, name: &'static str) -> PyAst {
+ // cpp's `Infinity` / `-Infinity` / `NaN` ship as strings in JSON; the Python side unwraps to f64, so the Constant holds `value: float('inf')` etc.
+ let f = match name {
+ "Infinity" => f64::INFINITY,
+ "-Infinity" => f64::NEG_INFINITY,
+ "NaN" => f64::NAN,
+ _ => panic!("unknown special number name `{name}`"),
+ };
+ let kw = PyDict::new_bound(self.py);
+ kw.set_item("value", f).unwrap();
+ self.build(&self.cls_constant, &kw)
+ }
+ fn constant_number_string(&self, text: String) -> PyAst {
+ // Lossless big int: hand the digit string to Python `int(text, base)`. Mirrors `pyobject::parse_large_int_literal`.
+ let body = text.strip_prefix('-').unwrap_or(&text);
+ let is_hex = body.starts_with("0x") || body.starts_with("0X");
+ let base = if is_hex { 16 } else { 10 };
+ let args = PyTuple::new_bound(self.py, [text.into_py(self.py), base.into_py(self.py)]);
+ let int_obj = self.cls_int.call(&args, None).unwrap();
+ let kw = PyDict::new_bound(self.py);
+ kw.set_item("value", &int_obj).unwrap();
+ self.build(&self.cls_constant, &kw)
+ }
+ fn field(&self, chain: Vec<PyAst>) -> PyAst {
+ let kw = PyDict::new_bound(self.py);
+ kw.set_item("chain", build_list(self.py, chain)).unwrap();
+ self.build(&self.cls_field, &kw)
+ }
+ fn arith(&self, left: PyAst, op: &str, right: PyAst) -> PyAst {
+ let kw = PyDict::new_bound(self.py);
+ kw.set_item("left", left.obj.bind(self.py)).unwrap();
+ kw.set_item("right", right.obj.bind(self.py)).unwrap();
+ kw.set_item("op", self.arith_op(op)).unwrap();
+ self.build(&self.cls_arith_op, &kw)
+ }
+ fn compare(&self, left: PyAst, op: &str, right: PyAst) -> PyAst {
+ let kw = PyDict::new_bound(self.py);
+ kw.set_item("left", left.obj.bind(self.py)).unwrap();
+ kw.set_item("right", right.obj.bind(self.py)).unwrap();
+ kw.set_item("op", self.compare_op(op)).unwrap();
+ self.build(&self.cls_compare_op, &kw)
+ }
+ fn compare_is_null(&self, left: PyAst, negated: bool) -> PyAst {
+ // `expr IS [NOT] NULL` → CompareOperation(left, Constant(None), == / !=, is_null_comparison_style=True).
+ let kw = PyDict::new_bound(self.py);
+ kw.set_item("left", left.obj.bind(self.py)).unwrap();
+ let null_constant = self.constant(self.null());
+ kw.set_item("right", null_constant.obj.bind(self.py))
+ .unwrap();
+ let op_member = if negated {
+ &self.compare_op_not_eq
+ } else {
+ &self.compare_op_eq
+ };
+ kw.set_item("op", op_member).unwrap();
+ kw.set_item("is_null_comparison_style", true).unwrap();
+ self.build(&self.cls_compare_op, &kw)
+ }
+ fn is_distinct_from(&self, left: PyAst, right: PyAst, negated: bool) -> PyAst {
+ let kw = PyDict::new_bound(self.py);
+ kw.set_item("left", left.obj.bind(self.py)).unwrap();
+ kw.set_item("right", right.obj.bind(self.py)).unwrap();
+ kw.set_item("negated", negated).unwrap();
+ self.build(&self.cls_is_distinct_from, &kw)
+ }
+ fn between(&self, expr: PyAst, low: PyAst, high: PyAst, negated: bool) -> PyAst {
+ let kw = PyDict::new_bound(self.py);
+ kw.set_item("expr", expr.obj.bind(self.py)).unwrap();
+ kw.set_item("low", low.obj.bind(self.py)).unwrap();
+ kw.set_item("high", high.obj.bind(self.py)).unwrap();
+ kw.set_item("negated", negated).unwrap();
+ self.build(&self.cls_between_expr, &kw)
+ }
+ fn not_(&self, expr: PyAst) -> PyAst {
+ let kw = PyDict::new_bound(self.py);
+ kw.set_item("expr", expr.obj.bind(self.py)).unwrap();
+ self.build(&self.cls_not, &kw)
+ }
+ fn and_(&self, exprs: Vec<PyAst>) -> PyAst {
+ let kw = PyDict::new_bound(self.py);
+ kw.set_item("exprs", build_list(self.py, exprs)).unwrap();
+ self.build(&self.cls_and, &kw)
+ }
+ fn or_(&self, exprs: Vec<PyAst>) -> PyAst {
+ let kw = PyDict::new_bound(self.py);
+ kw.set_item("exprs", build_list(self.py, exprs)).unwrap();
+ self.build(&self.cls_or, &kw)
+ }
+ fn tuple_(&self, exprs: Vec<PyAst>) -> PyAst {
+ let kw = PyDict::new_bound(self.py);
+ kw.set_item("exprs", build_list(self.py, exprs)).unwrap();
+ self.build(&self.cls_tuple, &kw)
+ }
+ fn array_(&self, exprs: Vec<PyAst>) -> PyAst {
+ let kw = PyDict::new_bound(self.py);
+ kw.set_item("exprs", build_list(self.py, exprs)).unwrap();
+ self.build(&self.cls_array, &kw)
+ }
+ fn array_access(&self, array: PyAst, property: PyAst, nullish: bool) -> PyAst {
+ let kw = PyDict::new_bound(self.py);
+ kw.set_item("array", array.obj.bind(self.py)).unwrap();
+ kw.set_item("property", property.obj.bind(self.py)).unwrap();
+ if nullish {
+ kw.set_item("nullish", true).unwrap();
+ }
+ self.build(&self.cls_array_access, &kw)
+ }
+ fn tuple_access(&self, tuple_: PyAst, index: i64, nullish: bool) -> PyAst {
+ let kw = PyDict::new_bound(self.py);
+ kw.set_item("tuple", tuple_.obj.bind(self.py)).unwrap();
+ kw.set_item("index", index).unwrap();
+ if nullish {
+ kw.set_item("nullish", true).unwrap();
+ }
+ self.build(&self.cls_tuple_access, &kw)
+ }
+ fn alias(&self, expr: PyAst, name: &str) -> PyAst {
+ let kw = PyDict::new_bound(self.py);
+ kw.set_item("expr", expr.obj.bind(self.py)).unwrap();
+ kw.set_item("alias", name).unwrap();
+ self.build(&self.cls_alias, &kw)
+ }
+ fn call(&self, name: &str, args: Vec<PyAst>) -> PyAst {
+ let kw = PyDict::new_bound(self.py);
+ kw.set_item("name", name).unwrap();
+ kw.set_item("args", build_list(self.py, args)).unwrap();
+ self.build(&self.cls_call, &kw)
+ }
+ fn call_full(
+ &self,
+ name: &str,
+ params: Option<Vec<PyAst>>,
+ args: Vec<PyAst>,
+ distinct: bool,
+ order_by: Option<Vec<PyAst>>,
+ filter_expr: Option<PyAst>,
+ within_group: Option<Vec<PyAst>>,
+ ) -> PyAst {
+ let kw = PyDict::new_bound(self.py);
+ kw.set_item("name", name).unwrap();
+ kw.set_item("args", build_list(self.py, args)).unwrap();
+ if let Some(p) = params {
+ kw.set_item("params", build_list(self.py, p)).unwrap();
+ }
+ if distinct {
+ kw.set_item("distinct", true).unwrap();
+ }
+ if let Some(ob) = order_by {
+ kw.set_item("order_by", build_list(self.py, ob)).unwrap();
+ }
+ if let Some(fe) = filter_expr {
+ kw.set_item("filter_expr", fe.obj.bind(self.py)).unwrap();
+ }
+ if let Some(wg) = within_group {
+ kw.set_item("within_group", build_list(self.py, wg))
+ .unwrap();
+ }
+ self.build(&self.cls_call, &kw)
+ }
+ fn lambda(&self, args: Vec<String>, expr: PyAst) -> PyAst {
+ let kw = PyDict::new_bound(self.py);
+ let args_list = PyList::empty_bound(self.py);
+ for a in args {
+ args_list.append(a).unwrap();
+ }
+ kw.set_item("args", args_list).unwrap();
+ kw.set_item("expr", expr.obj.bind(self.py)).unwrap();
+ self.build(&self.cls_lambda, &kw)
+ }
+ fn expr_call(&self, expr: PyAst, args: Vec<PyAst>) -> PyAst {
+ let kw = PyDict::new_bound(self.py);
+ kw.set_item("expr", expr.obj.bind(self.py)).unwrap();
+ kw.set_item("args", build_list(self.py, args)).unwrap();
+ self.build(&self.cls_expr_call, &kw)
+ }
+ fn type_cast(&self, expr: PyAst, type_name: &str) -> PyAst {
+ let kw = PyDict::new_bound(self.py);
+ kw.set_item("expr", expr.obj.bind(self.py)).unwrap();
+ kw.set_item("type_name", type_name).unwrap();
+ self.build(&self.cls_type_cast, &kw)
+ }
+ fn try_cast(&self, expr: PyAst, type_name: &str) -> PyAst {
+ let kw = PyDict::new_bound(self.py);
+ kw.set_item("expr", expr.obj.bind(self.py)).unwrap();
+ kw.set_item("type_name", type_name).unwrap();
+ self.build(&self.cls_try_cast, &kw)
+ }
+ fn array_slice(&self, array: PyAst, start: Option<PyAst>, end: Option<PyAst>) -> PyAst {
+ let kw = PyDict::new_bound(self.py);
+ kw.set_item("array", array.obj.bind(self.py)).unwrap();
+ if let Some(s) = start {
+ kw.set_item("start_expr", s.obj.bind(self.py)).unwrap();
+ }
+ if let Some(e) = end {
+ kw.set_item("end_expr", e.obj.bind(self.py)).unwrap();
+ }
+ self.build(&self.cls_array_slice, &kw)
+ }
+ fn dict_(&self, items: Vec<(PyAst, PyAst)>) -> PyAst {
+ let kw = PyDict::new_bound(self.py);
+ let items_list = PyList::empty_bound(self.py);
+ for (k, v) in items {
+ let pair = PyTuple::new_bound(self.py, [k.obj, v.obj]);
+ items_list.append(pair).unwrap();
+ }
+ kw.set_item("items", items_list).unwrap();
+ self.build(&self.cls_dict, &kw)
+ }
+ fn placeholder(&self, expr: PyAst) -> PyAst {
+ let kw = PyDict::new_bound(self.py);
+ kw.set_item("expr", expr.obj.bind(self.py)).unwrap();
+ self.build(&self.cls_placeholder, &kw)
+ }
+ fn named_argument(&self, name: &str, value: PyAst) -> PyAst {
+ let kw = PyDict::new_bound(self.py);
+ kw.set_item("name", name).unwrap();
+ kw.set_item("value", value.obj.bind(self.py)).unwrap();
+ let mut node = self.build(&self.cls_named_argument, &kw);
+ // cpp's `VISIT(NamedArgument)` emits this without `addPositionInfo`; `positions_locked` short-circuits future `with_pos` calls.
+ node.positions_locked = true;
+ node
+ }
+ fn order_expr(&self, expr: PyAst, order: &str, with_fill: Option<PyAst>) -> PyAst {
+ let kw = PyDict::new_bound(self.py);
+ kw.set_item("expr", expr.obj.bind(self.py)).unwrap();
+ kw.set_item("order", order).unwrap();
+ if let Some(wf) = with_fill {
+ kw.set_item("with_fill", wf.obj.bind(self.py)).unwrap();
+ }
+ self.build(&self.cls_order_expr, &kw)
+ }
+ fn columns_expr(
+ &self,
+ regex: Option<String>,
+ columns: Option<Vec<PyAst>>,
+ all_columns: bool,
+ exclude: Option<Vec<String>>,
+ replace: Option<Vec<(String, PyAst)>>,
+ ) -> PyAst {
+ let kw = PyDict::new_bound(self.py);
+ if let Some(r) = regex {
+ kw.set_item("regex", r).unwrap();
+ }
+ if let Some(c) = columns {
+ kw.set_item("columns", build_list(self.py, c)).unwrap();
+ }
+ if all_columns {
+ kw.set_item("all_columns", true).unwrap();
+ }
+ if let Some(ex) = exclude {
+ let ex_list = PyList::empty_bound(self.py);
+ for s in ex {
+ ex_list.append(s).unwrap();
+ }
+ kw.set_item("exclude", ex_list).unwrap();
+ }
+ if let Some(rep) = replace {
+ let rep_dict = PyDict::new_bound(self.py);
+ for (k, v) in rep {
+ rep_dict.set_item(k, v.obj.bind(self.py)).unwrap();
+ }
+ kw.set_item("replace", rep_dict).unwrap();
+ }
+ self.build(&self.cls_columns_expr, &kw)
+ }
+ fn spread_expr(&self, expr: PyAst) -> PyAst {
+ let kw = PyDict::new_bound(self.py);
+ kw.set_item("expr", expr.obj.bind(self.py)).unwrap();
+ self.build(&self.cls_spread_expr, &kw)
+ }
+ fn positional_ref(&self, index: i64) -> PyAst {
+ let kw = PyDict::new_bound(self.py);
+ kw.set_item("index", index).unwrap();
+ self.build(&self.cls_positional_ref, &kw)
+ }
+
+ // ===== Statement / program builders =====
+
+ fn program(&self, declarations: Vec<PyAst>) -> PyAst {
+ let kw = PyDict::new_bound(self.py);
+ kw.set_item("declarations", build_list(self.py, declarations))
+ .unwrap();
+ self.build(&self.cls_program, &kw)
+ }
+ fn block(&self, declarations: Vec<PyAst>) -> PyAst {
+ let kw = PyDict::new_bound(self.py);
+ kw.set_item("declarations", build_list(self.py, declarations))
+ .unwrap();
+ self.build(&self.cls_block, &kw)
+ }
+ fn expr_statement(&self, expr: PyAst) -> PyAst {
+ let kw = PyDict::new_bound(self.py);
+ kw.set_item("expr", expr.obj.bind(self.py)).unwrap();
+ self.build(&self.cls_expr_statement, &kw)
+ }
+ fn if_statement(&self, cond: PyAst, then: PyAst, else_: PyAst) -> PyAst {
+ let kw = PyDict::new_bound(self.py);
+ kw.set_item("expr", cond.obj.bind(self.py)).unwrap();
+ kw.set_item("then", then.obj.bind(self.py)).unwrap();
+ kw.set_item("else_", else_.obj.bind(self.py)).unwrap();
+ self.build(&self.cls_if_statement, &kw)
+ }
+ fn while_statement(&self, cond: PyAst, body: PyAst) -> PyAst {
+ let kw = PyDict::new_bound(self.py);
+ kw.set_item("expr", cond.obj.bind(self.py)).unwrap();
+ kw.set_item("body", body.obj.bind(self.py)).unwrap();
+ self.build(&self.cls_while_statement, &kw)
+ }
+ fn for_in_statement(
+ &self,
+ key_var: PyAst,
+ value_var: PyAst,
+ expr: PyAst,
+ body: PyAst,
+ ) -> PyAst {
+ let kw = PyDict::new_bound(self.py);
+ kw.set_item("keyVar", key_var.obj.bind(self.py)).unwrap();
+ kw.set_item("valueVar", value_var.obj.bind(self.py))
+ .unwrap();
+ kw.set_item("expr", expr.obj.bind(self.py)).unwrap();
+ kw.set_item("body", body.obj.bind(self.py)).unwrap();
+ self.build(&self.cls_for_in_statement, &kw)
+ }
+ fn for_statement(
+ &self,
+ initializer: PyAst,
+ condition: PyAst,
+ increment: PyAst,
+ body: PyAst,
+ ) -> PyAst {
+ let kw = PyDict::new_bound(self.py);
+ kw.set_item("initializer", initializer.obj.bind(self.py))
+ .unwrap();
+ kw.set_item("condition", condition.obj.bind(self.py))
+ .unwrap();
+ kw.set_item("increment", increment.obj.bind(self.py))
+ .unwrap();
+ kw.set_item("body", body.obj.bind(self.py)).unwrap();
+ self.build(&self.cls_for_statement, &kw)
+ }
+ fn function_(&self, name: &str, params: Vec<PyAst>, body: PyAst) -> PyAst {
+ let kw = PyDict::new_bound(self.py);
+ kw.set_item("name", name).unwrap();
+ kw.set_item("params", build_list(self.py, params)).unwrap();
+ kw.set_item("body", body.obj.bind(self.py)).unwrap();
+ self.build(&self.cls_function, &kw)
+ }
+ fn variable_assignment(&self, left: PyAst, right: PyAst) -> PyAst {
+ let kw = PyDict::new_bound(self.py);
+ kw.set_item("left", left.obj.bind(self.py)).unwrap();
+ kw.set_item("right", right.obj.bind(self.py)).unwrap();
+ self.build(&self.cls_variable_assignment, &kw)
+ }
+ fn return_statement(&self, expr: PyAst) -> PyAst {
+ let kw = PyDict::new_bound(self.py);
+ kw.set_item("expr", expr.obj.bind(self.py)).unwrap();
+ self.build(&self.cls_return_statement, &kw)
+ }
+ fn try_catch_statement(
+ &self,
+ try_stmt: PyAst,
+ catches: Vec<PyAst>,
+ finally_stmt: PyAst,
+ ) -> PyAst {
+ let kw = PyDict::new_bound(self.py);
+ kw.set_item("try_stmt", try_stmt.obj.bind(self.py)).unwrap();
+ kw.set_item("catches", build_list(self.py, catches))
+ .unwrap();
+ kw.set_item("finally_stmt", finally_stmt.obj.bind(self.py))
+ .unwrap();
+ self.build(&self.cls_try_catch_statement, &kw)
+ }
+ fn throw_statement(&self, expr: PyAst) -> PyAst {
+ let kw = PyDict::new_bound(self.py);
+ kw.set_item("expr", expr.obj.bind(self.py)).unwrap();
+ self.build(&self.cls_throw_statement, &kw)
+ }
+ fn variable_declaration(&self, name: &str, expr: PyAst) -> PyAst {
+ let kw = PyDict::new_bound(self.py);
+ kw.set_item("name", name).unwrap();
+ kw.set_item("expr", expr.obj.bind(self.py)).unwrap();
+ self.build(&self.cls_variable_declaration, &kw)
+ }
+ fn catch_clause(&self, var: PyAst, ty: PyAst, body: PyAst) -> PyAst {
+ // cpp emits this as a `[var, type, body]` JSON array — we mirror the shape on Py since `TryCatchStatement.catches` is `list[list[Expr | Type | Block]]`.
+ let list = PyList::empty_bound(self.py);
+ list.append(var.obj).unwrap();
+ list.append(ty.obj).unwrap();
+ list.append(body.obj).unwrap();
+ self.wrap_prim(list.into_any().unbind())
+ }
+
+ // ===== Query / clause builders =====
+
+ fn cte(&self, name: &str, expr: PyAst, cte_type: &str) -> PyAst {
+ let kw = PyDict::new_bound(self.py);
+ kw.set_item("name", name).unwrap();
+ kw.set_item("expr", expr.obj.bind(self.py)).unwrap();
+ kw.set_item("cte_type", cte_type).unwrap();
+ self.build(&self.cls_cte, &kw)
+ }
+ fn cte_subquery(
+ &self,
+ name: &str,
+ expr: PyAst,
+ columns: Option<Vec<String>>,
+ using_key: Option<Vec<String>>,
+ materialized: Option<bool>,
+ ) -> PyAst {
+ let kw = PyDict::new_bound(self.py);
+ kw.set_item("name", name).unwrap();
+ kw.set_item("expr", expr.obj.bind(self.py)).unwrap();
+ kw.set_item("cte_type", "subquery").unwrap();
+ if let Some(c) = columns {
+ let l = PyList::empty_bound(self.py);
+ for s in c {
+ l.append(s).unwrap();
+ }
+ kw.set_item("columns", l).unwrap();
+ }
+ if let Some(uk) = using_key {
+ let l = PyList::empty_bound(self.py);
+ for s in uk {
+ l.append(s).unwrap();
+ }
+ kw.set_item("using_key", l).unwrap();
+ }
+ if let Some(m) = materialized {
+ kw.set_item("materialized", m).unwrap();
+ }
+ self.build(&self.cls_cte, &kw)
+ }
+ fn join_constraint(&self, expr: PyAst, constraint_type: &str) -> PyAst {
+ let kw = PyDict::new_bound(self.py);
+ kw.set_item("expr", expr.obj.bind(self.py)).unwrap();
+ kw.set_item("constraint_type", constraint_type).unwrap();
+ self.build(&self.cls_join_constraint, &kw)
+ }
+ fn values_query(&self, rows: Vec<PyAst>) -> PyAst {
+ let kw = PyDict::new_bound(self.py);
+ kw.set_item("rows", build_list(self.py, rows)).unwrap();
+ self.build(&self.cls_values_query, &kw)
+ }
+ fn pivot_column(&self, column: PyAst, values: Vec<PyAst>) -> PyAst {
+ let kw = PyDict::new_bound(self.py);
+ kw.set_item("column", column.obj.bind(self.py)).unwrap();
+ kw.set_item("values", build_list(self.py, values)).unwrap();
+ self.build(&self.cls_pivot_column, &kw)
+ }
+ fn unpivot_column(
+ &self,
+ value_columns: PyAst,
+ name_columns: PyAst,
+ unpivot_values: Vec<PyAst>,
+ ) -> PyAst {
+ let kw = PyDict::new_bound(self.py);
+ kw.set_item("value_columns", value_columns.obj.bind(self.py))
+ .unwrap();
+ kw.set_item("name_columns", name_columns.obj.bind(self.py))
+ .unwrap();
+ kw.set_item("unpivot_values", build_list(self.py, unpivot_values))
+ .unwrap();
+ self.build(&self.cls_unpivot_column, &kw)
+ }
+ fn grouping_set(&self, exprs: Vec<PyAst>) -> PyAst {
+ let kw = PyDict::new_bound(self.py);
+ kw.set_item("exprs", build_list(self.py, exprs)).unwrap();
+ self.build(&self.cls_grouping_set, &kw)
+ }
+ fn hogqlx_tag(&self, kind: &str, attributes: Vec<PyAst>) -> PyAst {
+ let kw = PyDict::new_bound(self.py);
+ kw.set_item("kind", kind).unwrap();
+ kw.set_item("attributes", build_list(self.py, attributes))
+ .unwrap();
+ self.build(&self.cls_hogqlx_tag, &kw)
+ }
+ fn hogqlx_attribute(&self, name: &str, value: PyAst) -> PyAst {
+ let kw = PyDict::new_bound(self.py);
+ kw.set_item("name", name).unwrap();
+ kw.set_item("value", value.obj.bind(self.py)).unwrap();
+ self.build(&self.cls_hogqlx_attribute, &kw)
+ }
+ fn select_set_query(&self, initial: PyAst, subsequent: Vec<PyAst>) -> PyAst {
+ let kw = PyDict::new_bound(self.py);
+ kw.set_item("initial_select_query", initial.obj.bind(self.py))
+ .unwrap();
+ kw.set_item("subsequent_select_queries", build_list(self.py, subsequent))
+ .unwrap();
+ self.build(&self.cls_select_set_query, &kw)
+ }
+ fn window_expr_empty(&self) -> PyAst {
+ // `WindowExpr()` with all-defaults.
+ self.build(&self.cls_window_expr, &PyDict::new_bound(self.py))
+ }
+ fn window_frame_bound(&self, frame_type: &str, frame_value: PyAst) -> PyAst {
+ let kw = PyDict::new_bound(self.py);
+ kw.set_item("frame_type", frame_type).unwrap();
+ kw.set_item("frame_value", frame_value.obj.bind(self.py))
+ .unwrap();
+ self.build(&self.cls_window_frame_expr, &kw)
+ }
+ fn interpolate_expr(&self, expr: PyAst, value: Option<PyAst>) -> PyAst {
+ let kw = PyDict::new_bound(self.py);
+ kw.set_item("expr", expr.obj.bind(self.py)).unwrap();
+ if let Some(v) = value {
+ kw.set_item("value", v.obj.bind(self.py)).unwrap();
+ }
+ self.build(&self.cls_interpolate_expr, &kw)
+ }
+ fn limit_by_expr(&self, n: PyAst, exprs: Vec<PyAst>, offset_value: Option<PyAst>) -> PyAst {
+ let kw = PyDict::new_bound(self.py);
+ kw.set_item("n", n.obj.bind(self.py)).unwrap();
+ kw.set_item("exprs", build_list(self.py, exprs)).unwrap();
+ if let Some(o) = offset_value {
+ kw.set_item("offset_value", o.obj.bind(self.py)).unwrap();
+ }
+ self.build(&self.cls_limit_by_expr, &kw)
+ }
+ fn select_query_empty(&self) -> PyAst {
+ // `SelectQuery.select: list[Expr]` is required (no default) — passing nothing trips dataclass `__init__` validation. The parser fills the real value via `set_field("select", ...)` before the node leaves, so an empty list is a safe placeholder. Same idea for the other `_empty()` shell sites.
+ let kw = PyDict::new_bound(self.py);
+ kw.set_item("select", PyList::empty_bound(self.py)).unwrap();
+ self.build(&self.cls_select_query, &kw)
+ }
+ fn select_set_node(&self, select_query: PyAst, set_operator: Option<&str>) -> PyAst {
+ let kw = PyDict::new_bound(self.py);
+ kw.set_item("select_query", select_query.obj.bind(self.py))
+ .unwrap();
+ if let Some(op) = set_operator {
+ kw.set_item("set_operator", op).unwrap();
+ }
+ self.build(&self.cls_select_set_node, &kw)
+ }
+ fn sample_expr(&self, sample_value: PyAst, offset_value: Option<PyAst>) -> PyAst {
+ let kw = PyDict::new_bound(self.py);
+ kw.set_item("sample_value", sample_value.obj.bind(self.py))
+ .unwrap();
+ if let Some(o) = offset_value {
+ kw.set_item("offset_value", o.obj.bind(self.py)).unwrap();
+ }
+ self.build(&self.cls_sample_expr, &kw)
+ }
+ fn ratio_expr(&self, left: PyAst, right: Option<PyAst>) -> PyAst {
+ let kw = PyDict::new_bound(self.py);
+ kw.set_item("left", left.obj.bind(self.py)).unwrap();
+ if let Some(r) = right {
+ kw.set_item("right", r.obj.bind(self.py)).unwrap();
+ }
+ self.build(&self.cls_ratio_expr, &kw)
+ }
+ fn pivot_expr(
+ &self,
+ table: PyAst,
+ aggregates: Vec<PyAst>,
+ columns: Vec<PyAst>,
+ group_by: Option<Vec<PyAst>>,
+ ) -> PyAst {
+ let kw = PyDict::new_bound(self.py);
+ kw.set_item("table", table.obj.bind(self.py)).unwrap();
+ kw.set_item("aggregates", build_list(self.py, aggregates))
+ .unwrap();
+ kw.set_item("columns", build_list(self.py, columns))
+ .unwrap();
+ if let Some(g) = group_by {
+ kw.set_item("group_by", build_list(self.py, g)).unwrap();
+ }
+ self.build(&self.cls_pivot_expr, &kw)
+ }
+ fn unpivot_expr(&self, table: PyAst, columns: Vec<PyAst>, include_nulls: bool) -> PyAst {
+ let kw = PyDict::new_bound(self.py);
+ kw.set_item("table", table.obj.bind(self.py)).unwrap();
+ kw.set_item("columns", build_list(self.py, columns))
+ .unwrap();
+ kw.set_item("include_nulls", include_nulls).unwrap();
+ self.build(&self.cls_unpivot_expr, &kw)
+ }
+ fn join_expr(
+ &self,
+ table: PyAst,
+ alias: Option<String>,
+ table_args: Option<PyAst>,
+ column_aliases: Option<Vec<String>>,
+ table_final: bool,
+ sample: Option<PyAst>,
+ ) -> PyAst {
+ let kw = PyDict::new_bound(self.py);
+ kw.set_item("table", table.obj.bind(self.py)).unwrap();
+ if let Some(ta) = table_args {
+ kw.set_item("table_args", ta.obj.bind(self.py)).unwrap();
+ }
+ if let Some(a) = alias {
+ kw.set_item("alias", a).unwrap();
+ }
+ if table_final {
+ kw.set_item("table_final", true).unwrap();
+ }
+ if let Some(s) = sample {
+ kw.set_item("sample", s.obj.bind(self.py)).unwrap();
+ }
+ if let Some(ca) = column_aliases {
+ let l = PyList::empty_bound(self.py);
+ for s in ca {
+ l.append(s).unwrap();
+ }
+ kw.set_item("column_aliases", l).unwrap();
+ }
+ self.build(&self.cls_join_expr, &kw)
+ }
+ fn window_function(
+ &self,
+ name: &str,
+ exprs: Vec<PyAst>,
+ args: Vec<PyAst>,
+ over_expr: Option<PyAst>,
+ over_identifier: Option<String>,
+ ) -> PyAst {
+ let kw = PyDict::new_bound(self.py);
+ kw.set_item("name", name).unwrap();
+ kw.set_item("exprs", build_list(self.py, exprs)).unwrap();
+ kw.set_item("args", build_list(self.py, args)).unwrap();
+ if let Some(we) = over_expr {
+ kw.set_item("over_expr", we.obj.bind(self.py)).unwrap();
+ }
+ if let Some(id) = over_identifier {
+ kw.set_item("over_identifier", id).unwrap();
+ }
+ self.build(&self.cls_window_function, &kw)
+ }
+ fn with_fill_expr(
+ &self,
+ from_value: Option<PyAst>,
+ to_value: Option<PyAst>,
+ step_value: Option<PyAst>,
+ ) -> PyAst {
+ let kw = PyDict::new_bound(self.py);
+ if let Some(v) = from_value {
+ kw.set_item("from_value", v.obj.bind(self.py)).unwrap();
+ }
+ if let Some(v) = to_value {
+ kw.set_item("to_value", v.obj.bind(self.py)).unwrap();
+ }
+ if let Some(v) = step_value {
+ kw.set_item("step_value", v.obj.bind(self.py)).unwrap();
+ }
+ self.build(&self.cls_with_fill_expr, &kw)
+ }
+
+ // ===== Position machinery =====
+ fn position(&self, _line: u32, _column: u32, offset: usize) -> PyAst {
+ // Python AST `start` / `end` are `Optional[int]` — only the offset survives; lines/columns aren't carried on the dataclass. Pre-allocating the `Py<int>` here lets `with_pos` / `replace_pos` setattr via a `Bound` (fast IntoPy, no per-setattr int alloc).
+ self.wrap_prim(offset.into_py(self.py))
+ }
+ fn with_pos(&self, value: PyAst, start: PyAst, end: PyAst) -> PyAst {
+ if value.positions_locked {
+ return value;
+ }
+ let bound = value.obj.bind(self.py);
+ // `start` is only on AST dataclasses (via `AST` base); primitives (int / str / None) don't have it.
+ if let Ok(existing) = bound.getattr("start") {
+ if existing.is_none() {
+ bound.setattr("start", start.obj.bind(self.py)).unwrap();
+ bound.setattr("end", end.obj.bind(self.py)).unwrap();
+ }
+ }
+ value
+ }
+ fn no_pos(&self, mut value: PyAst) -> PyAst {
+ // `positions_locked` only blocks `with_pos` / `replace_pos` on AST dataclasses; primitives skip those paths already, so calling `no_pos` on one is a silent no-op. Debug-assert the precondition so a wrapper-less caller fails loud.
+ debug_assert!(
+ self.node_kind(&value).is_some(),
+ "no_pos called on a non-AST primitive — position suppression would be a no-op"
+ );
+ value.positions_locked = true;
+ value
+ }
+ fn replace_pos(&self, value: PyAst, start: PyAst, end: PyAst) -> PyAst {
+ if value.positions_locked {
+ return value;
+ }
+ let bound = value.obj.bind(self.py);
+ if bound.hasattr("start").unwrap_or(false) {
+ bound.setattr("start", start.obj.bind(self.py)).unwrap();
+ bound.setattr("end", end.obj.bind(self.py)).unwrap();
+ }
+ value
+ }
+
+ // ===== Inspection =====
+ fn node_kind<'a>(&self, v: &'a PyAst) -> Option<Cow<'a, str>> {
+ let bound = v.obj.bind(self.py);
+ // Plain primitives (int / str / None / list / dict / bool) aren't AST nodes — return None to match JsonEmitter. Probe `_visit_method_name` (every AST dataclass has it via `__init_subclass__`) — fast attr probe, no string parsing.
+ if !bound.hasattr("_visit_method_name").unwrap_or(false) {
+ return None;
+ }
+ let type_name = bound.get_type().qualname().ok()?;
+ Some(Cow::Owned(type_name.to_string()))
+ }
+ fn get_field(&self, v: &PyAst, name: &str) -> Option<PyAst> {
+ // Sentinel fields (`__rust_*`) live in the side-channel map — see `rust_sentinels` on `PyAst`.
+ if let Some(stored) = v.rust_sentinels.as_ref().and_then(|m| m.get(name)) {
+ return Some(PyAst {
+ obj: stored.clone_ref(self.py),
+ positions_locked: false,
+ rust_sentinels: None,
+ });
+ }
+ let bound = v.obj.bind(self.py);
+ let got = bound.getattr(name).ok()?;
+ // `ctes` is eagerly folded list->dict on write (see `set_field`); un-fold dict->list of values here so `inject_ctes_into_select`'s read-modify-write through `as_list` round-trips and the second `set_field` re-folds with all members. Mirrors JsonEmitter where ctes stays list-shaped during parsing.
+ if name == "ctes" {
+ if let Ok(dict) = got.downcast::<PyDict>() {
+ let list = PyList::empty_bound(self.py);
+ for (_, val) in dict.iter() {
+ list.append(val).unwrap();
+ }
+ return Some(PyAst {
+ obj: list.into_any().unbind(),
+ positions_locked: false,
+ rust_sentinels: None,
+ });
+ }
+ }
+ Some(PyAst {
+ obj: got.unbind(),
+ positions_locked: false,
+ rust_sentinels: None,
+ })
+ }
+ fn has_field(&self, v: &PyAst, name: &str) -> bool {
+ // JsonEmitter returns true iff the JSON Map has the key — only set when the parser emitted a non-default value.
+ // Python equivalent is "attribute exists AND is not None": slots=True dataclasses always declare every field as an attribute (even when default is None), so plain `hasattr` returns true for unset fields. The `not None` semantic matches JSON's "key exists" check for the parser's gating sites (wrap_pivot_chain's decoration check, the array-join FROM check).
+ if v.rust_sentinels
+ .as_ref()
+ .is_some_and(|m| m.contains_key(name))
+ {
+ return true;
+ }
+ let bound = v.obj.bind(self.py);
+ match bound.getattr(name) {
+ Ok(value) => !value.is_none(),
+ Err(_) => false,
+ }
+ }
+ fn is_null(&self, v: &PyAst) -> bool {
+ v.obj.is_none(self.py)
+ }
+ fn as_str<'a>(&self, v: &'a PyAst) -> Option<Cow<'a, str>> {
+ let bound = v.obj.bind(self.py);
+ bound.extract::<String>().ok().map(Cow::Owned)
+ }
+ fn as_list(&self, v: &PyAst) -> Option<Vec<PyAst>> {
+ let bound = v.obj.bind(self.py);
+ let list = bound.downcast::<PyList>().ok()?;
+ let mut out = Vec::with_capacity(list.len());
+ for item in list.iter() {
+ out.push(PyAst {
+ obj: item.unbind(),
+ positions_locked: false,
+ rust_sentinels: None,
+ });
+ }
+ Some(out)
+ }
+ fn as_bool(&self, v: &PyAst) -> Option<bool> {
+ // Match JsonEmitter's `Value::Bool` strictness; PyO3's `extract::<bool>` would accept ints (0 / 1) without the type gate.
+ let bound = v.obj.bind(self.py);
+ if bound.is_instance_of::<pyo3::types::PyBool>() {
+ bound.extract::<bool>().ok()
+ } else {
+ None
+ }
+ }
+ fn as_i64(&self, v: &PyAst) -> Option<i64> {
+ // Match JsonEmitter's `Value::Number` (booleans excluded); PyO3's `extract::<i64>` would coerce `True` to 1.
+ let bound = v.obj.bind(self.py);
+ if bound.is_instance_of::<pyo3::types::PyBool>() {
+ return None;
+ }
+ bound.extract::<i64>().ok()
+ }
+
+ // ===== Mutation =====
+ fn remove_field(&self, v: &mut PyAst, name: &str) -> Option<PyAst> {
+ // Sentinel fields live in the side-channel.
+ if let Some(prev) = v.rust_sentinels.as_mut().and_then(|m| m.remove(name)) {
+ return Some(PyAst {
+ obj: prev,
+ positions_locked: false,
+ rust_sentinels: None,
+ });
+ }
+ let bound = v.obj.bind(self.py);
+ let prev = bound.getattr(name).ok()?;
+ if prev.is_none() {
+ // Field already unset (slots=True keeps the attr bound but None) — treat as absent to match JSON's `as_object_mut().remove` returning None for missing keys.
+ return None;
+ }
+ // Replace with `None` so the field still exists (slots=True keeps it bound) but reads as missing semantically.
+ bound.setattr(name, self.py.None()).unwrap();
+ Some(PyAst {
+ obj: prev.unbind(),
+ positions_locked: false,
+ rust_sentinels: None,
+ })
+ }
+ fn set_field(&self, v: &mut PyAst, name: &str, value: PyAst) {
+ // Parser-internal sentinel fields (`__rust_*`) aren't on the dataclass; slots=True rejects setattr — route to the side-channel HashMap.
+ if name.starts_with("__rust_") {
+ v.sentinels_mut().insert(name.to_string(), value.obj);
+ return;
+ }
+ let bound = v.obj.bind(self.py);
+ // Dict-shaped AST fields (`_DICT_FIELDS` in `json_ast.py`): `ctes`, `replace`, `window_exprs`. The parser builds `ctes` as a list (see `inject_ctes_into_select`) and the JSON path folds list→dict in `json_ast.py::_deserialize_node`. PyEmitter has no post-walk, so we fold here using each item's `name` attribute (it's a `CTE`) as the dict key.
+ if name == "ctes" {
+ let val_bound = value.obj.bind(self.py);
+ if let Ok(list) = val_bound.downcast::<PyList>() {
+ let dict = PyDict::new_bound(self.py);
+ for item in list.iter() {
+ let cte_name = item
+ .getattr("name")
+ .expect("ctes list item missing `name` attribute");
+ dict.set_item(cte_name, &item).unwrap();
+ }
+ bound.setattr(name, dict).unwrap();
+ return;
+ }
+ }
+ bound.setattr(name, value.obj.bind(self.py)).unwrap();
+ // Re-fire `__post_init__` when writing a field whose validation lives there. The printer interpolates `join_type` / `order` / `constraint_type` / `set_operator` verbatim into emitted SQL and trusts the dataclass allow-list; the JSON path runs the check via `cls(**kwargs)`, but rust-py builds the node first and writes some of these fields post-construction (notably `join_type` via `chain_join`), so the check has to be re-driven here.
+ if matches!(
+ name,
+ "join_type" | "order" | "constraint_type" | "set_operator"
+ ) {
+ if let Ok(post_init) = bound.getattr("__post_init__") {
+ if let Err(py_err) = post_init.call0() {
+ // Panic with the inner Python message only (not the `PyErr` Debug repr); `run_py`'s `catch_unwind` converts the panic to a `ParseError::not_implemented` envelope.
+ let msg = py_err
+ .value_bound(self.py)
+ .str()
+ .ok()
+ .and_then(|s| s.to_str().ok().map(str::to_string))
+ .unwrap_or_else(|| "ast dataclass validation failed".to_string());
+ panic!("{msg}");
+ }
+ }
+ }
+ }
+}
+
+// ============================================================================
+// Helpers
+// ============================================================================
+
+fn build_list(py: Python<'_>, items: Vec<PyAst>) -> Bound<'_, PyList> {
+ let list = PyList::empty_bound(py);
+ for item in items {
+ list.append(item.obj).unwrap();
+ }
+ list
+}
diff --git a/rust/hogql/parser/src/error.rs b/rust/hogql/parser/src/error.rs
index 3c7497c26eeb..3e8544972359 100644
--- a/rust/hogql/parser/src/error.rs
+++ b/rust/hogql/parser/src/error.rs
@@ -25,12 +25,6 @@ pub struct ParseError {
}
#[derive(Debug, Clone, Copy)]
-#[allow(dead_code)] // `NotImplemented` is reserved for future
- // deferred-feature stubs (e.g. when new grammar
- // rules land in cpp that this parser hasn't
- // caught up to yet) — keep the variant + helper
- // around so callers can opt back in without
- // adding back the enum case.
pub enum ErrorKind {
Syntax,
NotImplemented,
@@ -56,8 +50,6 @@ impl ParseError {
}
}
- #[allow(dead_code)] // Reserved for deferred-feature stubs; see
- // `ErrorKind` for context.
pub fn not_implemented(message: impl Into<String>, start: usize, end: usize) -> Self {
Self {
message: message.into(),
@@ -68,8 +60,7 @@ impl ParseError {
}
}
- /// Like `not_implemented`, but marks the error fatal so `try_alt`
- /// short-circuits and doesn't fall back to the next alternative.
+ /// Like `not_implemented`, but marks the error fatal so `try_alt` short-circuits and doesn't fall back to the next alternative.
pub fn not_implemented_fatal(message: impl Into<String>, start: usize, end: usize) -> Self {
Self {
message: message.into(),
@@ -80,16 +71,22 @@ impl ParseError {
}
}
- pub fn to_json_string(&self) -> String {
- let value = json!({
+ /// Build the JSON error envelope shape. Used directly by the `parse_*_py`
+ /// path (which raises a Python exception from this) and serialised to a
+ /// string by [`Self::to_json_string`] for the `parse_*_json` path.
+ pub fn to_json_value(&self) -> serde_json::Value {
+ json!({
"error": true,
"type": self.kind.type_str(),
"message": self.message,
"start": {"offset": self.start},
"end": {"offset": self.end},
- });
+ })
+ }
+
+ pub fn to_json_string(&self) -> String {
// serde_json::to_string never fails for a Value, but be explicit.
- serde_json::to_string(&value).unwrap_or_else(|_| {
+ serde_json::to_string(&self.to_json_value()).unwrap_or_else(|_| {
r#"{"error":true,"type":"InternalError","message":"failed to serialize error envelope","start":{"offset":0},"end":{"offset":0}}"#.to_string()
})
}
diff --git a/rust/hogql/parser/src/lib.rs b/rust/hogql/parser/src/lib.rs
index d057328f27ad..f41abe3c23eb 100644
--- a/rust/hogql/parser/src/lib.rs
+++ b/rust/hogql/parser/src/lib.rs
@@ -13,12 +13,18 @@
//! envelope expected by [`posthog/hogql/json_ast.py`] so the Python side
//! can raise `ExposedHogQLError` / `SyntaxError` from it.
+// `#[pyfunction]`'s expansion does an `.into()` on the `PyResult<PyObject>` return value, which is an identity conversion when the function already returns the target type — clippy's `useless_conversion` doesn't see through the macro and would flag every `parse_*_py` entry point. The lint isn't actionable from our side without leaving pyo3's `#[pyfunction]` abstraction.
+#![allow(clippy::useless_conversion)]
+
use pyo3::prelude::*;
+use std::panic::AssertUnwindSafe;
mod emit;
+mod emit_py;
mod error;
mod lex;
mod parse;
+mod pyobject;
fn run<F>(f: F) -> String
where
@@ -26,14 +32,46 @@ where
{
match f() {
Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| {
- // serde_json::Value -> string never fails in practice, but emit
- // a structured error rather than panicking across the FFI.
+ // serde_json::Value -> string never fails in practice, but emit a structured error rather than panic across the FFI.
error::ParseError::syntax("internal: failed to serialize AST", 0, 0).to_json_string()
}),
Err(err) => err.to_json_string(),
}
}
+/// Counterpart to [`run`] for `parse_*_py` entry points: drive a `PyEmitter` so the parser constructs `posthog.hogql.ast` instances directly, returning the unbound `Py<PyAny>`. Skips both the JSON-string serialise step AND the post-walk `Value`→`PyObject` converter used by the `*_json` entry points — no `serde_json::Value` intermediate on the success path.
+///
+/// Error path still routes through the JSON-envelope `Converter` so Python exception construction stays in one place.
+fn run_py<'py, F>(py: Python<'py>, f: F) -> PyResult<PyObject>
+where
+ F: FnOnce(emit_py::PyEmitter<'py>) -> Result<emit_py::PyAst, error::ParseError>,
+{
+ let emitter = emit_py::PyEmitter::new(py)?;
+ // Convert any panic from the emitter drive (e.g. `class(**kwargs)` tripping dataclass `__post_init__`) into a `NotImplementedError` envelope. PyO3 would surface it as `PanicException`, which production callers catching the `ExposedHogQLError` family won't intercept.
+ let outcome = std::panic::catch_unwind(AssertUnwindSafe(|| f(emitter)));
+ let result = match outcome {
+ Ok(r) => r,
+ Err(panic) => {
+ let msg = panic
+ .downcast_ref::<&'static str>()
+ .copied()
+ .map(str::to_string)
+ .or_else(|| panic.downcast_ref::<String>().cloned())
+ .unwrap_or_else(|| "ast construction panicked".to_string());
+ Err(error::ParseError::not_implemented(msg, 0, 0))
+ }
+ };
+ match result {
+ Ok(v) => Ok(v.obj),
+ Err(err) => {
+ // Build the JSON error envelope so the converter raises the matching Python exception with start/end positions — one code path for both error sources.
+ let value = err.to_json_value();
+ let converter = pyobject::Converter::new(py)?;
+ converter.convert_root(&value)
+ }
+ }
+}
+
#[pyfunction]
#[pyo3(signature = (statement, is_internal=false))]
fn parse_expr_json(statement: &str, is_internal: bool) -> String {
@@ -60,6 +98,40 @@ fn parse_full_template_string_json(string: &str) -> String {
run(|| parse::parse_full_template_string(string))
}
+// `parse_*_py` mirror the `_json` entry points but return Python ast dataclass instances directly, skipping the JSON serialise/deserialise round-trip on both sides. The `_json` versions stay alongside for the future WASM build and for tests that compare on JSON shape.
+
+#[pyfunction]
+#[pyo3(signature = (statement, is_internal=false))]
+fn parse_expr_py(py: Python<'_>, statement: &str, is_internal: bool) -> PyResult<PyObject> {
+ run_py(py, |emit| {
+ parse::parse_expr_with_emit(emit, statement, is_internal)
+ })
+}
+
+#[pyfunction]
+fn parse_order_expr_py(py: Python<'_>, statement: &str) -> PyResult<PyObject> {
+ run_py(py, |emit| {
+ parse::parse_order_expr_with_emit(emit, statement)
+ })
+}
+
+#[pyfunction]
+fn parse_select_py(py: Python<'_>, statement: &str) -> PyResult<PyObject> {
+ run_py(py, |emit| parse::parse_select_with_emit(emit, statement))
+}
+
+#[pyfunction]
+fn parse_program_py(py: Python<'_>, source: &str) -> PyResult<PyObject> {
+ run_py(py, |emit| parse::parse_program_with_emit(emit, source))
+}
+
+#[pyfunction]
+fn parse_full_template_string_py(py: Python<'_>, string: &str) -> PyResult<PyObject> {
+ run_py(py, |emit| {
+ parse::parse_full_template_string_with_emit(emit, string)
+ })
+}
+
#[pymodule]
fn hogql_parser_rs(m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_function(wrap_pyfunction!(parse_expr_json, m)?)?;
@@ -67,5 +139,10 @@ fn hogql_parser_rs(m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_function(wrap_pyfunction!(parse_select_json, m)?)?;
m.add_function(wrap_pyfunction!(parse_program_json, m)?)?;
m.add_function(wrap_pyfunction!(parse_full_template_string_json, m)?)?;
+ m.add_function(wrap_pyfunction!(parse_expr_py, m)?)?;
+ m.add_function(wrap_pyfunction!(parse_order_expr_py, m)?)?;
+ m.add_function(wrap_pyfunction!(parse_select_py, m)?)?;
+ m.add_function(wrap_pyfunction!(parse_program_py, m)?)?;
+ m.add_function(wrap_pyfunction!(parse_full_template_string_py, m)?)?;
Ok(())
}
diff --git a/rust/hogql/parser/src/parse.rs b/rust/hogql/parser/src/parse.rs
index 85a4f0d4191f..1d56a7fedb90 100644
--- a/rust/hogql/parser/src/parse.rs
+++ b/rust/hogql/parser/src/parse.rs
@@ -13,7 +13,7 @@
use serde_json::Value;
-use crate::emit;
+use crate::emit::{Emitter, JsonEmitter};
use crate::error::ParseError;
use crate::lex::{Kw, Lexer, Token, TokenKind};
@@ -37,8 +37,16 @@ use template::parse_template_body;
// Public entry points
// ============================================================================
-pub fn parse_expr(src: &str, _is_internal: bool) -> Result<Value, ParseError> {
- let mut p = Parser::new(src)?;
+pub fn parse_expr(src: &str, is_internal: bool) -> Result<Value, ParseError> {
+ parse_expr_with_emit(JsonEmitter, src, is_internal)
+}
+
+pub fn parse_expr_with_emit<E: Emitter + Clone>(
+ emit: E,
+ src: &str,
+ _is_internal: bool,
+) -> Result<E::Value, ParseError> {
+ let mut p = Parser::new_with_emit(src, emit)?;
// Bare-list lambda `IDENT (, IDENT)* -> body` is only valid at the
// outermost expression level; inside an argument list each item parses
// independently and the commas are separators. So we try it here
@@ -62,7 +70,14 @@ pub fn parse_expr(src: &str, _is_internal: bool) -> Result<Value, ParseError> {
}
pub fn parse_order_expr(src: &str) -> Result<Value, ParseError> {
- let mut p = Parser::new(src)?;
+ parse_order_expr_with_emit(JsonEmitter, src)
+}
+
+pub fn parse_order_expr_with_emit<E: Emitter + Clone>(
+ emit: E,
+ src: &str,
+) -> Result<E::Value, ParseError> {
+ let mut p = Parser::new_with_emit(src, emit)?;
let exprs = p.parse_order_expr_list()?;
// cpp's `parse_order_expr_json` entry point silently drops any
// trailing tokens after the first OrderExpr — `a ASC extra` parses
@@ -79,7 +94,14 @@ pub fn parse_order_expr(src: &str) -> Result<Value, ParseError> {
}
pub fn parse_select(src: &str) -> Result<Value, ParseError> {
- let mut p = Parser::new(src)?;
+ parse_select_with_emit(JsonEmitter, src)
+}
+
+pub fn parse_select_with_emit<E: Emitter + Clone>(
+ emit: E,
+ src: &str,
+) -> Result<E::Value, ParseError> {
+ let mut p = Parser::new_with_emit(src, emit)?;
// `select` rule top-level admits a bare HogQLX tag element as the
// third alternative (alongside selectSetStmt / selectStmt). The tag
// covers both standalone-`<Tag />` use and the `from <Tag />` shape
@@ -95,13 +117,27 @@ pub fn parse_select(src: &str) -> Result<Value, ParseError> {
}
pub fn parse_program(src: &str) -> Result<Value, ParseError> {
- let mut p = Parser::new(src)?;
+ parse_program_with_emit(JsonEmitter, src)
+}
+
+pub fn parse_program_with_emit<E: Emitter + Clone>(
+ emit: E,
+ src: &str,
+) -> Result<E::Value, ParseError> {
+ let mut p = Parser::new_with_emit(src, emit)?;
let prog = p.parse_program()?;
p.expect_eof()?;
Ok(prog)
}
pub fn parse_full_template_string(src: &str) -> Result<Value, ParseError> {
+ parse_full_template_string_with_emit(JsonEmitter, src)
+}
+
+pub fn parse_full_template_string_with_emit<E: Emitter + Clone>(
+ emit: E,
+ src: &str,
+) -> Result<E::Value, ParseError> {
// The Python wrapper `parse_string_template` prepends `F'` to the
// template body before handing the source off to either backend
// (see `posthog/hogql/parser.py::parse_string_template`). Strip
@@ -117,14 +153,17 @@ pub fn parse_full_template_string(src: &str) -> Result<Value, ParseError> {
// `body_offset` and `body_end`. For the standalone entry point the
// body extends to the end of `src` — there is no trailing `'`.
let body_end = src.len();
- parse_template_body(src, body_offset, body_end)
+ parse_template_body(&emit, src, body_offset, body_end)
}
// ============================================================================
// Parser core
// ============================================================================
-pub(crate) struct Parser<'a> {
+/// Recursion-depth cap for `parse_expr_bp`. Mirrors ClickHouse's `max_parser_depth` default (1000) so deeply-nested input (e.g. `((((…))))`) surfaces a clean `ParseError::syntax` instead of stack-OOMing the worker before any parse error can fire.
+pub(crate) const MAX_EXPR_RECURSION_DEPTH: u32 = 1000;
+
+pub(crate) struct Parser<'a, E: Emitter = JsonEmitter> {
pub(crate) src: &'a str,
pub(crate) lexer: Lexer<'a>,
/// One-token-ahead cursor. We carry a second peek for the few
@@ -240,17 +279,21 @@ pub(crate) struct Parser<'a> {
/// once at construction so the hot wrap_pos path stays O(log n) via the
/// line-starts binary search.
pub(crate) is_ascii_src: bool,
+ /// Live `parse_expr_bp` recursion depth; bumped on entry, decremented on exit. Enforces `MAX_EXPR_RECURSION_DEPTH`.
+ pub(crate) expr_recursion_depth: u32,
+ /// AST node builder. Routes every node/position construction through the `Emitter` trait so we can swap `JsonEmitter` (current default, kept for WASM) for `PyEmitter` (constructs Python ast.* objects directly, avoiding the `serde_json::Value` intermediate). See `crate::emit`.
+ pub(crate) emit: E,
}
-impl<'a> Parser<'a> {
- pub(crate) fn new(src: &'a str) -> Result<Self, ParseError> {
- Self::with_pos(src, 0)
+impl<'a, E: Emitter + Clone> Parser<'a, E> {
+ pub(crate) fn new_with_emit(src: &'a str, emit: E) -> Result<Self, ParseError> {
+ Self::with_pos_emit(src, 0, emit)
}
/// Construct a Parser whose lexer starts at the given byte offset.
/// Used by the template-body splitter to parse a `{ … }` expression
/// block without lexing the literal text on either side.
- pub(crate) fn with_pos(src: &'a str, pos: usize) -> Result<Self, ParseError> {
+ pub(crate) fn with_pos_emit(src: &'a str, pos: usize, emit: E) -> Result<Self, ParseError> {
let mut lexer = Lexer::with_pos(src, pos);
let peek0 = lexer.next_token()?;
let peek1 = lexer.next_token()?;
@@ -274,9 +317,21 @@ impl<'a> Parser<'a> {
line_starts,
char_offsets: std::cell::OnceCell::new(),
is_ascii_src,
+ expr_recursion_depth: 0,
+ emit,
})
}
+}
+/// Test-only convenience: the JsonEmitter-bound `Parser::new(src)` form. Production code routes through `parse_<rule>_with_emit` (which uses `new_with_emit`) so this only has callers inside the `#[cfg(test)] mod tests` below.
+#[cfg(test)]
+impl<'a> Parser<'a, JsonEmitter> {
+ pub(crate) fn new(src: &'a str) -> Result<Self, ParseError> {
+ Self::new_with_emit(src, JsonEmitter)
+ }
+}
+
+impl<'a, E: Emitter + Clone> Parser<'a, E> {
pub(crate) fn peek(&self) -> TokenKind {
self.peek0.kind
}
@@ -381,13 +436,13 @@ impl<'a> Parser<'a> {
/// ANTLR `getStartIndex()` / `getCharPositionInLine()` are
/// character-based, so byte offsets need converting through `src`
/// slicing for any source containing non-ASCII bytes.
- pub(crate) fn pos_obj(&self, byte_offset: usize) -> Value {
+ pub(crate) fn pos_obj(&self, byte_offset: usize) -> E::Value {
let (line, byte_col, line_start_byte) = offset_to_line_col(&self.line_starts, byte_offset);
// ASCII fast path: byte == char in every dimension. Avoid the
// `byte_to_char_index` binary search and the line-slice chars
// count entirely.
if self.is_ascii_src {
- return emit::position(line, byte_col, byte_offset);
+ return self.emit.position(line, byte_col, byte_offset);
}
let char_offset = self.byte_to_char_index(byte_offset);
// Column needs to be characters-in-line, not bytes-in-line. For
@@ -398,7 +453,7 @@ impl<'a> Parser<'a> {
} else {
self.src[line_start_byte..byte_offset].chars().count() as u32
};
- emit::position(line, column, char_offset)
+ self.emit.position(line, column, char_offset)
}
/// Convert a byte offset into the source into a character (Unicode
@@ -430,19 +485,19 @@ impl<'a> Parser<'a> {
/// `last_consumed_end` (the end of the last token consumed). The
/// canonical wrap-on-return helper for every `parse_*` fn that emits
/// an AST node.
- pub(crate) fn wrap_pos(&self, value: Value, start: usize) -> Value {
+ pub(crate) fn wrap_pos(&self, value: E::Value, start: usize) -> E::Value {
let s = self.pos_obj(start);
let e = self.pos_obj(self.last_consumed_end);
- emit::with_pos(value, s, e)
+ self.emit.with_pos(value, s, e)
}
/// Variant of [`Self::wrap_pos`] that takes an explicit end offset —
/// used when the natural end of the node isn't `last_consumed_end`
/// (e.g. composite chain re-tagged with the rightmost child's end).
- pub(crate) fn wrap_pos_to(&self, value: Value, start: usize, end: usize) -> Value {
+ pub(crate) fn wrap_pos_to(&self, value: E::Value, start: usize, end: usize) -> E::Value {
let s = self.pos_obj(start);
let e = self.pos_obj(end);
- emit::with_pos(value, s, e)
+ self.emit.with_pos(value, s, e)
}
/// Like [`Self::wrap_pos_to`] but overrides any existing `start` /
@@ -450,10 +505,10 @@ impl<'a> Parser<'a> {
/// tokens that the outer grammar rule includes — e.g. cpp's
/// `ColumnExprColumnsReplace` ctx covers the outer parens but the
/// inner ColumnsExpr was wrapped at the `*` position only.
- pub(crate) fn replace_pos_to(&self, value: Value, start: usize, end: usize) -> Value {
+ pub(crate) fn replace_pos_to(&self, value: E::Value, start: usize, end: usize) -> E::Value {
let s = self.pos_obj(start);
let e = self.pos_obj(end);
- emit::replace_pos(value, s, e)
+ self.emit.replace_pos(value, s, e)
}
/// Snapshot the parser cursor + per-call context so a failed
@@ -553,7 +608,8 @@ impl<'a> Parser<'a> {
/// is the bounded-backtrack analogue of ANTLR's adaptive LL
/// prediction without the DFA cache. For our grammar's decision
/// points the wasted work is bounded by the arm depth.
- #[allow(dead_code, clippy::type_complexity)]
+ #[cfg(test)]
+ #[allow(clippy::type_complexity)]
pub(crate) fn try_alt_with_followup<T, F>(
&mut self,
alts: &[&dyn Fn(&mut Self) -> Result<T, ParseError>],
@@ -644,9 +700,9 @@ fn parse_hex_float_value(rest: &str) -> f64 {
/// Emit a finite float as a numeric Constant, or `±Infinity` / `NaN`
/// when the value isn't finite — mirrors cpp's `stod` result (and its
/// `out_of_range` → `±Infinity` fallthrough).
-fn emit_float_constant(f: f64) -> Value {
+fn emit_float_constant<E: Emitter>(emit: &E, f: f64) -> E::Value {
if !f.is_finite() {
- return emit::constant_special_number(if f.is_nan() {
+ return emit.constant_special_number(if f.is_nan() {
"NaN"
} else if f > 0.0 {
"Infinity"
@@ -654,14 +710,14 @@ fn emit_float_constant(f: f64) -> Value {
"-Infinity"
});
}
- emit::constant(
- serde_json::Number::from_f64(f)
- .map(Value::Number)
- .unwrap_or(Value::Null),
- )
+ emit.constant(emit.float(f))
}
-pub(crate) fn parse_number_literal(src: &str, negative: bool) -> Result<Value, ParseError> {
+pub(crate) fn parse_number_literal<E: Emitter>(
+ emit: &E,
+ src: &str,
+ negative: bool,
+) -> Result<E::Value, ParseError> {
// Hex literal — `0x…`. Three cases:
// - Contains `p`/`P`: hex-float (`FLOATING_LITERAL` strict C99
// `HEX (DOT HEX*)? P [+-]? DEC+`). Parse to f64 — Rust's f64
@@ -673,7 +729,7 @@ pub(crate) fn parse_number_literal(src: &str, negative: bool) -> Result<Value, P
if let Some(rest) = src.strip_prefix("0x").or_else(|| src.strip_prefix("0X")) {
if rest.bytes().any(|b| b == b'p' || b == b'P') {
let f = parse_hex_float_value(rest);
- return Ok(emit_float_constant(if negative { -f } else { f }));
+ return Ok(emit_float_constant(emit, if negative { -f } else { f }));
}
let signed = if negative {
format!("-{rest}")
@@ -681,14 +737,14 @@ pub(crate) fn parse_number_literal(src: &str, negative: bool) -> Result<Value, P
rest.to_string()
};
match i64::from_str_radix(&signed, 16) {
- Ok(n) => return Ok(emit::constant(Value::from(n))),
+ Ok(n) => return Ok(emit.constant(emit.int(n))),
Err(_) => {
let lit = if negative {
format!("-{src}")
} else {
src.to_string()
};
- return Ok(emit::constant_number_string(lit));
+ return Ok(emit.constant_number_string(lit));
}
}
}
@@ -739,12 +795,12 @@ pub(crate) fn parse_number_literal(src: &str, negative: bool) -> Result<Value, P
} else {
-(magnitude as i64)
};
- return Ok(emit::constant(Value::from(v)));
+ return Ok(emit.constant(emit.int(v)));
}
// Positive: `Value::from(u64)` emits the exact magnitude as a
// JSON number — for magnitude > i64::MAX this preserves the
// full unsigned value (cpp emits the same via Json::raw).
- return Ok(emit::constant(Value::from(magnitude)));
+ return Ok(emit.constant(emit.uint(magnitude)));
}
// cpp 1.3.45's `VISIT(NumberLiteral)` parses integer text with
// `stoll(text, nullptr, 10)` — base 10, NOT base-0 auto-detect.
@@ -756,7 +812,7 @@ pub(crate) fn parse_number_literal(src: &str, negative: bool) -> Result<Value, P
let is_float = src.contains('.') || src.contains('e') || src.contains('E');
if is_float {
let f: f64 = src.parse().unwrap_or(0.0);
- return Ok(emit_float_constant(if negative { -f } else { f }));
+ return Ok(emit_float_constant(emit, if negative { -f } else { f }));
}
// Integer. The signed text carries the sign so
// `-9223372036854775808` (i64::MIN) parses exactly. A literal
@@ -768,8 +824,8 @@ pub(crate) fn parse_number_literal(src: &str, negative: bool) -> Result<Value, P
src.to_string()
};
match signed.parse::<i64>() {
- Ok(i) => Ok(emit::constant(Value::from(i))),
- Err(_) => Ok(emit::constant_number_string(signed)),
+ Ok(i) => Ok(emit.constant(emit.int(i))),
+ Err(_) => Ok(emit.constant_number_string(signed)),
}
}
@@ -992,35 +1048,40 @@ pub(crate) fn kw_acts_as_ident_in_primary(kw: Kw) -> bool {
/// **appends** the outer CTEs after any existing inner CTEs — so if the
/// inner already has `WITH a AS ...`, the outer's CTEs come *after* `a`
/// in declaration order. Match that.
-pub(crate) fn inject_ctes_into_select(node: &mut Value, ctes: Vec<Value>) {
- let mut cursor: &mut Value = node;
- loop {
- let Some(obj) = cursor.as_object_mut() else {
- return;
- };
- match obj.get("node").and_then(Value::as_str) {
+pub(crate) fn inject_ctes_into_select<E: Emitter>(
+ emit: &E,
+ node: &mut E::Value,
+ ctes: Vec<E::Value>,
+) {
+ // Walk to the inner SelectQuery; the outer wrapper may be a
+ // SelectSetQuery that holds the SelectQuery in its
+ // `initial_select_query` slot. The walk uses owned recursion via
+ // get_field + set_field, mirroring chain_join's pattern (no
+ // mutable cursors into nested values for abstract E::Value).
+ fn walk<E: Emitter>(emit: &E, mut node: E::Value, ctes: Vec<E::Value>) -> E::Value {
+ match emit.node_kind(&node).as_deref() {
Some("SelectQuery") => {
- match obj.get_mut("ctes") {
- Some(existing) if existing.is_array() => {
- if let Some(arr) = existing.as_array_mut() {
- arr.extend(ctes);
- }
- }
- _ => {
- obj.insert("ctes".into(), Value::Array(ctes));
- }
- }
- return;
+ let existing = emit
+ .get_field(&node, "ctes")
+ .and_then(|v| emit.as_list(&v))
+ .unwrap_or_default();
+ let mut combined = existing;
+ combined.extend(ctes);
+ emit.set_field(&mut node, "ctes", emit.list_value(combined));
+ node
}
Some("SelectSetQuery") => {
- let Some(inner) = obj.get_mut("initial_select_query") else {
- return;
- };
- cursor = inner;
+ if let Some(inner) = emit.get_field(&node, "initial_select_query") {
+ let updated = walk(emit, inner, ctes);
+ emit.set_field(&mut node, "initial_select_query", updated);
+ }
+ node
}
- _ => return,
+ _ => node,
}
}
+ let owned = std::mem::replace(node, emit.null());
+ *node = walk(emit, owned, ctes);
}
/// Format a set operator from its base + modifier + by_name. Mirrors the
@@ -1049,26 +1110,27 @@ pub(crate) fn format_set_op(base: &str, modifier: Option<&str>, by_name: bool) -
/// SELECT/SelectSetQuery node. When the target is a SelectSetQuery they
/// land on the wrapper; for a single SelectQuery they merge into its
/// existing fields. We pass through whatever shape we have.
-pub(crate) fn merge_select_decorators(mut node: Value, decorators: Vec<(String, Value)>) -> Value {
+pub(crate) fn merge_select_decorators<E: Emitter>(
+ emit: &E,
+ mut node: E::Value,
+ decorators: Vec<(String, E::Value)>,
+) -> E::Value {
if decorators.is_empty() {
return node;
}
- if let Some(obj) = node.as_object_mut() {
- for (k, v) in decorators {
- // Clobber pre-existing values on the inner SelectQuery —
- // cpp's `VISIT(SelectSetStmt)` walks the inner select
- // first, then the trailing `orderByClause` /
- // `limitAndOffsetClauseOptional`, so later writes (the SET
- // level) overwrite earlier ones (the inner STMT level).
- // A `Value::Null` is a sentinel for "remove this key" —
- // the SET-level visitor writes all four limit-related
- // fields, clearing the inner's `offset` even when the
- // outer clause has no OFFSET of its own.
- if v.is_null() {
- obj.remove(&k);
- } else {
- obj.insert(k, v);
- }
+ for (k, v) in decorators {
+ // Clobber pre-existing values on the inner SelectQuery —
+ // cpp's `VISIT(SelectSetStmt)` walks the inner select first,
+ // then the trailing `orderByClause` / `limitAndOffsetClauseOptional`,
+ // so later writes (the SET level) overwrite earlier ones (the
+ // inner STMT level). A null value is a sentinel for "remove
+ // this key" — the SET-level visitor writes all four limit-related
+ // fields, clearing the inner's `offset` even when the outer
+ // clause has no OFFSET of its own.
+ if emit.is_null(&v) {
+ emit.remove_field(&mut node, &k);
+ } else {
+ emit.set_field(&mut node, &k, v);
}
}
node
@@ -1077,38 +1139,38 @@ pub(crate) fn merge_select_decorators(mut node: Value, decorators: Vec<(String,
/// Build / extend a JoinExpr chain. `left` is the existing chain root; we
/// walk down its `next_join` pointers and attach `right` (carrying its
/// `join_type` + `constraint`) at the tail.
-pub(crate) fn chain_join(
- mut left: Value,
- mut right: Value,
+pub(crate) fn chain_join<E: Emitter>(
+ emit: &E,
+ left: E::Value,
+ mut right: E::Value,
join_type: &str,
- constraint: Option<Value>,
-) -> Value {
- if let Some(obj) = right.as_object_mut() {
- obj.insert("join_type".into(), Value::String(join_type.into()));
- if let Some(c) = constraint {
- obj.insert("constraint".into(), c);
- }
+ constraint: Option<E::Value>,
+) -> E::Value {
+ let jt = emit.string(join_type);
+ emit.set_field(&mut right, "join_type", jt);
+ if let Some(c) = constraint {
+ emit.set_field(&mut right, "constraint", c);
}
- // Walk to the tail of `left`'s next_join chain.
- {
- let mut cursor: &mut Value = &mut left;
- loop {
- let next_exists = cursor
- .as_object()
- .and_then(|o| o.get("next_join"))
- .map(|v| !v.is_null())
- .unwrap_or(false);
- if !next_exists {
- break;
- }
- let obj = cursor.as_object_mut().unwrap();
- cursor = obj.get_mut("next_join").unwrap();
- }
- if let Some(obj) = cursor.as_object_mut() {
- obj.insert("next_join".into(), right);
+ // Walk to the tail of `left`'s next_join chain. With abstract
+ // E::Value we can't recurse with `&mut` cursors (no `as_object_mut`),
+ // so unwind via owned recursion: pop the existing next_join, recurse
+ // to append, then put it back.
+ fn append_at_tail<E: Emitter>(emit: &E, mut node: E::Value, new_tail: E::Value) -> E::Value {
+ let has_next = emit
+ .get_field(&node, "next_join")
+ .map(|v| !emit.is_null(&v))
+ .unwrap_or(false);
+ if !has_next {
+ emit.set_field(&mut node, "next_join", new_tail);
+ return node;
}
+ // Move the existing next_join out, recurse with it, set it back.
+ let existing = emit.get_field(&node, "next_join").expect("just checked");
+ let updated = append_at_tail(emit, existing, new_tail);
+ emit.set_field(&mut node, "next_join", updated);
+ node
}
- left
+ append_at_tail(emit, left, right)
}
/// Map an INTERVAL unit name (e.g. "month") to the call name the C++
diff --git a/rust/hogql/parser/src/parse/bp.rs b/rust/hogql/parser/src/parse/bp.rs
index 458bb907831d..9f43541232e9 100644
--- a/rust/hogql/parser/src/parse/bp.rs
+++ b/rust/hogql/parser/src/parse/bp.rs
@@ -4,9 +4,9 @@
//! other module reads them through `pub(super)` re-exports rather than
//! hard-coding numbers. Higher value = tighter binding.
-use serde_json::Value;
+use std::borrow::Cow;
-use crate::emit;
+use crate::emit::Emitter;
use crate::lex::{Kw, TokenKind};
pub(super) const BP_ALIAS: u8 = 10;
@@ -30,7 +30,6 @@ pub(super) const BP_IGNORE_NULLS: u8 = 87;
pub(super) const BP_COMPARE: u8 = 90;
pub(super) const BP_ADDITIVE: u8 = 100;
pub(super) const BP_MULT: u8 = 110;
-#[allow(dead_code)]
pub(super) const BP_UNARY_MINUS: u8 = 120;
pub(super) const BP_POSTFIX: u8 = 130;
@@ -94,27 +93,32 @@ pub(super) fn postfix_bp(kind: TokenKind) -> Option<u8> {
}
}
-pub(super) fn build_infix(op: InfixOp, lhs: Value, rhs: Value) -> Value {
+pub(super) fn build_infix<E: Emitter>(
+ emit: &E,
+ op: InfixOp,
+ lhs: E::Value,
+ rhs: E::Value,
+) -> E::Value {
match op {
- InfixOp::Mul => emit::arith(lhs, "*", rhs),
- InfixOp::Div => emit::arith(lhs, "/", rhs),
- InfixOp::Mod => emit::arith(lhs, "%", rhs),
- InfixOp::Add => emit::arith(lhs, "+", rhs),
- InfixOp::Sub => emit::arith(lhs, "-", rhs),
- InfixOp::Concat => merge_concat(lhs, rhs),
- InfixOp::Eq => emit::compare(lhs, "==", rhs),
- InfixOp::NotEq => emit::compare(lhs, "!=", rhs),
- InfixOp::Lt => emit::compare(lhs, "<", rhs),
- InfixOp::LtEq => emit::compare(lhs, "<=", rhs),
- InfixOp::Gt => emit::compare(lhs, ">", rhs),
- InfixOp::GtEq => emit::compare(lhs, ">=", rhs),
- InfixOp::Regex => emit::compare(lhs, "=~", rhs),
- InfixOp::IRegex => emit::compare(lhs, "=~*", rhs),
- InfixOp::NotRegex => emit::compare(lhs, "!~", rhs),
- InfixOp::NotIRegex => emit::compare(lhs, "!~*", rhs),
- InfixOp::And => merge_and_or("And", lhs, rhs),
- InfixOp::Or => merge_and_or("Or", lhs, rhs),
- InfixOp::Nullish => emit::call("ifNull", vec![lhs, rhs]),
+ InfixOp::Mul => emit.arith(lhs, "*", rhs),
+ InfixOp::Div => emit.arith(lhs, "/", rhs),
+ InfixOp::Mod => emit.arith(lhs, "%", rhs),
+ InfixOp::Add => emit.arith(lhs, "+", rhs),
+ InfixOp::Sub => emit.arith(lhs, "-", rhs),
+ InfixOp::Concat => merge_concat(emit, lhs, rhs),
+ InfixOp::Eq => emit.compare(lhs, "==", rhs),
+ InfixOp::NotEq => emit.compare(lhs, "!=", rhs),
+ InfixOp::Lt => emit.compare(lhs, "<", rhs),
+ InfixOp::LtEq => emit.compare(lhs, "<=", rhs),
+ InfixOp::Gt => emit.compare(lhs, ">", rhs),
+ InfixOp::GtEq => emit.compare(lhs, ">=", rhs),
+ InfixOp::Regex => emit.compare(lhs, "=~", rhs),
+ InfixOp::IRegex => emit.compare(lhs, "=~*", rhs),
+ InfixOp::NotRegex => emit.compare(lhs, "!~", rhs),
+ InfixOp::NotIRegex => emit.compare(lhs, "!~*", rhs),
+ InfixOp::And => merge_and_or(emit, "And", lhs, rhs),
+ InfixOp::Or => merge_and_or(emit, "Or", lhs, rhs),
+ InfixOp::Nullish => emit.call("ifNull", vec![lhs, rhs]),
}
}
@@ -126,10 +130,10 @@ pub(super) fn build_infix(op: InfixOp, lhs: Value, rhs: Value) -> Value {
/// for the CONCAT alt: `a || b || c` becomes `concat(a, b, c)` rather
/// than `concat(concat(a, b), c)`. Either side that's already a
/// `Call(name="concat", ...)` contributes its existing args.
-pub(super) fn merge_concat(lhs: Value, rhs: Value) -> Value {
- let mut args: Vec<Value> = Vec::new();
- if is_concat_call(&lhs) {
- if let Some(left_args) = lhs.get("args").and_then(Value::as_array).cloned() {
+pub(super) fn merge_concat<E: Emitter>(emit: &E, lhs: E::Value, rhs: E::Value) -> E::Value {
+ let mut args: Vec<E::Value> = Vec::new();
+ if is_concat_call(emit, &lhs) {
+ if let Some(left_args) = emit.get_field(&lhs, "args").and_then(|v| emit.as_list(&v)) {
args.extend(left_args);
} else {
args.push(lhs);
@@ -137,8 +141,8 @@ pub(super) fn merge_concat(lhs: Value, rhs: Value) -> Value {
} else {
args.push(lhs);
}
- if is_concat_call(&rhs) {
- if let Some(right_args) = rhs.get("args").and_then(Value::as_array).cloned() {
+ if is_concat_call(emit, &rhs) {
+ if let Some(right_args) = emit.get_field(&rhs, "args").and_then(|v| emit.as_list(&v)) {
args.extend(right_args);
} else {
args.push(rhs);
@@ -146,56 +150,50 @@ pub(super) fn merge_concat(lhs: Value, rhs: Value) -> Value {
} else {
args.push(rhs);
}
- emit::call("concat", args)
+ emit.call("concat", args)
}
-fn is_concat_call(v: &Value) -> bool {
- v.get("node").and_then(Value::as_str) == Some("Call")
- && v.get("name").and_then(Value::as_str) == Some("concat")
+fn is_concat_call<E: Emitter>(emit: &E, v: &E::Value) -> bool {
+ if emit.node_kind(v).as_deref() != Some("Call") {
+ return false;
+ }
+ emit.get_field(v, "name")
+ .and_then(|name| emit.as_str(&name).map(Cow::into_owned))
+ .as_deref()
+ == Some("concat")
}
-pub(super) fn merge_and_or(node: &str, mut lhs: Value, rhs: Value) -> Value {
- // cpp's `And` / `Or` visitor flattens BOTH operands, so `a AND b AND
- // c` and `a AND (b AND c)` both produce a single flat `And` with
- // three exprs — parenthesisation does not nest. Flatten the rhs's
- // children in when it is the same node type.
- let rhs_children: Vec<Value> = match rhs {
- Value::Object(mut o) if o.get("node").and_then(Value::as_str) == Some(node) => {
- match o.remove("exprs") {
- Some(Value::Array(a)) => a,
- other => {
- if let Some(v) = other {
- o.insert("exprs".into(), v);
- }
- vec![Value::Object(o)]
- }
- }
- }
- other => vec![other],
- };
- if let Some(obj) = lhs.as_object_mut() {
- if obj.get("node").and_then(Value::as_str) == Some(node) {
- if let Some(exprs) = obj.get_mut("exprs").and_then(Value::as_array_mut) {
- exprs.extend(rhs_children);
- // Clear positions so the pratt loop's outer `wrap_pos` can
- // re-stamp them with the new span — without this the
- // idempotent `with_pos` would keep the pre-merge `[start,
- // end]` (end of the second operand only) and `a or b or c`
- // would end at `b`'s position instead of `c`'s.
- obj.remove("start");
- obj.remove("end");
- return lhs;
- }
- }
- }
- let mut exprs = Vec::with_capacity(rhs_children.len() + 1);
- exprs.push(lhs);
- exprs.extend(rhs_children);
+/// Flatten And/Or chains. cpp's `And`/`Or` visitor flattens BOTH operands, so `a AND b AND c` and `a AND (b AND c)` both produce a single flat `And` with three exprs — parenthesisation does not nest. We rebuild a fresh node from the extracted exprs so the outer pratt loop's `wrap_pos` can stamp the merged span (without the rebuild, idempotent `with_pos` would keep the pre-merge `[start, end]` and `a or b or c` would end at `b`'s position).
+pub(super) fn merge_and_or<E: Emitter>(
+ emit: &E,
+ node: &str,
+ lhs: E::Value,
+ rhs: E::Value,
+) -> E::Value {
+ let mut exprs: Vec<E::Value> = Vec::new();
+ extend_with_node_children(emit, &mut exprs, lhs, node);
+ extend_with_node_children(emit, &mut exprs, rhs, node);
if node == "And" {
- emit::and_(exprs)
+ emit.and_(exprs)
} else {
- emit::or_(exprs)
+ emit.or_(exprs)
+ }
+}
+
+/// If `v` is an `And`/`Or` node matching `node`, push its `exprs` children individually; otherwise push `v` itself.
+fn extend_with_node_children<E: Emitter>(
+ emit: &E,
+ out: &mut Vec<E::Value>,
+ v: E::Value,
+ node: &str,
+) {
+ if emit.node_kind(&v).as_deref() == Some(node) {
+ if let Some(children) = emit.get_field(&v, "exprs").and_then(|f| emit.as_list(&f)) {
+ out.extend(children);
+ return;
+ }
}
+ out.push(v);
}
/// Function-call postfix on an already-parsed `lhs`. The cpp grammar
@@ -216,24 +214,24 @@ pub(super) fn merge_and_or(node: &str, mut lhs: Value, rhs: Value) -> Value {
/// cpp's `selectSetStmt` grammar admits a bare `{X}` placeholder as
/// a set-stmt alternative, so `* ({x})` matches `ColumnExprCallSelect`
/// even when there's no SELECT keyword.
-pub(super) fn fold_call_or_exprcall(lhs: Value, args: Vec<Value>) -> Value {
+pub(super) fn fold_call_or_exprcall<E: Emitter>(
+ emit: &E,
+ lhs: E::Value,
+ args: Vec<E::Value>,
+) -> E::Value {
let is_select_call = args.len() == 1
&& matches!(
- args[0].get("node").and_then(Value::as_str),
+ emit.node_kind(&args[0]).as_deref(),
Some("SelectQuery") | Some("SelectSetQuery") | Some("Placeholder")
);
- if is_select_call {
- if let Some(obj) = lhs.as_object() {
- if obj.get("node").and_then(Value::as_str) == Some("Field") {
- if let Some(chain) = obj.get("chain").and_then(Value::as_array) {
- if chain.len() == 1 {
- if let Some(name) = chain[0].as_str() {
- return emit::call(name, args);
- }
- }
+ if is_select_call && emit.node_kind(&lhs).as_deref() == Some("Field") {
+ if let Some(chain) = emit.get_field(&lhs, "chain").and_then(|c| emit.as_list(&c)) {
+ if chain.len() == 1 {
+ if let Some(name) = emit.as_str(&chain[0]).map(Cow::into_owned) {
+ return emit.call(&name, args);
}
}
}
}
- serde_json::json!({"node": "ExprCall", "expr": lhs, "args": args})
+ emit.expr_call(lhs, args)
}
diff --git a/rust/hogql/parser/src/parse/cte.rs b/rust/hogql/parser/src/parse/cte.rs
index 1b478e0182c1..c9dc5fb4b073 100644
--- a/rust/hogql/parser/src/parse/cte.rs
+++ b/rust/hogql/parser/src/parse/cte.rs
@@ -9,14 +9,13 @@
//! token is an identifier-or-keyword-acting-as-identifier and the
//! follow-up sequence ends with `AS (`, we commit to subquery form.
-use serde_json::{json, Value};
-
use super::{identifier_text, kw_valid_as_identifier, Parser, BP_ALIAS};
+use crate::emit::Emitter;
use crate::error::ParseError;
use crate::lex::{Kw, Lexer, TokenKind};
-impl<'a> Parser<'a> {
- pub(crate) fn parse_with_expr_list(&mut self) -> Result<Vec<Value>, ParseError> {
+impl<'a, E: Emitter + Clone> Parser<'a, E> {
+ pub(crate) fn parse_with_expr_list(&mut self) -> Result<Vec<E::Value>, ParseError> {
// The C++ visitor returns CTEs as a list; the Python deserialiser
// turns it into a dict keyed by name. We follow the same shape.
// ANTLR ALL(*) tolerates a trailing comma before the SELECT
@@ -78,7 +77,7 @@ impl<'a> Parser<'a> {
)
}
- fn parse_with_expr(&mut self) -> Result<Value, ParseError> {
+ fn parse_with_expr(&mut self) -> Result<E::Value, ParseError> {
let cte_start = self.peek0.start;
// The grammar's `identifier` rule accepts plain IDENTIFIERs,
// QUOTED_IDENTIFIERs, and (most) reserved keywords — see
@@ -193,13 +192,10 @@ impl<'a> Parser<'a> {
)));
}
};
- Ok(self.wrap_pos(
- json!({"node": "CTE", "name": name, "expr": expr, "cte_type": "column"}),
- cte_start,
- ))
+ Ok(self.wrap_pos(self.emit.cte(&name, expr, "column"), cte_start))
}
- fn parse_with_expr_subquery(&mut self) -> Result<Value, ParseError> {
+ fn parse_with_expr_subquery(&mut self) -> Result<E::Value, ParseError> {
let id = self.bump()?;
let name = identifier_text(self.text(id), id.kind);
// Optional column-name list (parenthesised idents).
@@ -268,26 +264,8 @@ impl<'a> Parser<'a> {
self.expect(TokenKind::LParen, "(")?;
let sub = self.parse_select_set_stmt()?;
self.expect(TokenKind::RParen, ")")?;
- let mut obj = serde_json::Map::new();
- obj.insert("node".into(), Value::String("CTE".into()));
- obj.insert("name".into(), Value::String(name));
- obj.insert("expr".into(), sub);
- obj.insert("cte_type".into(), Value::String("subquery".into()));
- if let Some(c) = columns {
- obj.insert(
- "columns".into(),
- Value::Array(c.into_iter().map(Value::String).collect()),
- );
- }
- if let Some(uk) = using_key {
- obj.insert(
- "using_key".into(),
- Value::Array(uk.into_iter().map(Value::String).collect()),
- );
- }
- if let Some(m) = materialized {
- obj.insert("materialized".into(), Value::Bool(m));
- }
- Ok(Value::Object(obj))
+ Ok(self
+ .emit
+ .cte_subquery(&name, sub, columns, using_key, materialized))
}
}
diff --git a/rust/hogql/parser/src/parse/expr.rs b/rust/hogql/parser/src/parse/expr.rs
index ff6cdadba3fc..89ce3b85c262 100644
--- a/rust/hogql/parser/src/parse/expr.rs
+++ b/rust/hogql/parser/src/parse/expr.rs
@@ -8,8 +8,6 @@
//! `parse.rs` because both the SELECT/JOIN/CTE modules and the
//! expression parser reach them.
-use serde_json::{json, Value};
-
use super::template::parse_template_body;
use super::{
build_infix, fold_call_or_exprcall, identifier_text, infix_bp, interval_call_name,
@@ -18,26 +16,38 @@ use super::{
unquote_single_string, Parser, BP_ADDITIVE, BP_ALIAS, BP_BETWEEN, BP_COMPARE, BP_IGNORE_NULLS,
BP_IS_DISTINCT_FROM, BP_IS_NULL, BP_NOT, BP_OR, BP_POSTFIX, BP_TERNARY, BP_UNARY_MINUS,
};
-use crate::emit;
+use crate::emit::Emitter;
use crate::error::ParseError;
use crate::lex::{Kw, Lexer, Token, TokenKind};
/// Return value of [`Parser::parse_columns_decorators`]: optional
/// `EXCLUDE` name list, plus an optional `REPLACE` `(expr AS name, …)`
/// list as (name, expr) pairs in declaration order.
-type ColumnsDecorators = (Option<Vec<String>>, Option<Vec<(String, Value)>>);
+type ColumnsDecorators<V> = (Option<Vec<String>>, Option<Vec<(String, V)>>);
/// Return value of [`Parser::parse_function_args_inner`]: the
/// `DISTINCT` flag, the positional args, and an optional in-arg
/// `ORDER BY` list.
-type FunctionArgs = (bool, Vec<Value>, Option<Vec<Value>>);
+type FunctionArgs<V> = (bool, Vec<V>, Option<Vec<V>>);
-impl<'a> Parser<'a> {
- pub(crate) fn parse_expr_bp(&mut self, min_bp: u8) -> Result<Value, ParseError> {
- let lhs_start = self.peek0.start;
- let lhs = self.parse_prefix()?;
- let lhs = self.wrap_pos(lhs, lhs_start);
- self.pratt_continue_with_lhs(lhs, min_bp, lhs_start)
+impl<'a, E: Emitter + Clone> Parser<'a, E> {
+ pub(crate) fn parse_expr_bp(&mut self, min_bp: u8) -> Result<E::Value, ParseError> {
+ // Cap the central recursive entry so deeply-nested input (`((…))` with thousands of nests) surfaces as a syntax error rather than stack OOM. Bound rationale on `MAX_EXPR_RECURSION_DEPTH`.
+ self.expr_recursion_depth += 1;
+ let result = if self.expr_recursion_depth > crate::parse::MAX_EXPR_RECURSION_DEPTH {
+ Err(ParseError::syntax(
+ "expression too deeply nested",
+ self.peek0.start,
+ self.peek0.end,
+ ))
+ } else {
+ let lhs_start = self.peek0.start;
+ self.parse_prefix()
+ .map(|lhs| self.wrap_pos(lhs, lhs_start))
+ .and_then(|lhs| self.pratt_continue_with_lhs(lhs, min_bp, lhs_start))
+ };
+ self.expr_recursion_depth -= 1;
+ result
}
/// Run the Pratt infix/postfix loop with an externally-provided
@@ -46,10 +56,10 @@ impl<'a> Parser<'a> {
/// trailing `* …` arithmetic).
pub(crate) fn pratt_continue_with_lhs(
&mut self,
- mut lhs: Value,
+ mut lhs: E::Value,
min_bp: u8,
lhs_start: usize,
- ) -> Result<Value, ParseError> {
+ ) -> Result<E::Value, ParseError> {
loop {
let kind = self.peek();
if let Some((lbp, rbp, op)) = infix_bp(kind) {
@@ -102,7 +112,7 @@ impl<'a> Parser<'a> {
self.bump()?;
match self.parse_expr_bp(rbp) {
Ok(rhs) => {
- lhs = self.wrap_pos(build_infix(op, lhs, rhs), lhs_start);
+ lhs = self.wrap_pos(build_infix(&self.emit, op, lhs, rhs), lhs_start);
continue;
}
Err(_) => {
@@ -113,7 +123,7 @@ impl<'a> Parser<'a> {
}
self.bump()?;
let rhs = self.parse_expr_bp(rbp)?;
- lhs = self.wrap_pos(build_infix(op, lhs, rhs), lhs_start);
+ lhs = self.wrap_pos(build_infix(&self.emit, op, lhs, rhs), lhs_start);
continue;
}
if let Some(handled) = self.try_special_infix(kind, &mut lhs, min_bp, lhs_start)? {
@@ -153,7 +163,7 @@ impl<'a> Parser<'a> {
Ok(self.wrap_pos(lhs, lhs_start))
}
- pub(crate) fn parse_prefix(&mut self) -> Result<Value, ParseError> {
+ pub(crate) fn parse_prefix(&mut self) -> Result<E::Value, ParseError> {
// `IDENT (, IDENT)* -> body` — a bare-list arrow lambda may
// appear as the RHS of any binary operator (e.g. `x =~* y, z ->
// body` parses as `x =~* (lambda y, z -> body)`). The probe is
@@ -181,7 +191,7 @@ impl<'a> Parser<'a> {
self.bump()?;
let n = self.bump()?;
let src = self.consume_optional_fractional(self.text(n));
- return parse_number_literal(&src, true);
+ return parse_number_literal(&self.emit, &src, true);
}
TokenKind::Dot => {
// `-.<digits>` — leading-dot float. Peek one
@@ -201,20 +211,22 @@ impl<'a> Parser<'a> {
// "-Infinity" (no NaN fallback reachable here).
self.bump()?;
self.bump()?;
- return Ok(emit::constant_special_number("-Infinity"));
+ return Ok(self.emit.constant_special_number("-Infinity"));
}
TokenKind::Keyword(Kw::Nan) => {
// -NaN is still NaN — match the C++ behaviour of
// emitting "NaN".
self.bump()?;
self.bump()?;
- return Ok(emit::constant_special_number("NaN"));
+ return Ok(self.emit.constant_special_number("NaN"));
}
_ => {}
}
self.bump()?;
let rhs = self.parse_expr_bp(BP_UNARY_MINUS)?;
- Ok(emit::arith(emit::constant(Value::from(0)), "-", rhs))
+ Ok(self
+ .emit
+ .arith(self.emit.constant(self.emit.int(0)), "-", rhs))
}
TokenKind::Plus => {
// `+` is only a sign on a `numberLiteral` per grammar
@@ -228,7 +240,7 @@ impl<'a> Parser<'a> {
self.bump()?;
let n = self.bump()?;
let src = self.consume_optional_fractional(self.text(n));
- parse_number_literal(&src, false)
+ parse_number_literal(&self.emit, &src, false)
}
TokenKind::Dot => {
if let Some(num) = self.consume_signed_dot_float(false)? {
@@ -242,12 +254,12 @@ impl<'a> Parser<'a> {
// `+infinity` → "infinity" — both → "Infinity".
self.bump()?;
self.bump()?;
- Ok(emit::constant_special_number("Infinity"))
+ Ok(self.emit.constant_special_number("Infinity"))
}
TokenKind::Keyword(Kw::Nan) => {
self.bump()?;
self.bump()?;
- Ok(emit::constant_special_number("NaN"))
+ Ok(self.emit.constant_special_number("NaN"))
}
_ => Err(self.err("unary `+` only applies to a number literal")),
}
@@ -277,7 +289,7 @@ impl<'a> Parser<'a> {
{
self.bump()?; // NOT
let rhs = self.parse_expr_bp(BP_NOT)?;
- return Ok(emit::not_(rhs));
+ return Ok(self.emit.not_(rhs));
}
if self.peek_next() == TokenKind::LParen {
return self.parse_ident_lead();
@@ -463,7 +475,7 @@ impl<'a> Parser<'a> {
}
self.bump()?;
let rhs = self.parse_expr_bp(BP_NOT)?;
- Ok(emit::not_(rhs))
+ Ok(self.emit.not_(rhs))
}
_ => {
// `<Tag ...>` — HogQLX tag in column position (cpp's
@@ -480,13 +492,13 @@ impl<'a> Parser<'a> {
}
}
- fn parse_primary(&mut self) -> Result<Value, ParseError> {
+ fn parse_primary(&mut self) -> Result<E::Value, ParseError> {
let tok = self.peek0;
match tok.kind {
TokenKind::Number => {
self.bump()?;
let src = self.consume_optional_fractional(self.text(tok));
- Ok(parse_number_literal(&src, false)?)
+ Ok(parse_number_literal(&self.emit, &src, false)?)
}
// `.<digits>` — bare-decimal float per the grammar's
// `floatingLiteral: DOT (DECIMAL_LITERAL | ...)`.
@@ -494,13 +506,13 @@ impl<'a> Parser<'a> {
self.bump()?;
let n = self.bump()?;
let src = format!(".{}", self.text(n));
- Ok(parse_number_literal(&src, false)?)
+ Ok(parse_number_literal(&self.emit, &src, false)?)
}
TokenKind::String => {
self.bump()?;
- Ok(emit::constant(Value::String(unquote_single_string(
- self.text(tok),
- ))))
+ Ok(self
+ .emit
+ .constant(self.emit.string(&unquote_single_string(self.text(tok)))))
}
TokenKind::TemplateString => {
// Lexer captured the whole `f'…'` or `F'…'` span. The
@@ -521,7 +533,7 @@ impl<'a> Parser<'a> {
let body_offset = tok.start + 2; // past `f'`
let body_end = tok.end - 1; // before closing `'`
self.bump()?;
- parse_template_body(self.src, body_offset, body_end)
+ parse_template_body(&self.emit, self.src, body_offset, body_end)
}
TokenKind::Keyword(Kw::True | Kw::False)
if self.peek_next() == TokenKind::LParen || self.peek_next() == TokenKind::Dot =>
@@ -543,15 +555,15 @@ impl<'a> Parser<'a> {
}
TokenKind::Keyword(Kw::True) => {
self.bump()?;
- Ok(emit::constant(Value::Bool(true)))
+ Ok(self.emit.constant(self.emit.bool(true)))
}
TokenKind::Keyword(Kw::False) => {
self.bump()?;
- Ok(emit::constant(Value::Bool(false)))
+ Ok(self.emit.constant(self.emit.bool(false)))
}
TokenKind::Keyword(Kw::Null) => {
self.bump()?;
- Ok(emit::constant(Value::Null))
+ Ok(self.emit.constant(self.emit.null()))
}
TokenKind::Keyword(Kw::Inf) => {
// cpp 1.3.45's `VISIT(NumberLiteral)` maps both `inf`
@@ -560,11 +572,11 @@ impl<'a> Parser<'a> {
// collapsed bare `infinity` to NaN — that's been fixed
// upstream, so unsigned INF is unconditionally Infinity.)
self.bump()?;
- Ok(emit::constant_special_number("Infinity"))
+ Ok(self.emit.constant_special_number("Infinity"))
}
TokenKind::Keyword(Kw::Nan) => {
self.bump()?;
- Ok(emit::constant_special_number("NaN"))
+ Ok(self.emit.constant_special_number("NaN"))
}
// CASE/CAST/TRY_CAST/INTERVAL/LAMBDA — special grammar
@@ -743,7 +755,7 @@ impl<'a> Parser<'a> {
/// `CASE [scrutinee] WHEN c1 THEN r1 [WHEN c2 THEN r2 ...] [ELSE r] END`
/// rewrites to `Call("if"|"multiIf"|"transform", ...)` per the C++
/// visitor's [`VISIT(ColumnExprCase)`] logic.
- fn parse_case_expr(&mut self) -> Result<Value, ParseError> {
+ fn parse_case_expr(&mut self) -> Result<E::Value, ParseError> {
self.expect_kw(Kw::Case, "CASE")?;
// Optional scrutinee. The simple case (peek != WHEN) parses
// greedy and uses the result. The WHEN-first case is more
@@ -767,7 +779,10 @@ impl<'a> Parser<'a> {
} else {
let cp = self.checkpoint();
match self.parse_expr_bp(0) {
- Ok(s) if self.peek() == TokenKind::Keyword(Kw::When) && !is_bare_field(&s) => {
+ Ok(s)
+ if self.peek() == TokenKind::Keyword(Kw::When)
+ && !is_bare_field(&self.emit, &s) =>
+ {
Some(s)
}
_ => {
@@ -776,8 +791,8 @@ impl<'a> Parser<'a> {
}
}
};
- let mut whens: Vec<Value> = Vec::new();
- let mut thens: Vec<Value> = Vec::new();
+ let mut whens: Vec<E::Value> = Vec::new();
+ let mut thens: Vec<E::Value> = Vec::new();
while self.eat_kw(Kw::When)? {
whens.push(self.parse_expr_bp(0)?);
self.expect_kw(Kw::Then, "THEN")?;
@@ -806,7 +821,7 @@ impl<'a> Parser<'a> {
// case S when v then r else d end → transform(S, [v], [r], d)
// case S when v1 then r1 when v2 then r2 end
// → transform(S, [v1, v2], [r1], r2)
- let mut flat: Vec<Value> = Vec::with_capacity(whens.len() * 2 + 2);
+ let mut flat: Vec<E::Value> = Vec::with_capacity(whens.len() * 2 + 2);
for (w, t) in whens.into_iter().zip(thens) {
flat.push(w);
flat.push(t);
@@ -814,9 +829,11 @@ impl<'a> Parser<'a> {
if let Some(d) = else_branch {
flat.push(d);
}
- let else_arg = flat.pop().unwrap_or_else(|| emit::constant(Value::Null));
- let mut whens_arr: Vec<Value> = Vec::new();
- let mut thens_arr: Vec<Value> = Vec::new();
+ let else_arg = flat
+ .pop()
+ .unwrap_or_else(|| self.emit.constant(self.emit.null()));
+ let mut whens_arr: Vec<E::Value> = Vec::new();
+ let mut thens_arr: Vec<E::Value> = Vec::new();
for (i, col) in flat.into_iter().enumerate() {
if i % 2 == 0 {
whens_arr.push(col);
@@ -824,12 +841,12 @@ impl<'a> Parser<'a> {
thens_arr.push(col);
}
}
- return Ok(emit::call(
+ return Ok(self.emit.call(
"transform",
vec![
scrut,
- emit::array_(whens_arr),
- emit::array_(thens_arr),
+ self.emit.array_(whens_arr),
+ self.emit.array_(thens_arr),
else_arg,
],
));
@@ -843,7 +860,7 @@ impl<'a> Parser<'a> {
// Notably an implicit-NULL else is NOT synthesised here, so
// `case when c then r end` produces `multiIf(c, r)`, not
// `if(c, r, null)`.
- let mut columns: Vec<Value> = Vec::with_capacity(whens.len() * 2 + 1);
+ let mut columns: Vec<E::Value> = Vec::with_capacity(whens.len() * 2 + 1);
for (w, t) in whens.into_iter().zip(thens) {
columns.push(w);
columns.push(t);
@@ -852,14 +869,14 @@ impl<'a> Parser<'a> {
columns.push(d);
}
if columns.len() == 3 {
- Ok(emit::call("if", columns))
+ Ok(self.emit.call("if", columns))
} else {
- Ok(emit::call("multiIf", columns))
+ Ok(self.emit.call("multiIf", columns))
}
}
/// `CAST(expr AS type)` / `TRY_CAST(expr AS type)`.
- fn parse_cast_expr(&mut self, is_try: bool) -> Result<Value, ParseError> {
+ fn parse_cast_expr(&mut self, is_try: bool) -> Result<E::Value, ParseError> {
self.bump()?; // consume CAST / TRY_CAST
self.expect(TokenKind::LParen, "(")?;
// cpp grammar: `castFunction: CAST LPAREN columnExpr AS
@@ -879,9 +896,9 @@ impl<'a> Parser<'a> {
let type_name = self.parse_type_expr()?;
self.expect(TokenKind::RParen, ")")?;
if is_try {
- Ok(emit::try_cast(expr, &type_name))
+ Ok(self.emit.try_cast(expr, &type_name))
} else {
- Ok(emit::type_cast(expr, &type_name))
+ Ok(self.emit.type_cast(expr, &type_name))
}
}
@@ -960,7 +977,7 @@ impl<'a> Parser<'a> {
/// `INTERVAL <expr> <unit>` or `INTERVAL '<n> <unit>'`. Both forms
/// rewrite to `Call("toInterval<Unit>", [expr])` per the C++ visitor.
- fn parse_interval_expr(&mut self) -> Result<Value, ParseError> {
+ fn parse_interval_expr(&mut self) -> Result<E::Value, ParseError> {
self.expect_kw(Kw::Interval, "INTERVAL")?;
// `INTERVAL '5 day'` — a single string literal carrying both
// count and unit. Only take this branch when the string is the
@@ -1015,10 +1032,9 @@ impl<'a> Parser<'a> {
let unit_name = interval_call_name_case_sensitive(unit);
if let Some(unit_name) = unit_name {
self.bump()?;
- return Ok(emit::call(
- unit_name,
- vec![emit::constant(Value::from(count))],
- ));
+ return Ok(self
+ .emit
+ .call(unit_name, vec![self.emit.constant(self.emit.int(count))]));
}
// Unit not lowercase / not recognised — cpp errors
// here even though the count was valid.
@@ -1075,7 +1091,7 @@ impl<'a> Parser<'a> {
)))
}
};
- Ok(emit::call(unit_name, vec![expr]))
+ Ok(self.emit.call(unit_name, vec![expr]))
}
/// Is `peek_next` a recognised INTERVAL unit keyword? Used by
@@ -1142,7 +1158,7 @@ impl<'a> Parser<'a> {
}
}
- fn parse_trim_keyword_form(&mut self) -> Result<Value, ParseError> {
+ fn parse_trim_keyword_form(&mut self) -> Result<E::Value, ParseError> {
self.expect_kw(Kw::Trim, "TRIM")?;
self.expect(TokenKind::LParen, "(")?;
let name = if self.eat_kw(Kw::Leading)? {
@@ -1170,13 +1186,13 @@ impl<'a> Parser<'a> {
self.expect(TokenKind::RParen, ")")?;
// Args order matches the C++ visitor: expr first, then the trim
// substring.
- Ok(emit::call(name, vec![expr, str_value]))
+ Ok(self.emit.call(name, vec![expr, str_value]))
}
/// `lambda IDENT (, IDENT)* : body`. The body admits a bare-list
/// arrow lambda (`a, b -> body`) as a full columnExpr, so we try
/// that form first before falling back to the regular Pratt parse.
- fn parse_lambda_keyword(&mut self) -> Result<Value, ParseError> {
+ fn parse_lambda_keyword(&mut self) -> Result<E::Value, ParseError> {
self.expect_kw(Kw::Lambda, "lambda")?;
let mut params: Vec<String> = Vec::new();
loop {
@@ -1205,14 +1221,14 @@ impl<'a> Parser<'a> {
} else {
self.parse_lambda_body()?
};
- Ok(emit::lambda(params, body))
+ Ok(self.emit.lambda(params, body))
}
/// `COLUMNS('regex')` / `COLUMNS(expr, …)` / `COLUMNS(*)` with optional
/// `EXCLUDE (…)` / `REPLACE (…)` decoration and an optional
/// `IDENT.*` qualifier. Plus the leading-`ASTERISK COLUMNS(…)` spread
/// forms. Covers the full ColumnExprColumns* family from the grammar.
- fn parse_columns_expr(&mut self) -> Result<Value, ParseError> {
+ fn parse_columns_expr(&mut self) -> Result<E::Value, ParseError> {
self.expect_kw(Kw::Columns, "COLUMNS")?;
self.expect(TokenKind::LParen, "(")?;
// Three shapes inside the parens:
@@ -1220,145 +1236,146 @@ impl<'a> Parser<'a> {
// 2. `*` [EXCLUDE (...)] [REPLACE (...)]
// 3. `ident DOT *` [EXCLUDE (...)] [REPLACE (...)]
// 4. `expr_list` → ColumnsList
- let result =
- if matches!(self.peek(), TokenKind::String) && self.peek_next() == TokenKind::RParen {
- let str_tok = self.bump()?;
- let s = unquote_single_string(self.text(str_tok));
- emit::columns_expr(Some(s), None, false, None, None)
- } else if self.peek() == TokenKind::Asterisk
- && matches!(
- self.peek_next(),
- TokenKind::Keyword(Kw::Exclude) | TokenKind::Keyword(Kw::Replace)
- )
+ let result = if matches!(self.peek(), TokenKind::String)
+ && self.peek_next() == TokenKind::RParen
+ {
+ let str_tok = self.bump()?;
+ let s = unquote_single_string(self.text(str_tok));
+ self.emit.columns_expr(Some(s), None, false, None, None)
+ } else if self.peek() == TokenKind::Asterisk
+ && matches!(
+ self.peek_next(),
+ TokenKind::Keyword(Kw::Exclude) | TokenKind::Keyword(Kw::Replace)
+ )
+ {
+ let asterisk_pos = self.peek0.start;
+ self.bump()?;
+ let (exclude, replace) = self.parse_columns_decorators()?;
+ // ANTLR resolves `COLUMNS(* …)` against five alternatives in
+ // declared order. The interesting split:
+ //
+ // `COLUMNS(* EXCLUDE …)` only
+ // → matches `ColumnExprColumnsList` first because
+ // `ColumnExprAsterisk` admits a trailing EXCLUDE
+ // (line 288 of HogQLParser.g4). cpp wraps the asterisk
+ // columns-expr inside an outer `ColumnsExpr(columns=…)`.
+ //
+ // `COLUMNS(* REPLACE …)`
+ // `COLUMNS(* EXCLUDE … REPLACE …)`
+ // → list path can't match (REPLACE isn't a valid trailing
+ // decoration on `ColumnExprAsterisk`), so ANTLR falls
+ // through to the specialised `ColumnExprColumnsReplace`
+ // / `…ExcludeReplace` rule, which returns the
+ // UNWRAPPED `ColumnsExpr(all_columns=True, …)` shape.
+ //
+ // Mirror that split here.
+ if replace.is_some() {
+ self.emit.columns_expr(None, None, true, exclude, replace)
+ } else {
+ // cpp's `ColumnExprAsterisk` ctx covers `*` plus the
+ // optional `EXCLUDE(...)` trailer. Wrap the inner
+ // ColumnsExpr from the `*` position so it carries the
+ // span before the outer columns_list_from_first picks
+ // it up as `columns[0]`.
+ let inner = self.wrap_pos(
+ self.emit.columns_expr(None, None, true, exclude, None),
+ asterisk_pos,
+ );
+ self.columns_list_from_first(inner)?
+ }
+ } else {
+ // Could be `ident . *` or an expression list.
+ // Peek for the qualified-asterisk pattern: IDENT DOT ASTERISK.
+ if matches!(
+ self.peek(),
+ TokenKind::Ident | TokenKind::QuotedIdent | TokenKind::Keyword(_)
+ ) && self.peek_next() == TokenKind::Dot
{
- let asterisk_pos = self.peek0.start;
- self.bump()?;
- let (exclude, replace) = self.parse_columns_decorators()?;
- // ANTLR resolves `COLUMNS(* …)` against five alternatives in
- // declared order. The interesting split:
- //
- // `COLUMNS(* EXCLUDE …)` only
- // → matches `ColumnExprColumnsList` first because
- // `ColumnExprAsterisk` admits a trailing EXCLUDE
- // (line 288 of HogQLParser.g4). cpp wraps the asterisk
- // columns-expr inside an outer `ColumnsExpr(columns=…)`.
- //
- // `COLUMNS(* REPLACE …)`
- // `COLUMNS(* EXCLUDE … REPLACE …)`
- // → list path can't match (REPLACE isn't a valid trailing
- // decoration on `ColumnExprAsterisk`), so ANTLR falls
- // through to the specialised `ColumnExprColumnsReplace`
- // / `…ExcludeReplace` rule, which returns the
- // UNWRAPPED `ColumnsExpr(all_columns=True, …)` shape.
- //
- // Mirror that split here.
- if replace.is_some() {
- emit::columns_expr(None, None, true, exclude, replace)
- } else {
- // cpp's `ColumnExprAsterisk` ctx covers `*` plus the
- // optional `EXCLUDE(...)` trailer. Wrap the inner
- // ColumnsExpr from the `*` position so it carries the
- // span before the outer columns_list_from_first picks
- // it up as `columns[0]`.
- let inner = self.wrap_pos(
- emit::columns_expr(None, None, true, exclude, None),
- asterisk_pos,
- );
- self.columns_list_from_first(inner)?
+ // Try to consume `IDENT.*` (or longer dotted chain ending in `*`).
+ let saved_pos = self.peek0.start;
+ let mut chain: Vec<String> = Vec::new();
+ let mut probe = Lexer::with_pos(self.src, saved_pos);
+ let first = probe.next_token()?;
+ chain.push(identifier_text(
+ &self.src[first.start..first.end],
+ first.kind,
+ ));
+ let mut ok = true;
+ let mut saw_star = false;
+ loop {
+ let dot = probe.next_token()?;
+ if dot.kind != TokenKind::Dot {
+ ok = false;
+ break;
+ }
+ let nxt = probe.next_token()?;
+ if nxt.kind == TokenKind::Asterisk {
+ saw_star = true;
+ break;
+ }
+ if matches!(
+ nxt.kind,
+ TokenKind::Ident | TokenKind::QuotedIdent | TokenKind::Keyword(_)
+ ) {
+ chain.push(identifier_text(&self.src[nxt.start..nxt.end], nxt.kind));
+ } else {
+ ok = false;
+ break;
+ }
}
- } else {
- // Could be `ident . *` or an expression list.
- // Peek for the qualified-asterisk pattern: IDENT DOT ASTERISK.
- if matches!(
- self.peek(),
- TokenKind::Ident | TokenKind::QuotedIdent | TokenKind::Keyword(_)
- ) && self.peek_next() == TokenKind::Dot
- {
- // Try to consume `IDENT.*` (or longer dotted chain ending in `*`).
- let saved_pos = self.peek0.start;
- let mut chain: Vec<String> = Vec::new();
- let mut probe = Lexer::with_pos(self.src, saved_pos);
- let first = probe.next_token()?;
- chain.push(identifier_text(
- &self.src[first.start..first.end],
- first.kind,
- ));
- let mut ok = true;
- let mut saw_star = false;
- loop {
- let dot = probe.next_token()?;
- if dot.kind != TokenKind::Dot {
- ok = false;
- break;
- }
- let nxt = probe.next_token()?;
- if nxt.kind == TokenKind::Asterisk {
- saw_star = true;
- break;
- }
- if matches!(
- nxt.kind,
- TokenKind::Ident | TokenKind::QuotedIdent | TokenKind::Keyword(_)
- ) {
- chain.push(identifier_text(&self.src[nxt.start..nxt.end], nxt.kind));
- } else {
- ok = false;
- break;
+ if ok && saw_star {
+ // Capture the end of the `*` token before committing
+ // the cursor — we want the Field span to cover the
+ // qualified asterisk (`table.*`), matching cpp's
+ // `ColumnExprColumnsQualifiedAll` ctx span.
+ let asterisk_end = probe.pos();
+ // Commit the qualified-asterisk consumption.
+ self.set_lexer_pos(probe.pos())?;
+ let (exclude, replace) = self.parse_columns_decorators()?;
+ let mut chain_values: Vec<E::Value> =
+ chain.into_iter().map(|s| self.emit.string(&s)).collect();
+ chain_values.push(self.emit.string("*"));
+ let qualified_field =
+ self.wrap_pos_to(self.emit.field(chain_values), saved_pos, asterisk_end);
+ // Four C++-visitor shapes, all reachable here:
+ // QualifiedAll: ColumnsExpr(columns=[Field(table.*)])
+ // QualifiedExclude: ColumnsExpr(columns=[ColumnsExpr(all_columns=True, exclude=...)])
+ // QualifiedReplace: ColumnsExpr(all_columns=True, replace=...) // qualifier dropped
+ // QualifiedExcludeReplace: ColumnsExpr(all_columns=True, exclude=..., replace=...) // qualifier dropped
+ match (exclude, replace) {
+ (None, None) => self.columns_list_from_first(qualified_field)?,
+ (Some(ex), None) => {
+ // cpp's `ColumnExprColumnsQualifiedExclude`
+ // ctx covers `IDENT.* EXCLUDE(...)`; the
+ // inner ColumnsExpr inherits that span.
+ // Wrap before passing to the outer list.
+ let inner = self.wrap_pos(
+ self.emit.columns_expr(None, None, true, Some(ex), None),
+ saved_pos,
+ );
+ self.columns_list_from_first(inner)?
}
- }
- if ok && saw_star {
- // Capture the end of the `*` token before committing
- // the cursor — we want the Field span to cover the
- // qualified asterisk (`table.*`), matching cpp's
- // `ColumnExprColumnsQualifiedAll` ctx span.
- let asterisk_end = probe.pos();
- // Commit the qualified-asterisk consumption.
- self.set_lexer_pos(probe.pos())?;
- let (exclude, replace) = self.parse_columns_decorators()?;
- let mut chain_values: Vec<Value> =
- chain.into_iter().map(Value::String).collect();
- chain_values.push(Value::String("*".into()));
- let qualified_field =
- self.wrap_pos_to(emit::field(chain_values), saved_pos, asterisk_end);
- // Four C++-visitor shapes, all reachable here:
- // QualifiedAll: ColumnsExpr(columns=[Field(table.*)])
- // QualifiedExclude: ColumnsExpr(columns=[ColumnsExpr(all_columns=True, exclude=...)])
- // QualifiedReplace: ColumnsExpr(all_columns=True, replace=...) // qualifier dropped
- // QualifiedExcludeReplace: ColumnsExpr(all_columns=True, exclude=..., replace=...) // qualifier dropped
- match (exclude, replace) {
- (None, None) => self.columns_list_from_first(qualified_field)?,
- (Some(ex), None) => {
- // cpp's `ColumnExprColumnsQualifiedExclude`
- // ctx covers `IDENT.* EXCLUDE(...)`; the
- // inner ColumnsExpr inherits that span.
- // Wrap before passing to the outer list.
- let inner = self.wrap_pos(
- emit::columns_expr(None, None, true, Some(ex), None),
- saved_pos,
- );
- self.columns_list_from_first(inner)?
- }
- (ex, repl @ Some(_)) => {
- // cpp's `ColumnExprColumnsQualifiedReplace` /
- // `…QualifiedExcludeReplace` ctx covers the
- // full `COLUMNS LPAREN IDENT.* [EXCLUDE(...)]
- // REPLACE(...) RPAREN`. The outer
- // `parse_expr_bp` wrap captures positions
- // from the COLUMNS keyword, so emit the
- // ColumnsExpr without a local wrap and let
- // that outer wrap stamp the span.
- emit::columns_expr(None, None, true, ex, repl)
- }
+ (ex, repl @ Some(_)) => {
+ // cpp's `ColumnExprColumnsQualifiedReplace` /
+ // `…QualifiedExcludeReplace` ctx covers the
+ // full `COLUMNS LPAREN IDENT.* [EXCLUDE(...)]
+ // REPLACE(...) RPAREN`. The outer
+ // `parse_expr_bp` wrap captures positions
+ // from the COLUMNS keyword, so emit the
+ // ColumnsExpr without a local wrap and let
+ // that outer wrap stamp the span.
+ self.emit.columns_expr(None, None, true, ex, repl)
}
- } else {
- let list = self.parse_arg_list(TokenKind::RParen)?;
- emit::columns_expr(None, Some(list), false, None, None)
}
} else {
let list = self.parse_arg_list(TokenKind::RParen)?;
- emit::columns_expr(None, Some(list), false, None, None)
+ self.emit.columns_expr(None, Some(list), false, None, None)
}
- };
+ } else {
+ let list = self.parse_arg_list(TokenKind::RParen)?;
+ self.emit.columns_expr(None, Some(list), false, None, None)
+ }
+ };
self.expect(TokenKind::RParen, ")")?;
Ok(result)
}
@@ -1372,15 +1389,11 @@ impl<'a> Parser<'a> {
/// larger `columnExpr` (a postfix `(…)` call etc.) and may be the
/// first of a comma list — continue it through the Pratt loop and
/// collect the rest as `ColumnExprColumnsList`.
- fn columns_list_from_first(&mut self, first: Value) -> Result<Value, ParseError> {
+ fn columns_list_from_first(&mut self, first: E::Value) -> Result<E::Value, ParseError> {
if self.peek() == TokenKind::RParen {
- return Ok(emit::columns_expr(
- None,
- Some(vec![first]),
- false,
- None,
- None,
- ));
+ return Ok(self
+ .emit
+ .columns_expr(None, Some(vec![first]), false, None, None));
}
let cont_start = self.peek0.start;
let first = self.pratt_continue_with_lhs(first, 0, cont_start)?;
@@ -1391,10 +1404,10 @@ impl<'a> Parser<'a> {
}
list.push(self.parse_expr_bp(0)?);
}
- Ok(emit::columns_expr(None, Some(list), false, None, None))
+ Ok(self.emit.columns_expr(None, Some(list), false, None, None))
}
- fn parse_columns_decorators(&mut self) -> Result<ColumnsDecorators, ParseError> {
+ fn parse_columns_decorators(&mut self) -> Result<ColumnsDecorators<E::Value>, ParseError> {
let exclude = if self.eat_kw(Kw::Exclude)? {
self.expect(TokenKind::LParen, "(")?;
let mut names = Vec::new();
@@ -1508,7 +1521,7 @@ impl<'a> Parser<'a> {
/// either regex or list)
/// - `* EXCLUDE (…)` / `* REPLACE (…)` → `ColumnsExpr(all_columns=True, …)`
/// - bare `*` → `Field(["*"])` (C++ visitor's `ColumnExprAsterisk`)
- fn parse_top_level_asterisk(&mut self) -> Result<Value, ParseError> {
+ fn parse_top_level_asterisk(&mut self) -> Result<E::Value, ParseError> {
self.expect(TokenKind::Asterisk, "*")?;
// `* COLUMNS(…)` — spread-columns form. The inner is whatever
// parse_columns_expr produces (regex / list / qualified-all);
@@ -1520,7 +1533,7 @@ impl<'a> Parser<'a> {
&& self.peek_next() == TokenKind::LParen
{
let inner = self.parse_columns_expr()?;
- return Ok(emit::spread_expr(inner));
+ return Ok(self.emit.spread_expr(inner));
}
// `ColumnExprAsterisk` (grammar line 289) admits ONLY an
// optional trailing EXCLUDE on a bare `*`. `REPLACE` after `*`
@@ -1540,24 +1553,24 @@ impl<'a> Parser<'a> {
));
}
if exclude.is_none() && replace.is_none() {
- Ok(emit::field(vec![Value::String("*".into())]))
+ Ok(self.emit.field(vec![self.emit.string("*")]))
} else {
- Ok(emit::columns_expr(None, None, true, exclude, replace))
+ Ok(self.emit.columns_expr(None, None, true, exclude, replace))
}
}
/// `#<integer>` — positional column reference from a SELECT.
- fn parse_positional(&mut self) -> Result<Value, ParseError> {
+ fn parse_positional(&mut self) -> Result<E::Value, ParseError> {
self.expect(TokenKind::Hash, "#")?;
let tok = self.bump()?;
if tok.kind != TokenKind::Number {
return Err(self.err(format!("expected integer after '#', got {:?}", tok.kind)));
}
let n: i64 = self.text(tok).parse().unwrap_or(0);
- Ok(json!({"node": "PositionalRef", "index": n}))
+ Ok(self.emit.positional_ref(n))
}
- pub(crate) fn parse_brace_dict_or_placeholder(&mut self) -> Result<Value, ParseError> {
+ pub(crate) fn parse_brace_dict_or_placeholder(&mut self) -> Result<E::Value, ParseError> {
// Capture the `{` start so the resulting Dict / Placeholder carries
// a span from `{` through `}`. Callers reached via `parse_expr_bp`
// also wrap, but `parse_table_expr` and the join-expr placeholder
@@ -1567,7 +1580,7 @@ impl<'a> Parser<'a> {
self.expect(TokenKind::LBrace, "{")?;
if self.peek() == TokenKind::RBrace {
self.bump()?;
- return Ok(self.wrap_pos(emit::dict_(vec![]), brace_start));
+ return Ok(self.wrap_pos(self.emit.dict_(vec![]), brace_start));
}
let first = self.parse_expr_bp(0)?;
if self.eat(TokenKind::Colon)? {
@@ -1583,19 +1596,19 @@ impl<'a> Parser<'a> {
items.push((k, v));
}
self.expect(TokenKind::RBrace, "}")?;
- Ok(self.wrap_pos(emit::dict_(items), brace_start))
+ Ok(self.wrap_pos(self.emit.dict_(items), brace_start))
} else {
self.expect(TokenKind::RBrace, "}")?;
- Ok(self.wrap_pos(emit::placeholder(first), brace_start))
+ Ok(self.wrap_pos(self.emit.placeholder(first), brace_start))
}
}
- fn parse_single_arg_arrow_lambda(&mut self) -> Result<Value, ParseError> {
+ fn parse_single_arg_arrow_lambda(&mut self) -> Result<E::Value, ParseError> {
let ident = self.bump()?;
let name = identifier_text(self.text(ident), ident.kind);
self.expect(TokenKind::Arrow, "->")?;
let body = self.parse_lambda_body()?;
- Ok(emit::lambda(vec![name], body))
+ Ok(self.emit.lambda(vec![name], body))
}
/// Lambda body — either a single expression (`(x) -> expr`) or a
@@ -1612,7 +1625,7 @@ impl<'a> Parser<'a> {
/// any nesting depth — a heuristic that pattern-matches the brace
/// contents inevitably misses shapes (e.g. a block of juxtaposed
/// `exprStmt`s carries no `;`, keyword, or `:=` to key on).
- pub(crate) fn parse_lambda_body(&mut self) -> Result<Value, ParseError> {
+ pub(crate) fn parse_lambda_body(&mut self) -> Result<E::Value, ParseError> {
if self.peek() == TokenKind::LBrace {
return self.try_alt(&[&Self::parse_brace_expr_body, &Self::parse_block]);
}
@@ -1622,14 +1635,14 @@ impl<'a> Parser<'a> {
/// `try_alt` arm: parse a `{…}` lambda body as a single Dict /
/// Placeholder expression. Fails (so the block arm takes over) when
/// the brace contents are not one whole `columnExpr`.
- fn parse_brace_expr_body(&mut self) -> Result<Value, ParseError> {
+ fn parse_brace_expr_body(&mut self) -> Result<E::Value, ParseError> {
self.parse_expr_bp(0)
}
/// Try the bare-list arrow lambda form: `IDENT (, IDENT)* -> body`.
/// Only valid at the outermost expression level (inside argument lists
/// the commas are separators, so we never need to detect it there).
- pub(crate) fn try_bare_list_lambda(&mut self) -> Result<Option<Value>, ParseError> {
+ pub(crate) fn try_bare_list_lambda(&mut self) -> Result<Option<E::Value>, ParseError> {
// `IDENT (, IDENT)* COMMA? -> body`. A lambda parameter is an
// `identifier`: a plain Ident, a QuotedIdent, or any keyword
// admitted by `kw_valid_as_identifier` (`name -> 1`,
@@ -1660,7 +1673,7 @@ impl<'a> Parser<'a> {
// Confirmed; commit the consumption.
self.set_lexer_pos(probe.pos())?;
let body = self.parse_lambda_body()?;
- return Ok(Some(emit::lambda(names, body)));
+ return Ok(Some(self.emit.lambda(names, body)));
}
TokenKind::Comma => {
// Peek past the comma to handle the trailing-comma
@@ -1671,7 +1684,7 @@ impl<'a> Parser<'a> {
TokenKind::Arrow => {
self.set_lexer_pos(probe.pos())?;
let body = self.parse_lambda_body()?;
- return Ok(Some(emit::lambda(names, body)));
+ return Ok(Some(self.emit.lambda(names, body)));
}
k if is_ident_kind(k) => {
names.push(identifier_text(
@@ -1690,7 +1703,7 @@ impl<'a> Parser<'a> {
/// `(...)` may be a paren-wrapped expression, a tuple, or a lambda
/// head followed by `->`. We probe for the lambda shape first because
/// it's the only one that needs to refuse non-identifier contents.
- fn parse_paren_or_lambda(&mut self) -> Result<Value, ParseError> {
+ fn parse_paren_or_lambda(&mut self) -> Result<E::Value, ParseError> {
// Probe for `( [IDENT (, IDENT)* COMMA?]? ) ARROW`.
let mut probe = Lexer::with_pos(self.src, self.peek0.start);
let lp = probe.next_token()?;
@@ -1736,7 +1749,7 @@ impl<'a> Parser<'a> {
if arrow.kind == TokenKind::Arrow {
self.set_lexer_pos(probe.pos())?;
let body = self.parse_lambda_body()?;
- return Ok(emit::lambda(names, body));
+ return Ok(self.emit.lambda(names, body));
}
}
// Not a lambda — fall through to the normal paren/tuple parse.
@@ -1848,7 +1861,7 @@ impl<'a> Parser<'a> {
/// token after the dot is `Number` before committing. Returns
/// `Ok(None)` (without moving the cursor) when the lookahead
/// doesn't fit, so the caller can fall through to unary-minus.
- fn consume_signed_dot_float(&mut self, negative: bool) -> Result<Option<Value>, ParseError> {
+ fn consume_signed_dot_float(&mut self, negative: bool) -> Result<Option<E::Value>, ParseError> {
// Probe the token after `.` via a shadow lexer; only commit if
// it's a Number.
let mut probe = Lexer::with_pos(self.src, self.peek1.end);
@@ -1860,7 +1873,7 @@ impl<'a> Parser<'a> {
self.bump()?; // dot
let n = self.bump()?; // digits
let src = format!(".{}", self.text(n));
- Ok(Some(parse_number_literal(&src, negative)?))
+ Ok(Some(parse_number_literal(&self.emit, &src, negative)?))
}
pub(crate) fn set_lexer_pos(&mut self, pos: usize) -> Result<(), ParseError> {
@@ -1870,7 +1883,7 @@ impl<'a> Parser<'a> {
Ok(())
}
- fn parse_paren_or_tuple(&mut self) -> Result<Value, ParseError> {
+ fn parse_paren_or_tuple(&mut self) -> Result<E::Value, ParseError> {
// Capture the outer-LParen start before consuming it. cpp's
// `ColumnExprColumnsReplace` / `ColumnExprColumnsExcludeReplace`
// grammar alts (`LPAREN ASTERISK [EXCLUDE(...)]? REPLACE(...) RPAREN`)
@@ -1913,7 +1926,7 @@ impl<'a> Parser<'a> {
// Exclude-only `(* EXCLUDE (...))` is a regular ColumnExprAsterisk
// inside ColumnExprParens (pass-through), so REPLACE is the
// distinguishing marker.
- if is_paren_form_columns_replace(&result) {
+ if is_paren_form_columns_replace(&self.emit, &result) {
let end = self.last_consumed_end;
return Ok(self.replace_pos_to(result, outer_start, end));
}
@@ -1922,7 +1935,7 @@ impl<'a> Parser<'a> {
/// `parse_paren_or_tuple` arm: ColumnExprParens or ColumnExprTuple
/// after the leading `(` has been consumed.
- fn parse_paren_expr_or_tuple_arm(&mut self) -> Result<Value, ParseError> {
+ fn parse_paren_expr_or_tuple_arm(&mut self) -> Result<E::Value, ParseError> {
let first = self.parse_expr_bp(0)?;
if self.eat(TokenKind::Comma)? {
let mut exprs = vec![first];
@@ -1938,7 +1951,7 @@ impl<'a> Parser<'a> {
}
}
self.expect(TokenKind::RParen, ")")?;
- Ok(emit::tuple_(exprs))
+ Ok(self.emit.tuple_(exprs))
} else {
self.expect(TokenKind::RParen, ")")?;
Ok(first)
@@ -2365,7 +2378,7 @@ impl<'a> Parser<'a> {
)
}
- fn parse_array_literal(&mut self) -> Result<Value, ParseError> {
+ fn parse_array_literal(&mut self) -> Result<E::Value, ParseError> {
self.expect(TokenKind::LBracket, "[")?;
let mut exprs = Vec::new();
if self.peek() != TokenKind::RBracket {
@@ -2380,7 +2393,7 @@ impl<'a> Parser<'a> {
}
}
self.expect(TokenKind::RBracket, "]")?;
- Ok(emit::array_(exprs))
+ Ok(self.emit.array_(exprs))
}
/// Identifier-led primary: either a function call (`IDENT (args)`) or
@@ -2388,7 +2401,7 @@ impl<'a> Parser<'a> {
/// function-call form covers the full grammar shape: parametric calls
/// (`quantile(0.95)(x)`), DISTINCT, in-arg ORDER BY, trailing FILTER,
/// and WITHIN GROUP (which forces the first paren list to be params).
- pub(crate) fn parse_ident_lead(&mut self) -> Result<Value, ParseError> {
+ pub(crate) fn parse_ident_lead(&mut self) -> Result<E::Value, ParseError> {
let head = self.bump()?;
let name = identifier_text(self.text(head), head.kind);
@@ -2406,7 +2419,7 @@ impl<'a> Parser<'a> {
// `addPositionInfo`, so NamedArgument has no `start`/`end`.
// Mark via `no_pos` so the outer `parse_expr_bp` pratt-loop
// wrap leaves it bare.
- return Ok(emit::named_argument(&name, value));
+ return Ok(self.emit.named_argument(&name, value));
}
// Statement-RHS guard: `f (x) := y` is `f` (an exprStmt) then
@@ -2418,7 +2431,7 @@ impl<'a> Parser<'a> {
&& self.stop_postfix_call_before_colon_equals
&& self.paren_block_then_colon_equals(self.peek0.end)
{
- return Ok(json!({"node": "Field", "chain": [name]}));
+ return Ok(self.emit.field(vec![self.emit.string(&name)]));
}
if self.peek() == TokenKind::LParen {
@@ -2469,26 +2482,12 @@ impl<'a> Parser<'a> {
));
}
self.bump()?;
- let mut obj = serde_json::Map::new();
- obj.insert("node".into(), Value::String("WindowFunction".into()));
- obj.insert("name".into(), Value::String(name.clone()));
- obj.insert("exprs".into(), Value::Array(first_args.clone()));
- // cpp's `VISIT(ColumnExprWinFunction)` always emits an
- // `args` field — the empty list for the single-paren
- // form, the second paren list for the parametric form.
- // The Python AST has `args: Optional[list[Expr]]` where
- // `[]` and `None` are NOT equal under dataclass `__eq__`,
- // so emitting `[]` here matches cpp's deserialised shape.
- obj.insert("args".into(), Value::Array(Vec::new()));
- // WindowFunction has no `filter_expr` field on the AST;
- // drop the captured FILTER expression. The C++ side
- // similarly doesn't model it on the window-function path.
drop(filter_expr_for_window);
- if self.peek() == TokenKind::LParen {
+ let (over_expr, over_identifier) = if self.peek() == TokenKind::LParen {
self.bump()?;
let we = self.parse_window_expr()?;
self.expect(TokenKind::RParen, ")")?;
- obj.insert("over_expr".into(), we);
+ (Some(we), None)
} else {
let tok = self.bump()?;
let id = match tok.kind {
@@ -2502,9 +2501,15 @@ impl<'a> Parser<'a> {
)))
}
};
- obj.insert("over_identifier".into(), Value::String(id));
- }
- return Ok(Value::Object(obj));
+ (None, Some(id))
+ };
+ return Ok(self.emit.window_function(
+ &name,
+ first_args.clone(),
+ Vec::new(),
+ over_expr,
+ over_identifier,
+ ));
}
// `name(params) WITHIN GROUP (ORDER BY ... [INTERPOLATE (...)])`.
@@ -2554,7 +2559,7 @@ impl<'a> Parser<'a> {
}
}
self.expect(TokenKind::RParen, ")")?;
- return Ok(emit::call_full(
+ return Ok(self.emit.call_full(
&name,
Some(first_args),
vec![],
@@ -2576,7 +2581,7 @@ impl<'a> Parser<'a> {
// Single-paren call. `filter_expr_for_window` was consumed
// by the window-function probe above; re-use it so we don't
// double-parse the FILTER.
- return Ok(emit::call_full(
+ return Ok(self.emit.call_full(
&name,
None,
first_args,
@@ -2587,7 +2592,7 @@ impl<'a> Parser<'a> {
));
}
- let mut chain: Vec<Value> = vec![Value::String(name)];
+ let mut chain: Vec<E::Value> = vec![self.emit.string(&name)];
let mut ended_with_star = false;
while self.peek() == TokenKind::Dot {
// `.<number>` is a tuple access, handled by the postfix loop.
@@ -2610,7 +2615,7 @@ impl<'a> Parser<'a> {
// Stop the chain at the `*` and let the outer Pratt
// postfix loop apply DOT → ArrayAccess to whatever
// follows.
- chain.push(Value::String("*".into()));
+ chain.push(self.emit.string("*"));
ended_with_star = true;
break;
}
@@ -2621,7 +2626,10 @@ impl<'a> Parser<'a> {
)))
}
}
- chain.push(Value::String(identifier_text(self.text(part), part.kind)));
+ chain.push(
+ self.emit
+ .string(&identifier_text(self.text(part), part.kind)),
+ );
ended_with_star = false;
}
// `IDENT(.IDENT)*.* EXCLUDE (…)` — the grammar's `ColumnExprAsterisk`
@@ -2630,9 +2638,9 @@ impl<'a> Parser<'a> {
// exclude=[…])`, NOT a Field chain).
if ended_with_star && matches!(self.peek(), TokenKind::Keyword(Kw::Exclude)) {
let (exclude, _) = self.parse_columns_decorators()?;
- return Ok(emit::columns_expr(None, None, true, exclude, None));
+ return Ok(self.emit.columns_expr(None, None, true, exclude, None));
}
- Ok(emit::field(chain))
+ Ok(self.emit.field(chain))
}
/// Parse a function-call argument list with the grammar's
@@ -2704,7 +2712,7 @@ impl<'a> Parser<'a> {
}
}
- fn try_parametric_call(&mut self, name: &str) -> Result<Value, ParseError> {
+ fn try_parametric_call(&mut self, name: &str) -> Result<E::Value, ParseError> {
self.expect(TokenKind::LParen, "(")?;
let params = self.parse_arg_list(TokenKind::RParen)?;
// A bare `selectSetStmt` inside the first paren means this is
@@ -2718,7 +2726,7 @@ impl<'a> Parser<'a> {
// the second paren as `ExprCall`.
if params.iter().any(|p| {
matches!(
- p.get("node").and_then(Value::as_str),
+ self.emit.node_kind(p).as_deref(),
Some("SelectQuery") | Some("SelectSetQuery")
)
}) {
@@ -2746,19 +2754,12 @@ impl<'a> Parser<'a> {
let filter_expr = self.parse_optional_filter()?;
if matches!(self.peek(), TokenKind::Keyword(Kw::Over)) {
self.bump()?;
- let mut obj = serde_json::Map::new();
- obj.insert("node".into(), Value::String("WindowFunction".into()));
- obj.insert("name".into(), Value::String(name.to_string()));
- obj.insert("exprs".into(), Value::Array(params));
- obj.insert("args".into(), Value::Array(args));
- // WindowFunction has no slots for FILTER / DISTINCT / ORDER
- // BY in the args paren; drop them to mirror the cpp visitor.
drop((distinct, order_by, filter_expr));
- if self.peek() == TokenKind::LParen {
+ let (over_expr, over_identifier) = if self.peek() == TokenKind::LParen {
self.bump()?;
let we = self.parse_window_expr()?;
self.expect(TokenKind::RParen, ")")?;
- obj.insert("over_expr".into(), we);
+ (Some(we), None)
} else {
let tok = self.bump()?;
let id = match tok.kind {
@@ -2772,11 +2773,13 @@ impl<'a> Parser<'a> {
)))
}
};
- obj.insert("over_identifier".into(), Value::String(id));
- }
- return Ok(Value::Object(obj));
+ (None, Some(id))
+ };
+ return Ok(self
+ .emit
+ .window_function(name, params, args, over_expr, over_identifier));
}
- Ok(emit::call_full(
+ Ok(self.emit.call_full(
name,
Some(params),
args,
@@ -2797,7 +2800,7 @@ impl<'a> Parser<'a> {
&& matches!(self.peek_next(), TokenKind::Keyword(Kw::By))
}
- fn parse_function_args_inner(&mut self) -> Result<FunctionArgs, ParseError> {
+ fn parse_function_args_inner(&mut self) -> Result<FunctionArgs<E::Value>, ParseError> {
// Only consume DISTINCT as the args-keyword when what follows can
// legitimately continue the rule (`RPAREN`, `ORDER`, or the start
// of a columnExpr). cpp's ANTLR otherwise parses DISTINCT as a
@@ -2815,7 +2818,7 @@ impl<'a> Parser<'a> {
} else {
false
};
- let mut args: Vec<Value> = Vec::new();
+ let mut args: Vec<E::Value> = Vec::new();
if self.peek() != TokenKind::RParen && !self.peek_starts_in_arg_order_by() {
loop {
args.push(self.parse_call_argument_for_function()?);
@@ -2837,7 +2840,7 @@ impl<'a> Parser<'a> {
Ok((distinct, args, order_by))
}
- fn parse_optional_filter(&mut self) -> Result<Option<Value>, ParseError> {
+ fn parse_optional_filter(&mut self) -> Result<Option<E::Value>, ParseError> {
if !matches!(self.peek(), TokenKind::Keyword(Kw::Filter)) {
return Ok(None);
}
@@ -2862,7 +2865,7 @@ impl<'a> Parser<'a> {
/// Parse a comma-separated list of `orderExpr` items — `expr [ASC|DESC]
/// [NULLS FIRST|LAST] [COLLATE STRING_LITERAL] [WITH FILL …]`.
- pub(crate) fn parse_order_expr_list(&mut self) -> Result<Vec<Value>, ParseError> {
+ pub(crate) fn parse_order_expr_list(&mut self) -> Result<Vec<E::Value>, ParseError> {
let mut out = Vec::new();
loop {
let order_start = self.peek0.start;
@@ -2910,25 +2913,15 @@ impl<'a> Parser<'a> {
} else {
None
};
- let mut obj = serde_json::Map::new();
- obj.insert("node".into(), Value::String("WithFillExpr".into()));
- if let Some(v) = from_value {
- obj.insert("from_value".into(), v);
- }
- if let Some(v) = to_value {
- obj.insert("to_value".into(), v);
- }
- if let Some(v) = step_value {
- obj.insert("step_value".into(), v);
- }
+ let wfe = self.emit.with_fill_expr(from_value, to_value, step_value);
// cpp's `WithFill` visitor calls `addPositionInfo(json, ctx)`,
// so the JSON has `start` / `end` spanning the `WITH FILL ...`
// tokens. Wrap before stuffing into OrderExpr.
- Some(self.wrap_pos(Value::Object(obj), with_fill_start))
+ Some(self.wrap_pos(wfe, with_fill_start))
} else {
None
};
- out.push(self.wrap_pos(emit::order_expr(expr, order, with_fill), order_start));
+ out.push(self.wrap_pos(self.emit.order_expr(expr, order, with_fill), order_start));
if !self.eat(TokenKind::Comma)? {
break;
}
@@ -2961,7 +2954,7 @@ impl<'a> Parser<'a> {
// lowercasing the rest. The grammar's `columnTypeExpr` resolves
// through `identifier`, so a `"foo"` type token is semantically
// the bare ident `foo`; cpp `visitIdentifier` strips the quotes.
- fn token_text(parser: &Parser<'_>, t: Token) -> String {
+ fn token_text<E: Emitter + Clone>(parser: &Parser<'_, E>, t: Token) -> String {
let raw = parser.text(t);
match t.kind {
TokenKind::QuotedIdent => identifier_text(raw, t.kind).to_ascii_lowercase(),
@@ -3455,7 +3448,7 @@ impl<'a> Parser<'a> {
false
}
- pub(crate) fn parse_expr_list_until_paren(&mut self) -> Result<Vec<Value>, ParseError> {
+ pub(crate) fn parse_expr_list_until_paren(&mut self) -> Result<Vec<E::Value>, ParseError> {
let mut out = Vec::new();
if self.peek() == TokenKind::RParen {
return Ok(out);
@@ -3472,7 +3465,9 @@ impl<'a> Parser<'a> {
Ok(out)
}
- pub(crate) fn parse_expr_list_until_terminators(&mut self) -> Result<Vec<Value>, ParseError> {
+ pub(crate) fn parse_expr_list_until_terminators(
+ &mut self,
+ ) -> Result<Vec<E::Value>, ParseError> {
let mut out = Vec::new();
out.push(self.parse_expr_bp(0)?);
// cpp's `columnExprList: columnExpr (COMMA columnExpr)*` — after
@@ -3776,7 +3771,7 @@ impl<'a> Parser<'a> {
pub(crate) fn parse_arg_list(
&mut self,
terminator: TokenKind,
- ) -> Result<Vec<Value>, ParseError> {
+ ) -> Result<Vec<E::Value>, ParseError> {
let mut args = Vec::new();
if self.peek() == terminator {
return Ok(args);
@@ -3797,7 +3792,7 @@ impl<'a> Parser<'a> {
/// argument shape `ident := expr` which is grammar-bound to call sites,
/// and a `SELECT …` subquery (`f(select 1)`) which the grammar's
/// `ColumnExprCallSelect` allows.
- fn parse_call_argument(&mut self) -> Result<Value, ParseError> {
+ fn parse_call_argument(&mut self) -> Result<E::Value, ParseError> {
// Default caller: `parse_arg_list`, which is the postfix `(...)`
// form (cpp's `ColumnExprCallSelect`). The grammar there admits
// a selectSetStmt as the entire body — including its
@@ -3816,14 +3811,14 @@ impl<'a> Parser<'a> {
/// vs 237), so a trailing `ORDER BY` after the inner paren-wrapped
/// SELECT belongs to the outer `Call.order_by`, not the inner
/// SetStmt wrapper.
- fn parse_call_argument_for_function(&mut self) -> Result<Value, ParseError> {
+ fn parse_call_argument_for_function(&mut self) -> Result<E::Value, ParseError> {
self.parse_call_argument_with(true)
}
fn parse_call_argument_with(
&mut self,
suppress_inner_trailing_order_by: bool,
- ) -> Result<Value, ParseError> {
+ ) -> Result<E::Value, ParseError> {
// cpp's `ColumnExprNamedArg: identifier COLONEQUALS columnExpr`
// admits the full `identifier` rule — IDENT / QUOTED_IDENTIFIER /
// any keyword accepted by `kw_valid_as_identifier`. That includes
@@ -3841,7 +3836,7 @@ impl<'a> Parser<'a> {
let name = identifier_text(self.text(name_tok), name_tok.kind);
self.bump()?; // consume `:=`
let value = self.parse_expr_bp(0)?;
- return Ok(emit::named_argument(&name, value));
+ return Ok(self.emit.named_argument(&name, value));
}
// A function-call argument is either a selectSetStmt (cpp's
// ColumnExprCallSelect) or a regular columnExpr. The grammar
@@ -3868,7 +3863,7 @@ impl<'a> Parser<'a> {
fn parse_call_argument_select(
&mut self,
suppress_trailing_order_by: bool,
- ) -> Result<Value, ParseError> {
+ ) -> Result<E::Value, ParseError> {
// Selectively suppress the SetStmt-wrapper-level ORDER BY when
// the caller is the named-function-call path (cpp's
// `ColumnExprFunction`). For the postfix call-select form
@@ -3882,7 +3877,8 @@ impl<'a> Parser<'a> {
let result = self.parse_select_set_stmt();
self.suppress_setstmt_trailing_order_by = prev;
let v = result?;
- let kind = v.get("node").and_then(Value::as_str);
+ let kind = self.emit.node_kind(&v);
+ let kind = kind.as_deref();
if matches!(
kind,
Some("SelectQuery") | Some("SelectSetQuery") | Some("Placeholder")
@@ -3924,13 +3920,13 @@ impl<'a> Parser<'a> {
// ---- Postfix --------------------------------------------------------
- fn parse_postfix(&mut self, kind: TokenKind, lhs: Value) -> Result<Value, ParseError> {
+ fn parse_postfix(&mut self, kind: TokenKind, lhs: E::Value) -> Result<E::Value, ParseError> {
match kind {
TokenKind::LParen => {
self.bump()?;
let args = self.parse_arg_list(TokenKind::RParen)?;
self.expect(TokenKind::RParen, ")")?;
- Ok(fold_call_or_exprcall(lhs, args))
+ Ok(fold_call_or_exprcall(&self.emit, lhs, args))
}
TokenKind::LBracket => {
self.bump()?;
@@ -3945,7 +3941,7 @@ impl<'a> Parser<'a> {
Some(self.parse_expr_bp(0)?)
};
self.expect(TokenKind::RBracket, "]")?;
- return Ok(emit::array_slice(lhs, None, end));
+ return Ok(self.emit.array_slice(lhs, None, end));
}
let first = self.parse_expr_bp(0)?;
if self.eat(TokenKind::Colon)? {
@@ -3955,10 +3951,10 @@ impl<'a> Parser<'a> {
Some(self.parse_expr_bp(0)?)
};
self.expect(TokenKind::RBracket, "]")?;
- return Ok(emit::array_slice(lhs, Some(first), end));
+ return Ok(self.emit.array_slice(lhs, Some(first), end));
}
self.expect(TokenKind::RBracket, "]")?;
- Ok(emit::array_access(lhs, first, false))
+ Ok(self.emit.array_access(lhs, first, false))
}
TokenKind::DoubleColon => {
self.bump()?;
@@ -4005,7 +4001,7 @@ impl<'a> Parser<'a> {
} else {
name
};
- Ok(emit::type_cast(lhs, &full))
+ Ok(self.emit.type_cast(lhs, &full))
}
TokenKind::Dot => {
self.bump()?;
@@ -4026,13 +4022,13 @@ impl<'a> Parser<'a> {
let n: i64 = text.parse().map_err(|_| {
self.err(format!("expected integer after '.', got {:?}", text))
})?;
- Ok(emit::tuple_access(lhs, n, false))
+ Ok(self.emit.tuple_access(lhs, n, false))
}
TokenKind::Ident | TokenKind::QuotedIdent => {
let name = identifier_text(self.text(part), part.kind);
- Ok(emit::array_access(
+ Ok(self.emit.array_access(
lhs,
- emit::constant(Value::String(name)),
+ self.emit.constant(self.emit.string(&name)),
false,
))
}
@@ -4045,9 +4041,9 @@ impl<'a> Parser<'a> {
// `ArrayAccess(a, "null")`.
TokenKind::Keyword(kw) if kw_valid_as_identifier(kw) => {
let name = identifier_text(self.text(part), part.kind);
- Ok(emit::array_access(
+ Ok(self.emit.array_access(
lhs,
- emit::constant(Value::String(name)),
+ self.emit.constant(self.emit.string(&name)),
false,
))
}
@@ -4064,7 +4060,7 @@ impl<'a> Parser<'a> {
self.bump()?;
let property = self.parse_expr_bp(0)?;
self.expect(TokenKind::RBracket, "]")?;
- return Ok(emit::array_access(lhs, property, true));
+ return Ok(self.emit.array_access(lhs, property, true));
}
let part = self.bump()?;
match part.kind {
@@ -4080,21 +4076,21 @@ impl<'a> Parser<'a> {
let n: i64 = text.parse().map_err(|_| {
self.err(format!("expected integer after '?.', got {:?}", text))
})?;
- Ok(emit::tuple_access(lhs, n, true))
+ Ok(self.emit.tuple_access(lhs, n, true))
}
TokenKind::Ident | TokenKind::QuotedIdent => {
let name = identifier_text(self.text(part), part.kind);
- Ok(emit::array_access(
+ Ok(self.emit.array_access(
lhs,
- emit::constant(Value::String(name)),
+ self.emit.constant(self.emit.string(&name)),
true,
))
}
TokenKind::Keyword(kw) if kw_valid_as_identifier(kw) => {
let name = identifier_text(self.text(part), part.kind);
- Ok(emit::array_access(
+ Ok(self.emit.array_access(
lhs,
- emit::constant(Value::String(name)),
+ self.emit.constant(self.emit.string(&name)),
true,
))
}
@@ -4167,7 +4163,7 @@ impl<'a> Parser<'a> {
fn try_special_infix(
&mut self,
kind: TokenKind,
- lhs: &mut Value,
+ lhs: &mut E::Value,
min_bp: u8,
lhs_start: usize,
) -> Result<Option<bool>, ParseError> {
@@ -4236,13 +4232,13 @@ impl<'a> Parser<'a> {
// chain (since BP_IS_NULL > BP_IS_DISTINCT_FROM)
// but blocks a second IS NOT DISTINCT FROM.
let rhs = self.parse_expr_bp(BP_IS_DISTINCT_FROM + 1)?;
- let prev = lhs.take();
- *lhs = emit::is_distinct_from(prev, rhs, negated);
+ let prev = std::mem::replace(lhs, self.emit.null());
+ *lhs = self.emit.is_distinct_from(prev, rhs, negated);
return Ok(Some(true));
}
self.expect_kw(Kw::Null, "NULL")?;
- let prev = lhs.take();
- *lhs = emit::compare_is_null(prev, negated);
+ let prev = std::mem::replace(lhs, self.emit.null());
+ *lhs = self.emit.compare_is_null(prev, negated);
Ok(Some(true))
}
// `NOT BETWEEN ...` / `NOT IN ...` / `NOT LIKE ...` / `NOT ILIKE ...`
@@ -4254,7 +4250,7 @@ impl<'a> Parser<'a> {
self.bump()?;
self.bump()?;
let (low, high, hoisted) = self.parse_between_body(min_bp)?;
- let prev = lhs.take();
+ let prev = std::mem::replace(lhs, self.emit.null());
// Wrap the inner BetweenExpr with positions BEFORE the hoist loop. When a hoist
// wrapper (Or / Ternary / Alias / Arith) is applied, the outer pratt-loop wrap_pos
// at line ~126 stamps positions onto the OUTERMOST wrapper, but the BetweenExpr
@@ -4262,14 +4258,17 @@ impl<'a> Parser<'a> {
// and would not otherwise receive a span. cpp emits position info on BetweenExpr
// unconditionally — match that. Use `high.end` (not `last_consumed_end`) — see
// the BETWEEN arm below for the rationale.
- let high_end = high.get("end").cloned();
- let between_inner = emit::between(prev, low, high, true);
+ let high_end = self.emit.get_field(&high, "end");
+ let between_inner = self.emit.between(prev, low, high, true);
let mut between = match high_end {
- Some(end) => emit::with_pos(between_inner, self.pos_obj(lhs_start), end),
+ Some(end) => {
+ self.emit
+ .with_pos(between_inner, self.pos_obj(lhs_start), end)
+ }
None => self.wrap_pos(between_inner, lhs_start),
};
for hoist in hoisted {
- between = apply_between_hoist(between, hoist);
+ between = apply_between_hoist(&self.emit, between, hoist);
}
*lhs = between;
Ok(Some(true))
@@ -4283,8 +4282,8 @@ impl<'a> Parser<'a> {
let cohort = self.try_consume_cohort_marker()?;
let rhs = self.parse_expr_bp(BP_COMPARE + 1)?;
let op = if cohort { "not in cohort" } else { "not in" };
- let prev = lhs.take();
- *lhs = emit::compare(prev, op, rhs);
+ let prev = std::mem::replace(lhs, self.emit.null());
+ *lhs = self.emit.compare(prev, op, rhs);
Ok(Some(true))
}
TokenKind::Keyword(Kw::Like) => {
@@ -4294,8 +4293,8 @@ impl<'a> Parser<'a> {
self.bump()?;
self.bump()?;
let rhs = self.parse_expr_bp(BP_COMPARE + 1)?;
- let prev = lhs.take();
- *lhs = emit::compare(prev, "not like", rhs);
+ let prev = std::mem::replace(lhs, self.emit.null());
+ *lhs = self.emit.compare(prev, "not like", rhs);
Ok(Some(true))
}
TokenKind::Keyword(Kw::Ilike) => {
@@ -4305,8 +4304,8 @@ impl<'a> Parser<'a> {
self.bump()?;
self.bump()?;
let rhs = self.parse_expr_bp(BP_COMPARE + 1)?;
- let prev = lhs.take();
- *lhs = emit::compare(prev, "not ilike", rhs);
+ let prev = std::mem::replace(lhs, self.emit.null());
+ *lhs = self.emit.compare(prev, "not ilike", rhs);
Ok(Some(true))
}
_ => Ok(None),
@@ -4318,19 +4317,21 @@ impl<'a> Parser<'a> {
}
self.bump()?;
let (low, high, hoisted) = self.parse_between_body(min_bp)?;
- let prev = lhs.take();
+ let prev = std::mem::replace(lhs, self.emit.null());
// The inner BetweenExpr's structural end is `high.end`, not `self.last_consumed_end`.
// When `parse_between_body`'s WIDE arm absorbs a nested BETWEEN and the split hoists
// it back out (`BetweenHoist::Between`), `last_consumed_end` is past the high we'll
// actually use; mirror cpp's per-ctx span by reading the end off `high` directly.
- let high_end = high.get("end").cloned();
- let between_inner = emit::between(prev, low, high, false);
+ let high_end = self.emit.get_field(&high, "end");
+ let between_inner = self.emit.between(prev, low, high, false);
let mut between = match high_end {
- Some(end) => emit::with_pos(between_inner, self.pos_obj(lhs_start), end),
+ Some(end) => self
+ .emit
+ .with_pos(between_inner, self.pos_obj(lhs_start), end),
None => self.wrap_pos(between_inner, lhs_start),
};
for hoist in hoisted {
- between = apply_between_hoist(between, hoist);
+ between = apply_between_hoist(&self.emit, between, hoist);
}
*lhs = between;
Ok(Some(true))
@@ -4350,8 +4351,8 @@ impl<'a> Parser<'a> {
let cohort = self.try_consume_cohort_marker()?;
let rhs = self.parse_expr_bp(BP_COMPARE + 1)?;
let op = if cohort { "in cohort" } else { "in" };
- let prev = lhs.take();
- *lhs = emit::compare(prev, op, rhs);
+ let prev = std::mem::replace(lhs, self.emit.null());
+ *lhs = self.emit.compare(prev, op, rhs);
Ok(Some(true))
}
TokenKind::Keyword(Kw::Like) => {
@@ -4360,8 +4361,8 @@ impl<'a> Parser<'a> {
}
self.bump()?;
let rhs = self.parse_expr_bp(BP_COMPARE + 1)?;
- let prev = lhs.take();
- *lhs = emit::compare(prev, "like", rhs);
+ let prev = std::mem::replace(lhs, self.emit.null());
+ *lhs = self.emit.compare(prev, "like", rhs);
Ok(Some(true))
}
TokenKind::Keyword(Kw::Ilike) => {
@@ -4370,8 +4371,8 @@ impl<'a> Parser<'a> {
}
self.bump()?;
let rhs = self.parse_expr_bp(BP_COMPARE + 1)?;
- let prev = lhs.take();
- *lhs = emit::compare(prev, "ilike", rhs);
+ let prev = std::mem::replace(lhs, self.emit.null());
+ *lhs = self.emit.compare(prev, "ilike", rhs);
Ok(Some(true))
}
// `e IGNORE NULLS` is a postfix that the C++ visitor drops
@@ -4383,7 +4384,8 @@ impl<'a> Parser<'a> {
}
self.bump()?;
self.bump()?;
- *lhs = emit::ignore_nulls(lhs.take());
+ let prev = std::mem::replace(lhs, self.emit.null());
+ *lhs = self.emit.ignore_nulls(prev);
Ok(Some(true))
}
@@ -4396,8 +4398,8 @@ impl<'a> Parser<'a> {
let then_branch = self.parse_expr_bp(0)?;
self.expect(TokenKind::Colon, ":")?;
let else_branch = self.parse_expr_bp(BP_TERNARY)?;
- let prev = lhs.take();
- *lhs = emit::call("if", vec![prev, then_branch, else_branch]);
+ let prev = std::mem::replace(lhs, self.emit.null());
+ *lhs = self.emit.call("if", vec![prev, then_branch, else_branch]);
Ok(Some(true))
}
// `AS alias`
@@ -4483,8 +4485,8 @@ impl<'a> Parser<'a> {
tok.end,
));
}
- let prev = lhs.take();
- *lhs = emit::alias(prev, &name);
+ let prev = std::mem::replace(lhs, self.emit.null());
+ *lhs = self.emit.alias(prev, &name);
Ok(Some(true))
}
_ => Ok(None),
@@ -4532,7 +4534,10 @@ impl<'a> Parser<'a> {
///
/// Both alts share the same post-parse split + literal-AND
/// fallback; the difference is just the starting BP.
- fn parse_between_body(&mut self, outer_min_bp: u8) -> Result<BetweenSplit, ParseError> {
+ fn parse_between_body(
+ &mut self,
+ outer_min_bp: u8,
+ ) -> Result<BetweenSplit<E::Value>, ParseError> {
// Depth-aware arm ordering:
// - OUTERMOST call (depth=0): WIDE first. The body greedy
// parse maximizes what's inside the OUTER BETWEEN; split
@@ -4592,7 +4597,7 @@ impl<'a> Parser<'a> {
&mut self,
start_bp: u8,
outer_min_bp: u8,
- ) -> Result<BetweenSplit, ParseError> {
+ ) -> Result<BetweenSplit<E::Value>, ParseError> {
let (low, high, hoisted) = Self::parse_between_body_arm(self, start_bp)?;
if hoisted.iter().any(|h| hoist_min_bp(h) <= outer_min_bp) {
return Err(
@@ -4605,9 +4610,12 @@ impl<'a> Parser<'a> {
/// Shared body of `parse_between_body`'s two `try_alt` arms,
/// parameterized by the starting binding power. See
/// `parse_between_body` for the narrow/wide rationale.
- fn parse_between_body_arm(&mut self, start_bp: u8) -> Result<BetweenSplit, ParseError> {
+ fn parse_between_body_arm(
+ &mut self,
+ start_bp: u8,
+ ) -> Result<BetweenSplit<E::Value>, ParseError> {
let chain = self.parse_expr_bp(start_bp)?;
- if let Some((low, high, hoisted)) = split_at_rightmost_and(&chain) {
+ if let Some((low, high, hoisted)) = split_at_rightmost_and(&self.emit, &chain) {
return Ok((low, high, hoisted));
}
// The body had no AND that the split could find — consume the
@@ -4840,16 +4848,16 @@ fn peek_can_start_clause_body(tok: TokenKind) -> bool {
/// high), then, else)`), we hoist the ternary's then/else out to
/// wrap the BetweenExpr the caller builds.
#[derive(Debug, Clone)]
-pub(crate) enum BetweenHoist {
+pub(crate) enum BetweenHoist<V> {
Alias(String),
Between {
- low: Value,
- high: Value,
+ low: V,
+ high: V,
negated: bool,
},
Ternary {
- then_branch: Value,
- else_branch: Value,
+ then_branch: V,
+ else_branch: V,
},
/// `Or(left_siblings ... , <expr>, right_siblings ...)` — the
/// greedy body parse absorbed an OR whose AND-carrying child sits
@@ -4858,8 +4866,8 @@ pub(crate) enum BetweenHoist {
/// BETWEEN's high body, so the OR (and its siblings) become an
/// outer wrapper around the alias-wrapped BetweenExpr.
Or {
- left_siblings: Vec<Value>,
- right_siblings: Vec<Value>,
+ left_siblings: Vec<V>,
+ right_siblings: Vec<V>,
},
/// `IsDistinctFrom(<expr>, right, negated?)` — `BETWEEN body AND
/// high AS al IS [NOT] DISTINCT FROM rhs` parses with the IS
@@ -4868,7 +4876,7 @@ pub(crate) enum BetweenHoist {
/// terminates BETWEEN's high body, and IS DISTINCT FROM applies
/// to the alias-wrapped BetweenExpr).
IsDistinctFrom {
- right: Value,
+ right: V,
negated: bool,
},
/// `IsNull(<expr>, negated?)` — `BETWEEN body AND high AS al IS
@@ -4885,7 +4893,7 @@ pub(crate) enum BetweenHoist {
/// with the alias, we hoist it OUTSIDE the alias around the
/// BetweenExpr.
ArrayAccess {
- property: Value,
+ property: V,
nullish: bool,
},
/// `ExprCall(<expr>, args)` — postfix `(<args>)` on top of the
@@ -4896,14 +4904,14 @@ pub(crate) enum BetweenHoist {
/// the ExprCall hoists out alongside the alias to wrap the
/// final BetweenExpr.
ExprCall {
- args: Vec<Value>,
+ args: Vec<V>,
},
/// `TypeCast(<expr>, "<type-ident>")` — postfix `:: <type>` at
/// BP_POSTFIX=130. Same hoisting rationale as ExprCall: the
/// type-cast attaches OUTSIDE the BetweenExpr after the inner
/// AND-bearing wrapper chain is peeled.
TypeCast {
- type_name: Value,
+ type_name: String,
},
/// `TupleAccess(<tuple>, index, nullish?)` — postfix `.<NUMBER>`
/// / `?.<NUMBER>` at BP_POSTFIX=130. Same hoisting rationale as
@@ -4926,14 +4934,14 @@ pub(crate) enum BetweenHoist {
/// rather than hoisting.)
ArithmeticOperation {
op: String,
- right: Value,
+ right: V,
},
}
/// Result of finding the BETWEEN separator AND inside a greedy body
/// parse. `hoisted` wrappers are applied around the BetweenExpr by
/// the caller of `parse_between_body`, innermost first.
-type BetweenSplit = (Value, Value, Vec<BetweenHoist>);
+type BetweenSplit<V> = (V, V, Vec<BetweenHoist<V>>);
/// The lowest binding power at which this hoist's outer wrapper can
/// fire. Used by `parse_between_body_arm_wide` to detect when an
@@ -4941,7 +4949,7 @@ type BetweenSplit = (Value, Value, Vec<BetweenHoist>);
/// would itself claim the wrapper — in which case the WIDE arm must
/// reject so the wrapper attaches at the outer level instead of
/// being applied INSIDE the BETWEEN.
-fn hoist_min_bp(hoist: &BetweenHoist) -> u8 {
+fn hoist_min_bp<V>(hoist: &BetweenHoist<V>) -> u8 {
match hoist {
BetweenHoist::Alias(_) => BP_ALIAS,
BetweenHoist::Ternary { .. } => BP_TERNARY,
@@ -4964,82 +4972,50 @@ fn hoist_min_bp(hoist: &BetweenHoist) -> u8 {
}
/// Apply one outer wrapper around an in-progress BetweenExpr.
-fn apply_between_hoist(expr: Value, hoist: BetweenHoist) -> Value {
+fn apply_between_hoist<E: Emitter>(
+ emit: &E,
+ expr: E::Value,
+ hoist: BetweenHoist<E::Value>,
+) -> E::Value {
match hoist {
- BetweenHoist::Alias(name) => emit::alias(expr, &name),
- BetweenHoist::Between { low, high, negated } => emit::between(expr, low, high, negated),
+ BetweenHoist::Alias(name) => emit.alias(expr, &name),
+ BetweenHoist::Between { low, high, negated } => emit.between(expr, low, high, negated),
BetweenHoist::Ternary {
then_branch,
else_branch,
- } => emit::call("if", vec![expr, then_branch, else_branch]),
+ } => emit.call("if", vec![expr, then_branch, else_branch]),
BetweenHoist::Or {
left_siblings,
right_siblings,
} => {
- let mut all: Vec<Value> = left_siblings;
+ let mut all: Vec<E::Value> = left_siblings;
all.push(expr);
all.extend(right_siblings);
- emit::or_(all)
+ emit.or_(all)
}
BetweenHoist::IsDistinctFrom { right, negated } => {
- serde_json::json!({
- "node": "IsDistinctFrom",
- "left": expr,
- "right": right,
- "negated": negated,
- })
- }
- BetweenHoist::IsNull { negated } => emit::compare_is_null(expr, negated),
- BetweenHoist::ArrayAccess { property, nullish } => {
- let mut obj = serde_json::Map::new();
- obj.insert("node".into(), Value::String("ArrayAccess".into()));
- obj.insert("array".into(), expr);
- obj.insert("property".into(), property);
- if nullish {
- obj.insert("nullish".into(), Value::Bool(true));
- }
- Value::Object(obj)
+ emit.is_distinct_from(expr, right, negated)
}
- BetweenHoist::ExprCall { args } => {
- let mut obj = serde_json::Map::new();
- obj.insert("node".into(), Value::String("ExprCall".into()));
- obj.insert("expr".into(), expr);
- obj.insert("args".into(), Value::Array(args));
- Value::Object(obj)
+ BetweenHoist::IsNull { negated } => emit.compare_is_null(expr, negated),
+ BetweenHoist::ArrayAccess { property, nullish } => {
+ emit.array_access(expr, property, nullish)
}
+ BetweenHoist::ExprCall { args } => emit.expr_call(expr, args),
BetweenHoist::TypeCast { type_name } => {
// Reconstruct the TypeCast node the WIDE parse produced.
// Inner field is `expr`; the type identifier is on
// `type_name` (per cpp's `VISIT(ColumnTypeExprSimple)` —
// it deserialises to the Python dataclass field of the
// same name).
- serde_json::json!({
- "node": "TypeCast",
- "expr": expr,
- "type_name": type_name,
- })
+ emit.type_cast(expr, &type_name)
}
BetweenHoist::TupleAccess { index, nullish } => {
// cpp's `VISIT(ColumnExprTupleAccess)` emits the inner
// expression on the `tuple` field, and the dot-number
// index on `index`. Mirror that.
- let mut obj = serde_json::Map::new();
- obj.insert("node".into(), Value::String("TupleAccess".into()));
- obj.insert("tuple".into(), expr);
- obj.insert("index".into(), serde_json::Value::from(index));
- if nullish {
- obj.insert("nullish".into(), Value::Bool(true));
- }
- Value::Object(obj)
- }
- BetweenHoist::ArithmeticOperation { op, right } => {
- serde_json::json!({
- "node": "ArithmeticOperation",
- "left": expr,
- "right": right,
- "op": op,
- })
+ emit.tuple_access(expr, index, nullish)
}
+ BetweenHoist::ArithmeticOperation { op, right } => emit.arith(expr, &op, right),
}
}
@@ -5052,21 +5028,21 @@ fn apply_between_hoist(expr: Value, hoist: BetweenHoist) -> Value {
/// expressions that the pratt loop wraps). Derive the span from the
/// first child's `start` and the last child's `end` so the inner
/// synthetic node carries a non-null span.
-fn stamp_span_from_children(mut node: Value, children: &[Value]) -> Value {
+fn stamp_span_from_children<E: Emitter>(
+ emit: &E,
+ node: E::Value,
+ children: &[E::Value],
+) -> E::Value {
if children.is_empty() {
return node;
}
- let start = children[0].get("start").cloned();
- let end = children[children.len() - 1].get("end").cloned();
- if let Some(obj) = node.as_object_mut() {
- if let Some(s) = start {
- obj.insert("start".into(), s);
- }
- if let Some(e) = end {
- obj.insert("end".into(), e);
- }
+ let start = emit.get_field(&children[0], "start");
+ let end = emit.get_field(&children[children.len() - 1], "end");
+ if let (Some(s), Some(e)) = (start, end) {
+ emit.replace_pos(node, s, e)
+ } else {
+ node
}
- node
}
/// Walk an already-parsed boolean tree to find the rightmost AND in
@@ -5080,10 +5056,13 @@ fn stamp_span_from_children(mut node: Value, children: &[Value]) -> Value {
/// - An `Or` node defers — walk children right-to-left so we find the
/// *latest* AND-bearing child. Reconstruct the Or above the split.
/// - Anything else has no AND in it; return None.
-fn split_at_rightmost_and(node: &Value) -> Option<BetweenSplit> {
- let node_name = node.get("node").and_then(Value::as_str);
+fn split_at_rightmost_and<E: Emitter>(emit: &E, node: &E::Value) -> Option<BetweenSplit<E::Value>> {
+ let node_name = emit.node_kind(node);
+ let node_name = node_name.as_deref();
if node_name == Some("And") {
- let exprs = node.get("exprs").and_then(Value::as_array).cloned()?;
+ let exprs = emit
+ .get_field(node, "exprs")
+ .and_then(|v| emit.as_list(&v))?;
if exprs.len() < 2 {
return None;
}
@@ -5096,7 +5075,7 @@ fn split_at_rightmost_and(node: &Value) -> Option<BetweenSplit> {
// outer high. Without this descent we'd just pop the last
// element (NamedArg) wholesale and lose that AND.
if let Some((deep_left, deep_right, hoisted)) =
- split_at_rightmost_and(&exprs[exprs.len() - 1])
+ split_at_rightmost_and(emit, &exprs[exprs.len() - 1])
{
let mut new_exprs = exprs.clone();
let last_idx = new_exprs.len() - 1;
@@ -5104,8 +5083,8 @@ fn split_at_rightmost_and(node: &Value) -> Option<BetweenSplit> {
let new_left = if new_exprs.len() == 1 {
new_exprs.into_iter().next().unwrap()
} else {
- let synthetic = emit::and_(new_exprs.clone());
- stamp_span_from_children(synthetic, &new_exprs)
+ let synthetic = emit.and_(new_exprs.clone());
+ stamp_span_from_children(emit, synthetic, &new_exprs)
};
return Some((new_left, deep_right, hoisted));
}
@@ -5115,15 +5094,18 @@ fn split_at_rightmost_and(node: &Value) -> Option<BetweenSplit> {
let left = if exprs.len() == 1 {
exprs.pop().unwrap()
} else {
- let synthetic = emit::and_(exprs.clone());
- stamp_span_from_children(synthetic, &exprs)
+ let synthetic = emit.and_(exprs.clone());
+ stamp_span_from_children(emit, synthetic, &exprs)
};
return Some((left, right, Vec::new()));
}
if node_name == Some("Or") {
- let exprs = node.get("exprs").and_then(Value::as_array).cloned()?;
+ let exprs = emit
+ .get_field(node, "exprs")
+ .and_then(|v| emit.as_list(&v))?;
for i in (0..exprs.len()).rev() {
- if let Some((left_in, right_in, mut hoisted)) = split_at_rightmost_and(&exprs[i]) {
+ if let Some((left_in, right_in, mut hoisted)) = split_at_rightmost_and(emit, &exprs[i])
+ {
if hoisted.is_empty() {
// AND was found directly inside the Or's child (no
// looser-wrapper between them). cpp's grammar lets
@@ -5131,22 +5113,22 @@ fn split_at_rightmost_and(node: &Value) -> Option<BetweenSplit> {
// children flow into the high alongside the descent
// result. `x BETWEEN low AND high OR rest` →
// BETWEEN(x, low, Or(high, rest)).
- let mut left_children: Vec<Value> = exprs[..i].to_vec();
+ let mut left_children: Vec<E::Value> = exprs[..i].to_vec();
left_children.push(left_in);
let left = if left_children.len() == 1 {
left_children.pop().unwrap()
} else {
- let synthetic = emit::or_(left_children.clone());
- stamp_span_from_children(synthetic, &left_children)
+ let synthetic = emit.or_(left_children.clone());
+ stamp_span_from_children(emit, synthetic, &left_children)
};
- let mut right_children: Vec<Value> = Vec::with_capacity(exprs.len() - i);
+ let mut right_children: Vec<E::Value> = Vec::with_capacity(exprs.len() - i);
right_children.push(right_in);
right_children.extend_from_slice(&exprs[i + 1..]);
let right = if right_children.len() == 1 {
right_children.pop().unwrap()
} else {
- let synthetic = emit::or_(right_children.clone());
- stamp_span_from_children(synthetic, &right_children)
+ let synthetic = emit.or_(right_children.clone());
+ stamp_span_from_children(emit, synthetic, &right_children)
};
return Some((left, right, hoisted));
}
@@ -5157,8 +5139,8 @@ fn split_at_rightmost_and(node: &Value) -> Option<BetweenSplit> {
// being absorbed into the high. Pushing the Or hoist
// AFTER `hoisted` puts it OUTSIDE the wrappers the
// descent has accumulated.
- let left_siblings: Vec<Value> = exprs[..i].to_vec();
- let right_siblings: Vec<Value> = exprs[i + 1..].to_vec();
+ let left_siblings: Vec<E::Value> = exprs[..i].to_vec();
+ let right_siblings: Vec<E::Value> = exprs[i + 1..].to_vec();
if !left_siblings.is_empty() || !right_siblings.is_empty() {
hoisted.push(BetweenHoist::Or {
left_siblings,
@@ -5184,11 +5166,11 @@ fn split_at_rightmost_and(node: &Value) -> Option<BetweenSplit> {
// BetweenExpr. Descend through the Alias and HOIST its name to
// the caller's outer-wrap list.
if node_name == Some("Lambda") {
- if let Some(inner) = node.get("expr") {
- if let Some((left_in, right_in, hoisted)) = split_at_rightmost_and(inner) {
- let mut new_node = node.as_object()?.clone();
- new_node.insert("expr".into(), left_in);
- return Some((Value::Object(new_node), right_in, hoisted));
+ if let Some(inner) = emit.get_field(node, "expr") {
+ if let Some((left_in, right_in, hoisted)) = split_at_rightmost_and(emit, &inner) {
+ let mut new_node = node.clone();
+ emit.set_field(&mut new_node, "expr", left_in);
+ return Some((new_node, right_in, hoisted));
}
}
}
@@ -5199,11 +5181,11 @@ fn split_at_rightmost_and(node: &Value) -> Option<BetweenSplit> {
// `Not.expr` peels the AND off so the outer BETWEEN sees its own
// `low = Not(Lambda(x, b))`, `high = c` split.
if node_name == Some("Not") {
- if let Some(inner) = node.get("expr") {
- if let Some((left_in, right_in, hoisted)) = split_at_rightmost_and(inner) {
- let mut new_node = node.as_object()?.clone();
- new_node.insert("expr".into(), left_in);
- return Some((Value::Object(new_node), right_in, hoisted));
+ if let Some(inner) = emit.get_field(node, "expr") {
+ if let Some((left_in, right_in, hoisted)) = split_at_rightmost_and(emit, &inner) {
+ let mut new_node = node.clone();
+ emit.set_field(&mut new_node, "expr", left_in);
+ return Some((new_node, right_in, hoisted));
}
}
}
@@ -5230,47 +5212,52 @@ fn split_at_rightmost_and(node: &Value) -> Option<BetweenSplit> {
// possible), cpp prefers the rightmost-in-source which lives in
// `.right`.
if node_name == Some("ArithmeticOperation") {
- if let Some(inner) = node.get("right") {
- if let Some((left_in, right_in, hoisted)) = split_at_rightmost_and(inner) {
- let mut new_node = node.as_object()?.clone();
- new_node.insert("right".into(), left_in);
- return Some((Value::Object(new_node), right_in, hoisted));
+ if let Some(inner) = emit.get_field(node, "right") {
+ if let Some((left_in, right_in, hoisted)) = split_at_rightmost_and(emit, &inner) {
+ let mut new_node = node.clone();
+ emit.set_field(&mut new_node, "right", left_in);
+ return Some((new_node, right_in, hoisted));
}
}
- if let Some(inner) = node.get("left") {
- if let Some((left_in, right_in, mut hoisted)) = split_at_rightmost_and(inner) {
- let op = node
- .get("op")
- .and_then(Value::as_str)
- .unwrap_or("")
- .to_string();
- let right = node.get("right").cloned().unwrap_or(Value::Null);
+ if let Some(inner) = emit.get_field(node, "left") {
+ if let Some((left_in, right_in, mut hoisted)) = split_at_rightmost_and(emit, &inner) {
+ let op = emit
+ .get_field(node, "op")
+ .and_then(|v| emit.as_str(&v).map(|s| s.into_owned()))
+ .unwrap_or_default();
+ let right = emit.get_field(node, "right").unwrap_or_else(|| emit.null());
hoisted.push(BetweenHoist::ArithmeticOperation { op, right });
return Some((left_in, right_in, hoisted));
}
}
}
if node_name == Some("NamedArgument") {
- if let Some(inner) = node.get("value") {
- if let Some((left_in, right_in, hoisted)) = split_at_rightmost_and(inner) {
- let mut new_node = node.as_object()?.clone();
- new_node.insert("value".into(), left_in);
- return Some((Value::Object(new_node), right_in, hoisted));
+ if let Some(inner) = emit.get_field(node, "value") {
+ if let Some((left_in, right_in, hoisted)) = split_at_rightmost_and(emit, &inner) {
+ let mut new_node = node.clone();
+ emit.set_field(&mut new_node, "value", left_in);
+ return Some((new_node, right_in, hoisted));
}
}
}
- if node_name == Some("Call") && node.get("name").and_then(Value::as_str) == Some("if") {
- if let Some(args) = node.get("args").and_then(Value::as_array) {
+ if node_name == Some("Call")
+ && emit
+ .get_field(node, "name")
+ .and_then(|v| emit.as_str(&v).map(|s| s.into_owned()))
+ .as_deref()
+ == Some("if")
+ {
+ if let Some(args) = emit.get_field(node, "args").and_then(|v| emit.as_list(&v)) {
if args.len() == 3 {
// Try the else-branch (args[2]) first: `cond ? then :
// else AND high` parses with else absorbing the AND;
// we peel and rewrap the if-call.
- if let Some((left_in, right_in, hoisted)) = split_at_rightmost_and(&args[2]) {
+ if let Some((left_in, right_in, hoisted)) = split_at_rightmost_and(emit, &args[2]) {
let mut new_args = args.clone();
new_args[2] = left_in;
- let mut new_node = node.as_object()?.clone();
- new_node.insert("args".into(), Value::Array(new_args));
- return Some((Value::Object(new_node), right_in, hoisted));
+ let mut new_node = node.clone();
+ emit.set_field(&mut new_node, "args", emit.array_(new_args));
+ return Some((new_node, right_in, hoisted));
}
// Try the cond (args[0]): `(BETWEEN body AND high) ?
// then : else` parses with the AND inside the cond of
@@ -5280,7 +5267,9 @@ fn split_at_rightmost_and(node: &Value) -> Option<BetweenSplit> {
// BetweenExpr the caller builds. The if-call node
// itself dissolves: its then/else go to the hoist, its
// cond's split becomes BETWEEN's low/high.
- if let Some((left_in, right_in, mut hoisted)) = split_at_rightmost_and(&args[0]) {
+ if let Some((left_in, right_in, mut hoisted)) =
+ split_at_rightmost_and(emit, &args[0])
+ {
hoisted.push(BetweenHoist::Ternary {
then_branch: args[1].clone(),
else_branch: args[2].clone(),
@@ -5291,17 +5280,16 @@ fn split_at_rightmost_and(node: &Value) -> Option<BetweenSplit> {
}
}
if node_name == Some("Alias") {
- if let Some(inner) = node.get("expr") {
- if let Some((left_in, right_in, mut hoisted)) = split_at_rightmost_and(inner) {
+ if let Some(inner) = emit.get_field(node, "expr") {
+ if let Some((left_in, right_in, mut hoisted)) = split_at_rightmost_and(emit, &inner) {
// Hoist *this* alias name. Caller wraps BetweenExpr
// with each hoisted item in order (innermost first),
// which matches cpp's `Alias(BetweenExpr(...),
// outer_name)` shape.
- let name = node
- .get("alias")
- .and_then(Value::as_str)
- .unwrap_or("")
- .to_string();
+ let name = emit
+ .get_field(node, "alias")
+ .and_then(|v| emit.as_str(&v).map(|s| s.into_owned()))
+ .unwrap_or_default();
hoisted.push(BetweenHoist::Alias(name));
return Some((left_in, right_in, hoisted));
}
@@ -5318,12 +5306,12 @@ fn split_at_rightmost_and(node: &Value) -> Option<BetweenSplit> {
// accumulated wrappers so it ends up OUTERMOST around the
// alias-wrapped BetweenExpr the caller will build.
if node_name == Some("IsDistinctFrom") {
- if let Some(inner) = node.get("left") {
- if let Some((left_in, right_in, mut hoisted)) = split_at_rightmost_and(inner) {
- let right = node.get("right").cloned().unwrap_or(Value::Null);
- let negated = node
- .get("negated")
- .and_then(Value::as_bool)
+ if let Some(inner) = emit.get_field(node, "left") {
+ if let Some((left_in, right_in, mut hoisted)) = split_at_rightmost_and(emit, &inner) {
+ let right = emit.get_field(node, "right").unwrap_or_else(|| emit.null());
+ let negated = emit
+ .get_field(node, "negated")
+ .and_then(|v| emit.as_bool(&v))
.unwrap_or(false);
hoisted.push(BetweenHoist::IsDistinctFrom { right, negated });
return Some((left_in, right_in, hoisted));
@@ -5331,15 +5319,19 @@ fn split_at_rightmost_and(node: &Value) -> Option<BetweenSplit> {
}
}
if node_name == Some("CompareOperation")
- && node
- .get("is_null_comparison_style")
- .and_then(Value::as_bool)
+ && emit
+ .get_field(node, "is_null_comparison_style")
+ .and_then(|v| emit.as_bool(&v))
== Some(true)
{
- if let Some(inner) = node.get("left") {
- if let Some((left_in, right_in, mut hoisted)) = split_at_rightmost_and(inner) {
+ if let Some(inner) = emit.get_field(node, "left") {
+ if let Some((left_in, right_in, mut hoisted)) = split_at_rightmost_and(emit, &inner) {
// `op` is "==" for IS NULL, "!=" for IS NOT NULL.
- let negated = node.get("op").and_then(Value::as_str) == Some("!=");
+ let negated = emit
+ .get_field(node, "op")
+ .and_then(|v| emit.as_str(&v).map(|s| s.into_owned()))
+ .as_deref()
+ == Some("!=");
hoisted.push(BetweenHoist::IsNull { negated });
return Some((left_in, right_in, hoisted));
}
@@ -5350,12 +5342,14 @@ fn split_at_rightmost_and(node: &Value) -> Option<BetweenSplit> {
// Descend through `array`; on success, hoist the access OUTSIDE
// the alias so it wraps the BetweenExpr the caller builds.
if node_name == Some("ArrayAccess") {
- if let Some(inner) = node.get("array") {
- if let Some((left_in, right_in, mut hoisted)) = split_at_rightmost_and(inner) {
- let property = node.get("property").cloned().unwrap_or(Value::Null);
- let nullish = node
- .get("nullish")
- .and_then(Value::as_bool)
+ if let Some(inner) = emit.get_field(node, "array") {
+ if let Some((left_in, right_in, mut hoisted)) = split_at_rightmost_and(emit, &inner) {
+ let property = emit
+ .get_field(node, "property")
+ .unwrap_or_else(|| emit.null());
+ let nullish = emit
+ .get_field(node, "nullish")
+ .and_then(|v| emit.as_bool(&v))
.unwrap_or(false);
hoisted.push(BetweenHoist::ArrayAccess { property, nullish });
return Some((left_in, right_in, hoisted));
@@ -5370,12 +5364,11 @@ fn split_at_rightmost_and(node: &Value) -> Option<BetweenSplit> {
// on `Alias(And(1, (2)), 'a')`, burying the BETWEEN-separator
// AND inside the call's `.expr`.
if node_name == Some("ExprCall") {
- if let Some(inner) = node.get("expr") {
- if let Some((left_in, right_in, mut hoisted)) = split_at_rightmost_and(inner) {
- let args = node
- .get("args")
- .and_then(Value::as_array)
- .cloned()
+ if let Some(inner) = emit.get_field(node, "expr") {
+ if let Some((left_in, right_in, mut hoisted)) = split_at_rightmost_and(emit, &inner) {
+ let args = emit
+ .get_field(node, "args")
+ .and_then(|v| emit.as_list(&v))
.unwrap_or_default();
hoisted.push(BetweenHoist::ExprCall { args });
return Some((left_in, right_in, hoisted));
@@ -5385,9 +5378,12 @@ fn split_at_rightmost_and(node: &Value) -> Option<BetweenSplit> {
// `TypeCast(<expr>, type_name)` — postfix `:: <type>` at
// BP_POSTFIX=130. Same hoisting pattern as ExprCall.
if node_name == Some("TypeCast") {
- if let Some(inner) = node.get("expr") {
- if let Some((left_in, right_in, mut hoisted)) = split_at_rightmost_and(inner) {
- let type_name = node.get("type_name").cloned().unwrap_or(Value::Null);
+ if let Some(inner) = emit.get_field(node, "expr") {
+ if let Some((left_in, right_in, mut hoisted)) = split_at_rightmost_and(emit, &inner) {
+ let type_name = emit
+ .get_field(node, "type_name")
+ .and_then(|v| emit.as_str(&v).map(|s| s.into_owned()))
+ .unwrap_or_default();
hoisted.push(BetweenHoist::TypeCast { type_name });
return Some((left_in, right_in, hoisted));
}
@@ -5398,12 +5394,15 @@ fn split_at_rightmost_and(node: &Value) -> Option<BetweenSplit> {
// ArrayAccess but on a different node type with a different
// field name (`tuple` vs `array`, `index` vs `property`).
if node_name == Some("TupleAccess") {
- if let Some(inner) = node.get("tuple") {
- if let Some((left_in, right_in, mut hoisted)) = split_at_rightmost_and(inner) {
- let index = node.get("index").and_then(Value::as_i64).unwrap_or(0);
- let nullish = node
- .get("nullish")
- .and_then(Value::as_bool)
+ if let Some(inner) = emit.get_field(node, "tuple") {
+ if let Some((left_in, right_in, mut hoisted)) = split_at_rightmost_and(emit, &inner) {
+ let index = emit
+ .get_field(node, "index")
+ .and_then(|v| emit.as_i64(&v))
+ .unwrap_or(0);
+ let nullish = emit
+ .get_field(node, "nullish")
+ .and_then(|v| emit.as_bool(&v))
.unwrap_or(false);
hoisted.push(BetweenHoist::TupleAccess { index, nullish });
return Some((left_in, right_in, hoisted));
@@ -5438,21 +5437,25 @@ fn split_at_rightmost_and(node: &Value) -> Option<BetweenSplit> {
// (no AND), so the `low` peel above fails. Fall through to
// `expr`: split And(d,e), hoist (f, g, neg=true).
if node_name == Some("BetweenExpr") {
- if let (Some(inner_low), Some(inner_high)) = (node.get("low"), node.get("high")) {
- if let Some((new_low, new_high, hoisted)) = split_at_rightmost_and(inner_low) {
- let mut new_inner = node.as_object()?.clone();
- new_inner.insert("low".into(), new_low);
- new_inner.insert("high".into(), new_high);
- return Some((Value::Object(new_inner), inner_high.clone(), hoisted));
+ if let (Some(inner_low), Some(inner_high)) =
+ (emit.get_field(node, "low"), emit.get_field(node, "high"))
+ {
+ if let Some((new_low, new_high, hoisted)) = split_at_rightmost_and(emit, &inner_low) {
+ let mut new_inner = node.clone();
+ emit.set_field(&mut new_inner, "low", new_low);
+ emit.set_field(&mut new_inner, "high", new_high);
+ return Some((new_inner, inner_high, hoisted));
}
}
- if let Some(inner_expr) = node.get("expr") {
- if let Some((left_in, right_in, mut hoisted)) = split_at_rightmost_and(inner_expr) {
- let low = node.get("low").cloned().unwrap_or(Value::Null);
- let high = node.get("high").cloned().unwrap_or(Value::Null);
- let negated = node
- .get("negated")
- .and_then(Value::as_bool)
+ if let Some(inner_expr) = emit.get_field(node, "expr") {
+ if let Some((left_in, right_in, mut hoisted)) =
+ split_at_rightmost_and(emit, &inner_expr)
+ {
+ let low = emit.get_field(node, "low").unwrap_or_else(|| emit.null());
+ let high = emit.get_field(node, "high").unwrap_or_else(|| emit.null());
+ let negated = emit
+ .get_field(node, "negated")
+ .and_then(|v| emit.as_bool(&v))
.unwrap_or(false);
hoisted.push(BetweenHoist::Between { low, high, negated });
return Some((left_in, right_in, hoisted));
@@ -5468,14 +5471,11 @@ fn split_at_rightmost_and(node: &Value) -> Option<BetweenSplit> {
/// `offset`) that resolved to a bare identifier and should NOT extend
/// the column list — cpp backs off the comma and dispatches them as
/// the next clause introducer.
-pub(crate) fn is_bare_field(v: &Value) -> bool {
- let Some(obj) = v.as_object() else {
- return false;
- };
- if obj.get("node").and_then(Value::as_str) != Some("Field") {
+pub(crate) fn is_bare_field<E: Emitter>(emit: &E, v: &E::Value) -> bool {
+ if emit.node_kind(v).as_deref() != Some("Field") {
return false;
}
- let Some(chain) = obj.get("chain").and_then(Value::as_array) else {
+ let Some(chain) = emit.get_field(v, "chain").and_then(|c| emit.as_list(&c)) else {
return false;
};
chain.len() == 1
@@ -5489,15 +5489,18 @@ pub(crate) fn is_bare_field(v: &Value) -> bool {
/// bare-paren form. The COLUMNS-prefixed `COLUMNS(* REPLACE(...))`
/// variant takes a different parse path (it doesn't go through
/// `parse_paren_or_tuple`), so this check is safe.
-fn is_paren_form_columns_replace(v: &Value) -> bool {
- let Some(obj) = v.as_object() else {
- return false;
- };
- if obj.get("node").and_then(Value::as_str) != Some("ColumnsExpr") {
+fn is_paren_form_columns_replace<E: Emitter>(emit: &E, v: &E::Value) -> bool {
+ if emit.node_kind(v).as_deref() != Some("ColumnsExpr") {
return false;
}
- if obj.get("all_columns").and_then(Value::as_bool) != Some(true) {
+ if emit
+ .get_field(v, "all_columns")
+ .and_then(|v| emit.as_bool(&v))
+ != Some(true)
+ {
return false;
}
- obj.get("replace").map(|v| !v.is_null()).unwrap_or(false)
+ emit.get_field(v, "replace")
+ .map(|v| !emit.is_null(&v))
+ .unwrap_or(false)
}
diff --git a/rust/hogql/parser/src/parse/hogqlx.rs b/rust/hogql/parser/src/parse/hogqlx.rs
index dff444a0e33e..7e67020ccc8f 100644
--- a/rust/hogql/parser/src/parse/hogqlx.rs
+++ b/rust/hogql/parser/src/parse/hogqlx.rs
@@ -24,14 +24,12 @@
//! Parser API is identical across the two backends so no rewrites are
//! needed here.
-use serde_json::{json, Value};
-
use super::{identifier_text, unquote_single_string, Parser};
-use crate::emit;
+use crate::emit::Emitter;
use crate::error::ParseError;
use crate::lex::TokenKind;
-impl<'a> Parser<'a> {
+impl<'a, E: Emitter + Clone> Parser<'a, E> {
/// True when peek/peek_next look like the start of a HogQLX tag —
/// `<` followed by an identifier-or-keyword-acting-as-identifier.
/// `<` followed by anything else (most commonly an expression for
@@ -63,30 +61,23 @@ impl<'a> Parser<'a> {
/// byte-walks the body directly and re-seeks the lexer via
/// `consume_hogqlx_text`, so peek1's transient invalid state is
/// recoverable.
- pub(crate) fn parse_hogqlx_tag_element(&mut self) -> Result<Value, ParseError> {
+ pub(crate) fn parse_hogqlx_tag_element(&mut self) -> Result<E::Value, ParseError> {
self.hogqlx_text_lookahead_depth += 1;
let result = self.parse_hogqlx_tag_element_inner();
self.hogqlx_text_lookahead_depth -= 1;
result
}
- fn parse_hogqlx_tag_element_inner(&mut self) -> Result<Value, ParseError> {
+ fn parse_hogqlx_tag_element_inner(&mut self) -> Result<E::Value, ParseError> {
let tag_start = self.peek0.start;
self.expect(TokenKind::Lt, "<")?;
let kind = self.parse_hogqlx_identifier("tag name")?;
- let mut attributes: Vec<Value> = Vec::new();
+ let mut attributes: Vec<E::Value> = Vec::new();
loop {
match self.peek() {
TokenKind::SlashGt => {
self.bump()?;
- return Ok(self.wrap_pos(
- json!({
- "node": "HogQLXTag",
- "kind": kind,
- "attributes": attributes,
- }),
- tag_start,
- ));
+ return Ok(self.wrap_pos(self.emit.hogqlx_tag(&kind, attributes), tag_start));
}
TokenKind::Gt => {
self.bump()?;
@@ -102,28 +93,20 @@ impl<'a> Parser<'a> {
self.expect(TokenKind::Gt, ">")?;
if !children.is_empty() {
if attributes.iter().any(|a| {
- a.as_object()
- .and_then(|o| o.get("name").and_then(Value::as_str))
+ self.emit
+ .get_field(a, "name")
+ .and_then(|v| self.emit.as_str(&v).map(|s| s.into_owned()))
+ .as_deref()
== Some("children")
}) {
return Err(self.err(
"Can't have a HogQLX tag with both children and a 'children' attribute",
));
}
- attributes.push(json!({
- "node": "HogQLXAttribute",
- "name": "children",
- "value": children,
- }));
+ let kids = self.emit.list_value(children);
+ attributes.push(self.emit.hogqlx_attribute("children", kids));
}
- return Ok(self.wrap_pos(
- json!({
- "node": "HogQLXTag",
- "kind": kind,
- "attributes": attributes,
- }),
- tag_start,
- ));
+ return Ok(self.wrap_pos(self.emit.hogqlx_tag(&kind, attributes), tag_start));
}
TokenKind::Ident | TokenKind::QuotedIdent | TokenKind::Keyword(_) => {
attributes.push(self.parse_hogqlx_attribute()?);
@@ -145,21 +128,20 @@ impl<'a> Parser<'a> {
/// - `name = 'string'` → HogQLXAttribute(name, Constant(string))
/// - `name = { expr }` → HogQLXAttribute(name, expr)
/// - `name` → HogQLXAttribute(name, Constant(true))
- fn parse_hogqlx_attribute(&mut self) -> Result<Value, ParseError> {
+ fn parse_hogqlx_attribute(&mut self) -> Result<E::Value, ParseError> {
let name = self.parse_hogqlx_identifier("attribute name")?;
// No `=` → bare attribute, value is Constant(true).
if self.peek() != TokenKind::EqDouble {
- return Ok(json!({
- "node": "HogQLXAttribute",
- "name": name,
- "value": emit::constant(Value::Bool(true)),
- }));
+ return Ok(self
+ .emit
+ .hogqlx_attribute(&name, self.emit.constant(self.emit.bool(true))));
}
self.bump()?; // `=`
let value = match self.peek() {
TokenKind::String => {
let t = self.bump()?;
- emit::constant(Value::String(unquote_single_string(self.text(t))))
+ self.emit
+ .constant(self.emit.string(&unquote_single_string(self.text(t))))
}
TokenKind::LBrace => {
self.bump()?;
@@ -174,11 +156,7 @@ impl<'a> Parser<'a> {
)));
}
};
- Ok(json!({
- "node": "HogQLXAttribute",
- "name": name,
- "value": value,
- }))
+ Ok(self.emit.hogqlx_attribute(&name, value))
}
/// Read tag-body children until the closing `</`. Children are:
@@ -190,8 +168,8 @@ impl<'a> Parser<'a> {
/// Text scanning uses the source's byte stream directly because the
/// lexer's whitespace skip would otherwise destroy significant
/// inter-token spacing (e.g. `Hello World`).
- fn parse_hogqlx_children(&mut self) -> Result<Vec<Value>, ParseError> {
- let mut children: Vec<Value> = Vec::new();
+ fn parse_hogqlx_children(&mut self) -> Result<Vec<E::Value>, ParseError> {
+ let mut children: Vec<E::Value> = Vec::new();
loop {
let text = self.consume_hogqlx_text()?;
// cpp's `VISIT(HogqlxTagElementNested)` drops child text
@@ -203,7 +181,7 @@ impl<'a> Parser<'a> {
&& text.bytes().all(|b| b.is_ascii_whitespace())
&& text.bytes().any(|b| b == b'\n' || b == b'\r');
if !text.is_empty() && !drop_for_newline_ws {
- children.push(emit::constant(Value::String(text)));
+ children.push(self.emit.constant(self.emit.string(&text)));
}
match self.peek() {
TokenKind::LtSlash => return Ok(children),
diff --git a/rust/hogql/parser/src/parse/join.rs b/rust/hogql/parser/src/parse/join.rs
index 59c46f574f9a..33beff1aa9af 100644
--- a/rust/hogql/parser/src/parse/join.rs
+++ b/rust/hogql/parser/src/parse/join.rs
@@ -6,17 +6,15 @@
//! qualifier. ARRAY JOIN is *not* here — it belongs to the SELECT
//! statement (see `parse_select_stmt_body` in `select.rs`).
-use serde_json::{json, Value};
-
use super::{
chain_join, check_alias_not_reserved, identifier_text, kw_valid_as_identifier, Parser,
};
-use crate::emit;
+use crate::emit::Emitter;
use crate::error::ParseError;
use crate::lex::{Kw, Lexer, TokenKind};
-impl<'a> Parser<'a> {
- pub(crate) fn parse_join_expr(&mut self) -> Result<Value, ParseError> {
+impl<'a, E: Emitter + Clone> Parser<'a, E> {
+ pub(crate) fn parse_join_expr(&mut self) -> Result<E::Value, ParseError> {
// Left-recursive in the grammar; iterate, chaining each new
// right-side table into the previous JoinExpr's `next_join` field.
let chain_start = self.peek0.start;
@@ -26,7 +24,7 @@ impl<'a> Parser<'a> {
// loop below must NOT attach constraints into pre-existing joins —
// those slots belong to the inner scope. Scope-local additions made
// by THIS loop sit at depth > lead_depth.
- let lead_depth = chain_depth(&left);
+ let lead_depth = chain_depth(&self.emit, &left);
let mut joined_any = false;
loop {
// ARRAY JOIN belongs to the outer SELECT statement, not the
@@ -61,7 +59,7 @@ impl<'a> Parser<'a> {
}
self.bump()?;
let right = self.parse_table_atom_with_pivot()?;
- left = chain_join(left, right, "CROSS JOIN", None);
+ left = chain_join(&self.emit, left, right, "CROSS JOIN", None);
joined_any = true;
continue;
}
@@ -72,7 +70,7 @@ impl<'a> Parser<'a> {
self.bump()?;
self.bump()?;
let right = self.parse_table_atom_with_pivot()?;
- left = chain_join(left, right, "CROSS JOIN", None);
+ left = chain_join(&self.emit, left, right, "CROSS JOIN", None);
joined_any = true;
continue;
}
@@ -84,7 +82,7 @@ impl<'a> Parser<'a> {
self.bump()?;
let right = self.parse_table_atom_with_pivot()?;
let constraint = self.parse_join_constraint_opt()?;
- left = chain_join(left, right, "POSITIONAL JOIN", constraint);
+ left = chain_join(&self.emit, left, right, "POSITIONAL JOIN", constraint);
joined_any = true;
continue;
}
@@ -113,7 +111,7 @@ impl<'a> Parser<'a> {
} else {
format!("{op_text} JOIN")
};
- left = chain_join(left, right, &join_type, constraint);
+ left = chain_join(&self.emit, left, right, &join_type, constraint);
joined_any = true;
}
@@ -140,12 +138,15 @@ impl<'a> Parser<'a> {
let Some(constraint) = self.parse_join_constraint_opt()? else {
break;
};
- if !attach_constraint_to_outermost_unconstrained_join(
- &mut left,
+ let (updated, attached) = attach_constraint_to_outermost_unconstrained_join(
+ &self.emit,
+ left,
constraint,
lead_depth + 1,
1,
- ) {
+ );
+ left = updated;
+ if !attached {
let kw = if matches!(kw_kind, TokenKind::Keyword(Kw::On)) {
"ON"
} else {
@@ -175,7 +176,7 @@ impl<'a> Parser<'a> {
/// instead follows a join *constraint* (`a JOIN b ON x PIVOT (…)`)
/// applies to the whole chain; that case is left for the caller's
/// loop, which calls `wrap_pivot_chain` with `joined_any`.
- fn parse_table_atom_with_pivot(&mut self) -> Result<Value, ParseError> {
+ fn parse_table_atom_with_pivot(&mut self) -> Result<E::Value, ParseError> {
let atom_start = self.peek0.start;
let atom = self.parse_table_atom()?;
if matches!(
@@ -196,10 +197,10 @@ impl<'a> Parser<'a> {
/// following JOIN or further PIVOT is picked up too.
fn wrap_pivot_chain(
&mut self,
- left: Value,
+ left: E::Value,
joined_any: bool,
table_start: usize,
- ) -> Result<Value, ParseError> {
+ ) -> Result<E::Value, ParseError> {
// For the single-atom case (no JOIN happened) the chain is a
// JoinExpr that only wraps a bare Field — unwrap to match cpp's
// shape (PivotExpr's `table` is the bare Field). When the
@@ -209,14 +210,23 @@ impl<'a> Parser<'a> {
// exclude from the decoration probe.
let pivot_input = if joined_any {
left
- } else if let Some(obj) = left.as_object() {
- let has_decorations = obj
- .keys()
- .any(|k| !matches!(k.as_str(), "node" | "table" | "start" | "end"));
- if has_decorations {
+ } else if self.emit.node_kind(&left).is_some() {
+ // For abstract values we can't enumerate fields, so we use
+ // a probe-based check: if the value has only the "expected"
+ // shape (node + table + positions), peel out `table`. We
+ // approximate by checking `alias` / `final` / `sample` /
+ // `column_aliases` absence — the only other top-level
+ // JoinExpr decorations.
+ let decorated = self.emit.has_field(&left, "alias")
+ || self.emit.has_field(&left, "table_final")
+ || self.emit.has_field(&left, "sample")
+ || self.emit.has_field(&left, "column_aliases")
+ || self.emit.has_field(&left, "table_args")
+ || self.emit.has_field(&left, "next_join");
+ if decorated {
left
} else {
- obj.get("table").cloned().unwrap_or(left)
+ self.emit.get_field(&left, "table").unwrap_or(left)
}
} else {
left
@@ -224,34 +234,21 @@ impl<'a> Parser<'a> {
let wrapped = self.try_consume_pivot_unpivot(pivot_input, table_start)?;
// Wrap the PivotExpr/UnpivotExpr in an outer JoinExpr (the C++
// visitor's JoinExprPivot does the same).
- let mut outer = serde_json::Map::new();
- outer.insert("node".into(), Value::String("JoinExpr".into()));
- outer.insert("table".into(), wrapped);
// Grammar order: `TableExprAlias` (alias + columnAliases) binds
// inside `tableExpr`, then `JoinExprTable` adds `FINAL?
// sampleClause?`.
let (alias, column_aliases) = self.consume_table_alias_chain()?;
- if let Some(a) = alias {
- outer.insert("alias".into(), Value::String(a));
- }
- if let Some(ca) = column_aliases {
- outer.insert(
- "column_aliases".into(),
- Value::Array(ca.into_iter().map(Value::String).collect()),
- );
- }
- if self.eat_kw(Kw::Final)? {
- outer.insert("table_final".into(), Value::Bool(true));
- }
- if let Some(s) = self.try_consume_sample()? {
- outer.insert("sample".into(), s);
- }
+ let table_final = self.eat_kw(Kw::Final)?;
+ let sample = self.try_consume_sample()?;
+ let outer = self
+ .emit
+ .join_expr(wrapped, alias, None, column_aliases, table_final, sample);
// Wrap before returning so the JoinExpr carries positions even
// when a later wrap_pivot_chain stacks it as the inner table of
// a fresh outer PivotExpr / UnpivotExpr. The outer parse_join_expr
// wrap_pos at line ~160 is idempotent and only reaches the
// *outermost* node — the inner one needs its own wrap here.
- Ok(self.wrap_pos(Value::Object(outer), table_start))
+ Ok(self.wrap_pos(outer, table_start))
}
fn try_consume_join_op(&mut self) -> Result<Option<String>, ParseError> {
@@ -457,7 +454,7 @@ impl<'a> Parser<'a> {
Ok(Some(tokens.join(" ")))
}
- fn parse_join_constraint_opt(&mut self) -> Result<Option<Value>, ParseError> {
+ fn parse_join_constraint_opt(&mut self) -> Result<Option<E::Value>, ParseError> {
let cons_start = self.peek0.start;
if self.eat_kw(Kw::On)? {
let expr = self.parse_expr_bp(0)?;
@@ -487,10 +484,9 @@ impl<'a> Parser<'a> {
end,
));
}
- return Ok(Some(self.wrap_pos(
- json!({"node": "JoinConstraint", "expr": expr, "constraint_type": "ON"}),
- cons_start,
- )));
+ return Ok(Some(
+ self.wrap_pos(self.emit.join_constraint(expr, "ON"), cons_start),
+ ));
}
if self.eat_kw(Kw::Using)? {
// The grammar `joinConstraintClause` admits two USING shapes:
@@ -511,12 +507,11 @@ impl<'a> Parser<'a> {
let expr = if exprs.len() == 1 {
exprs.into_iter().next().unwrap()
} else {
- emit::tuple_(exprs)
+ self.emit.tuple_(exprs)
};
- return Ok(Some(self.wrap_pos(
- json!({"node": "JoinConstraint", "expr": expr, "constraint_type": "USING"}),
- cons_start,
- )));
+ return Ok(Some(
+ self.wrap_pos(self.emit.join_constraint(expr, "USING"), cons_start),
+ ));
}
Ok(None)
}
@@ -540,9 +535,9 @@ impl<'a> Parser<'a> {
)
}
- fn parse_table_atom(&mut self) -> Result<Value, ParseError> {
+ fn parse_table_atom(&mut self) -> Result<E::Value, ParseError> {
let atom_start = self.peek0.start;
- let mut table_expr = self.parse_table_expr()?;
+ let table_expr = self.parse_table_expr()?;
// Snapshot the end of `tableExpr` before alias / FINAL / SAMPLE
// are consumed. For the table-function case (cpp's
// `TableFunctionExpr`), cpp's emitted JoinExpr's ctx covers
@@ -563,16 +558,15 @@ impl<'a> Parser<'a> {
// closing paren. cpp rejects `(t) AS x`, `(t JOIN b ON x) AS y`,
// `(t) FINAL`, etc. Return the JoinExpr unchanged and let the
// caller surface any post-paren tokens as trailing-input errors.
- let already_join_expr = table_expr.get("node").and_then(Value::as_str) == Some("JoinExpr");
+ let already_join_expr = self.emit.node_kind(&table_expr).as_deref() == Some("JoinExpr");
if already_join_expr {
return Ok(table_expr);
}
// parse_table_expr signals table-function args via a sentinel key
// on the returned Field — extract them into `table_args` so the
// JoinExpr wrapper gets the C++-shape Field + table_args split.
- let table_args = table_expr
- .as_object_mut()
- .and_then(|m| m.remove("__rust_table_args"));
+ let mut table_expr = table_expr;
+ let table_args = self.emit.remove_field(&mut table_expr, "__rust_table_args");
let is_table_function = table_args.is_some();
// Grammar order: `TableExprAlias` is `tableExpr (alias | AS
// identifier) columnAliases?` — the alias and column-aliases
@@ -599,27 +593,14 @@ impl<'a> Parser<'a> {
// each individual atom — `FROM a JOIN b PIVOT (...)` wraps the
// entire `a JOIN b`, not just `b`. parse_table_atom only handles
// the immediate table + its alias / sample / final decoration.
- let mut obj = serde_json::Map::new();
- obj.insert("node".into(), Value::String("JoinExpr".into()));
- obj.insert("table".into(), table_expr);
- if let Some(ta) = table_args {
- obj.insert("table_args".into(), ta);
- }
- if let Some(a) = alias {
- obj.insert("alias".into(), Value::String(a));
- }
- if final_ {
- obj.insert("table_final".into(), Value::Bool(true));
- }
- if let Some(s) = sample {
- obj.insert("sample".into(), s);
- }
- if let Some(ca) = column_aliases {
- obj.insert(
- "column_aliases".into(),
- Value::Array(ca.into_iter().map(Value::String).collect()),
- );
- }
+ let obj = self.emit.join_expr(
+ table_expr,
+ alias,
+ table_args,
+ column_aliases,
+ final_,
+ sample,
+ );
// Three position-end regimes match cpp's three wrapping points:
// - `TableFunctionExpr` (cpp lines 2797-2817): ctx covers
// `name(args)` only; alias / FINAL / SAMPLE never widen it.
@@ -637,7 +618,7 @@ impl<'a> Parser<'a> {
} else {
self.last_consumed_end
};
- Ok(self.wrap_pos_to(Value::Object(obj), atom_start, wrap_end))
+ Ok(self.wrap_pos_to(obj, atom_start, wrap_end))
}
/// Consume a chain of table aliases. The grammar's `TableExprAlias`
@@ -754,7 +735,7 @@ impl<'a> Parser<'a> {
}
}
- fn parse_table_expr(&mut self) -> Result<Value, ParseError> {
+ fn parse_table_expr(&mut self) -> Result<E::Value, ParseError> {
// `(selectSet)`, table identifier (with optional function-arg
// syntax), `{placeholder}`, `VALUES (...)`, `(joinExpr)`
// (per the grammar's `JoinExprParens` rule — e.g. `FROM (t FINAL)`),
@@ -839,23 +820,29 @@ impl<'a> Parser<'a> {
// `addPositionInfo` — only the wrapping JoinExpr carries the
// span. Emit position-less here too so the deserialised
// Field's `start` / `end` stay `None`, matching cpp.
- return Ok(emit::no_pos(json!({
- "node": "Field",
- "chain": [name],
- "__rust_table_args": args,
- })));
+ let chain = vec![self.emit.string(&name)];
+ let mut field = self.emit.field(chain);
+ self.emit
+ .set_field(&mut field, "__rust_table_args", self.emit.list_value(args));
+ return Ok(self.emit.no_pos(field));
}
// Field chain.
- let mut chain: Vec<Value> = vec![Value::String(name)];
+ let mut chain: Vec<E::Value> = vec![self.emit.string(&name)];
while self.peek() == TokenKind::Dot {
self.bump()?;
let part = self.bump()?;
match part.kind {
TokenKind::Ident | TokenKind::QuotedIdent => {
- chain.push(Value::String(identifier_text(self.text(part), part.kind)));
+ chain.push(
+ self.emit
+ .string(&identifier_text(self.text(part), part.kind)),
+ );
}
TokenKind::Keyword(kw) if kw_valid_as_identifier(kw) => {
- chain.push(Value::String(identifier_text(self.text(part), part.kind)));
+ chain.push(
+ self.emit
+ .string(&identifier_text(self.text(part), part.kind)),
+ );
}
_ => {
return Err(self.err(format!(
@@ -865,14 +852,14 @@ impl<'a> Parser<'a> {
}
}
}
- Ok(self.wrap_pos(emit::field(chain), tab_start))
+ Ok(self.wrap_pos(self.emit.field(chain), tab_start))
}
/// `parse_table_expr` arm: TableExprSubquery, `LPAREN selectSetStmt RPAREN`.
/// The inner is anything `selectSetStmt` admits — SELECT statements,
/// WITH-CTE selects, paren-wrapped set-stmts, or a bare placeholder
/// `{x}` (placeholders are first-class `selectStmtWithParens` arms).
- fn parse_table_expr_subquery_arm(&mut self) -> Result<Value, ParseError> {
+ fn parse_table_expr_subquery_arm(&mut self) -> Result<E::Value, ParseError> {
self.expect(TokenKind::LParen, "(")?;
let inner = self.parse_select_set_stmt()?;
self.expect(TokenKind::RParen, ")")?;
@@ -883,7 +870,7 @@ impl<'a> Parser<'a> {
/// `VALUES` is the first inner token and uniquely identifies this arm,
/// but we still parse it inside the try_alt so a malformed valuesClause
/// (e.g. `(VALUES, x)`) rolls back cleanly to the joinExpr fallback.
- fn parse_table_expr_values_arm(&mut self) -> Result<Value, ParseError> {
+ fn parse_table_expr_values_arm(&mut self) -> Result<E::Value, ParseError> {
self.expect(TokenKind::LParen, "(")?;
if self.peek() != TokenKind::Keyword(Kw::Values) {
return Err(self.err("not a VALUES clause"));
@@ -898,7 +885,7 @@ impl<'a> Parser<'a> {
/// sample-decorated tables, JOIN chains. cpp's `JoinExprParens` doesn't
/// allow trailing FINAL / SAMPLE at the outer level; `parse_table_atom`
/// distinguishes this case via the returned node's `"JoinExpr"` shape.
- fn parse_join_expr_parens_arm(&mut self) -> Result<Value, ParseError> {
+ fn parse_join_expr_parens_arm(&mut self) -> Result<E::Value, ParseError> {
self.expect(TokenKind::LParen, "(")?;
let inner = self.parse_join_expr()?;
self.expect(TokenKind::RParen, ")")?;
@@ -908,25 +895,25 @@ impl<'a> Parser<'a> {
/// `VALUES (...), (...)` — a literal-row query usable wherever a table
/// reference is expected. The caller has already consumed the leading
/// `(` if any; we consume the `VALUES` keyword and emit a ValuesQuery.
- fn parse_values_query(&mut self) -> Result<Value, ParseError> {
+ fn parse_values_query(&mut self) -> Result<E::Value, ParseError> {
self.expect_kw(Kw::Values, "VALUES")?;
- let mut rows: Vec<Value> = Vec::new();
+ let mut rows: Vec<E::Value> = Vec::new();
loop {
self.expect(TokenKind::LParen, "(")?;
let row = self.parse_expr_list_until_paren()?;
self.expect(TokenKind::RParen, ")")?;
- rows.push(Value::Array(row));
+ rows.push(self.emit.list_value(row));
if !self.eat(TokenKind::Comma)? {
break;
}
}
- Ok(json!({"node": "ValuesQuery", "rows": rows}))
+ Ok(self.emit.values_query(rows))
}
/// `SAMPLE ratioExpr PERCENT? (OFFSET ratioExpr)? (LPAREN ident RPAREN)?`
/// — attached to a table reference inside a JoinExpr. Returns None
/// when no SAMPLE clause is present.
- pub(crate) fn try_consume_sample(&mut self) -> Result<Option<Value>, ParseError> {
+ pub(crate) fn try_consume_sample(&mut self) -> Result<Option<E::Value>, ParseError> {
if !matches!(self.peek(), TokenKind::Keyword(Kw::Sample)) {
return Ok(None);
}
@@ -968,13 +955,8 @@ impl<'a> Parser<'a> {
let _ = self.bump()?;
self.expect(TokenKind::RParen, ")")?;
}
- let mut obj = serde_json::Map::new();
- obj.insert("node".into(), Value::String("SampleExpr".into()));
- obj.insert("sample_value".into(), sample_value);
- if let Some(o) = offset_value {
- obj.insert("offset_value".into(), o);
- }
- Ok(Some(self.wrap_pos(Value::Object(obj), sample_start)))
+ let sample = self.emit.sample_expr(sample_value, offset_value);
+ Ok(Some(self.wrap_pos(sample, sample_start)))
}
/// After a SAMPLE clause has consumed its value and (optional)
@@ -1030,7 +1012,7 @@ impl<'a> Parser<'a> {
/// ratio context never runs the postfix loop — so a bare `5.`
/// would leave the `.` stranded. Detect Number-then-bare-Dot and
/// upgrade to a float Constant in-place.
- fn consume_ratio_value(&mut self) -> Result<Value, ParseError> {
+ fn consume_ratio_value(&mut self) -> Result<E::Value, ParseError> {
let val_start = self.peek0.start;
// cpp grammar: `ratioExpr: placeholder | numberLiteral
// (SLASH numberLiteral)?`. The numerator/denominator side is
@@ -1064,9 +1046,7 @@ impl<'a> Parser<'a> {
let mut val = self.parse_prefix()?;
// Reject non-numeric prefixes (a placeholder masquerading as
// a `{x}` ratio side, a sign followed by a non-number, etc.).
- let is_numeric_constant = val
- .as_object()
- .is_some_and(|o| o.get("node").and_then(Value::as_str) == Some("Constant"));
+ let is_numeric_constant = self.emit.node_kind(&val).as_deref() == Some("Constant");
if !is_numeric_constant {
return Err(self.err("SAMPLE ratio value must be a number literal"));
}
@@ -1079,18 +1059,21 @@ impl<'a> Parser<'a> {
)
{
self.bump()?;
- if let Some(obj) = val.as_object_mut() {
- if obj.get("node").and_then(Value::as_str) == Some("Constant") {
- if let Some(n) = obj.get("value").and_then(Value::as_i64) {
- obj.insert("value".into(), serde_json::json!(n as f64));
- }
+ if self.emit.node_kind(&val).as_deref() == Some("Constant") {
+ if let Some(n) = self
+ .emit
+ .get_field(&val, "value")
+ .and_then(|v| self.emit.as_i64(&v))
+ {
+ let fv = self.emit.float(n as f64);
+ self.emit.set_field(&mut val, "value", fv);
}
}
}
Ok(self.wrap_pos(val, val_start))
}
- fn parse_ratio_expr(&mut self) -> Result<Value, ParseError> {
+ fn parse_ratio_expr(&mut self) -> Result<E::Value, ParseError> {
// cpp grammar: `ratioExpr: placeholder | numberLiteral
// (SLASH numberLiteral)?`. We mirror it narrowly so the
// trailing `(identifier)` sample qualifier — and an unrelated
@@ -1109,13 +1092,8 @@ impl<'a> Parser<'a> {
} else {
None
};
- let mut obj = serde_json::Map::new();
- obj.insert("node".into(), Value::String("RatioExpr".into()));
- obj.insert("left".into(), left);
- if let Some(r) = right {
- obj.insert("right".into(), r);
- }
- Ok(self.wrap_pos(Value::Object(obj), ratio_start))
+ let ratio = self.emit.ratio_expr(left, right);
+ Ok(self.wrap_pos(ratio, ratio_start))
}
/// `<table> PIVOT (aggregates pivotColumnList (GROUP BY exprList)?)`
@@ -1131,9 +1109,9 @@ impl<'a> Parser<'a> {
/// — span includes that leading table.
fn try_consume_pivot_unpivot(
&mut self,
- mut table: Value,
+ mut table: E::Value,
table_start: usize,
- ) -> Result<Value, ParseError> {
+ ) -> Result<E::Value, ParseError> {
loop {
if matches!(self.peek(), TokenKind::Keyword(Kw::Pivot)) {
let pivot_start = table_start;
@@ -1143,7 +1121,7 @@ impl<'a> Parser<'a> {
// Parse pivotColumnList: `FOR pivotColumn+` where each
// pivotColumn is `<expr|tuple> IN (cols)`.
self.expect_kw(Kw::For, "FOR")?;
- let mut columns: Vec<Value> = Vec::new();
+ let mut columns: Vec<E::Value> = Vec::new();
loop {
let col_expr = self.parse_expr_tuple_or_single(true)?;
self.expect_kw(Kw::In, "IN")?;
@@ -1157,11 +1135,7 @@ impl<'a> Parser<'a> {
}
let values = self.parse_expr_list_until_paren()?;
self.expect(TokenKind::RParen, ")")?;
- columns.push(json!({
- "node": "PivotColumn",
- "column": col_expr,
- "values": values,
- }));
+ columns.push(self.emit.pivot_column(col_expr, values));
// `pivotColumn+`: keep collecting columns until the
// list terminator — the closing `)` or an optional
// `GROUP BY`. Anything else begins the next
@@ -1186,7 +1160,7 @@ impl<'a> Parser<'a> {
// `parse_expr_list_until_paren` returns an empty Vec on
// `)` immediately, silently accepting; reject explicitly
// to match cpp.
- let mut group_by: Option<Vec<Value>> = None;
+ let mut group_by: Option<Vec<E::Value>> = None;
if matches!(self.peek(), TokenKind::Keyword(Kw::Group))
&& self.peek_next() == TokenKind::Keyword(Kw::By)
{
@@ -1198,15 +1172,8 @@ impl<'a> Parser<'a> {
group_by = Some(self.parse_expr_list_until_paren()?);
}
self.expect(TokenKind::RParen, ")")?;
- let mut obj = serde_json::Map::new();
- obj.insert("node".into(), Value::String("PivotExpr".into()));
- obj.insert("table".into(), table);
- obj.insert("aggregates".into(), Value::Array(aggregates));
- obj.insert("columns".into(), Value::Array(columns));
- if let Some(g) = group_by {
- obj.insert("group_by".into(), Value::Array(g));
- }
- table = self.wrap_pos(Value::Object(obj), pivot_start);
+ let pivot = self.emit.pivot_expr(table, aggregates, columns, group_by);
+ table = self.wrap_pos(pivot, pivot_start);
continue;
}
if matches!(self.peek(), TokenKind::Keyword(Kw::Unpivot)) {
@@ -1224,7 +1191,7 @@ impl<'a> Parser<'a> {
// `tos FOR tos IN ( list ) (tos IN ( list ))*`.
// The trailing `(tos IN ( list ))*` groups are parsed but
// dropped — cpp's visitor keeps only the first IN list.
- let mut columns: Vec<Value> = Vec::new();
+ let mut columns: Vec<E::Value> = Vec::new();
loop {
// value-columns slot is bounded by `FOR`, not a
// structural `IN` — no `pivot_in_stop` needed.
@@ -1235,12 +1202,11 @@ impl<'a> Parser<'a> {
self.expect(TokenKind::LParen, "(")?;
let unpivot_values = self.parse_expr_list_until_paren()?;
self.expect(TokenKind::RParen, ")")?;
- columns.push(json!({
- "node": "UnpivotColumn",
- "value_columns": value_columns,
- "name_columns": name_columns,
- "unpivot_values": unpivot_values,
- }));
+ columns.push(self.emit.unpivot_column(
+ value_columns,
+ name_columns,
+ unpivot_values,
+ ));
// Additional `tos IN ( list )` groups (no FOR, no
// comma) extend the SAME unpivotColumn; they are
// discarded to match cpp.
@@ -1259,17 +1225,8 @@ impl<'a> Parser<'a> {
}
}
self.expect(TokenKind::RParen, ")")?;
- let mut obj = serde_json::Map::new();
- obj.insert("node".into(), Value::String("UnpivotExpr".into()));
- obj.insert("table".into(), table);
- obj.insert("columns".into(), Value::Array(columns));
- // cpp's `VISIT(JoinExprUnpivot)` always emits the
- // `include_nulls` field — default `false` when the
- // `INCLUDE NULLS` modifier isn't present. Rust used to
- // omit the field entirely. Emit unconditionally to
- // match the JSON shape.
- obj.insert("include_nulls".into(), Value::Bool(include_nulls));
- table = self.wrap_pos(Value::Object(obj), unpivot_start);
+ let unpivot = self.emit.unpivot_expr(table, columns, include_nulls);
+ table = self.wrap_pos(unpivot, unpivot_start);
continue;
}
return Ok(table);
@@ -1297,7 +1254,7 @@ impl<'a> Parser<'a> {
/// it as an operator. The value-columns slot of an `unpivotColumn`
/// is bounded by `FOR` instead — never an infix operator — so it
/// needs no stop.
- fn parse_expr_tuple_or_single(&mut self, in_separated: bool) -> Result<Value, ParseError> {
+ fn parse_expr_tuple_or_single(&mut self, in_separated: bool) -> Result<E::Value, ParseError> {
let op_start = self.peek0.start;
if self.peek() == TokenKind::LParen && self.paren_group_followed_by_for_or_in() {
self.bump()?;
@@ -1311,7 +1268,7 @@ impl<'a> Parser<'a> {
// exists only inside PIVOT/UNPIVOT, so every call to this
// function lands in one of those slots and the Tuple
// emission must be position-less to match.
- return Ok(emit::tuple_(exprs));
+ return Ok(self.emit.tuple_(exprs));
}
let stop = if in_separated {
self.find_pivot_in_separator()
@@ -1334,7 +1291,7 @@ impl<'a> Parser<'a> {
{
let t = self.bump()?;
let name = identifier_text(self.text(t), t.kind);
- return Ok(self.wrap_pos(emit::field(vec![Value::String(name)]), op_start));
+ return Ok(self.wrap_pos(self.emit.field(vec![self.emit.string(&name)]), op_start));
}
}
let prev = std::mem::replace(&mut self.pivot_in_stop, stop);
@@ -1493,7 +1450,7 @@ impl<'a> Parser<'a> {
/// spec). Comma-separated.
fn parse_expr_list_until_terminators_at_for_or_rparen(
&mut self,
- ) -> Result<Vec<Value>, ParseError> {
+ ) -> Result<Vec<E::Value>, ParseError> {
let mut out = Vec::new();
loop {
out.push(self.parse_expr_bp(0)?);
@@ -1568,60 +1525,66 @@ fn token_extends_pivot_column_lhs(kind: TokenKind) -> bool {
/// (one past the lead's pre-existing chain). Nodes shallower than that
/// belong to a parens-wrapped inner scope and are opaque — we recurse
/// through them but never attach.
-fn attach_constraint_to_outermost_unconstrained_join(
- node: &mut Value,
- constraint: Value,
+/// Returns `(node, attached)` — `node` is the (possibly updated) input,
+/// `attached` is true iff the constraint was placed.
+fn attach_constraint_to_outermost_unconstrained_join<E: Emitter>(
+ emit: &E,
+ mut node: E::Value,
+ constraint: E::Value,
min_attachable_depth: usize,
current_depth: usize,
-) -> bool {
- let Some(obj) = node.as_object_mut() else {
- return false;
- };
- if obj.get("node").and_then(Value::as_str) != Some("JoinExpr") {
- return false;
+) -> (E::Value, bool) {
+ if emit.node_kind(&node).as_deref() != Some("JoinExpr") {
+ return (node, false);
}
- if let Some(nj) = obj.get_mut("next_join") {
- if nj.is_object()
- && attach_constraint_to_outermost_unconstrained_join(
+ // Try recursing into next_join first.
+ if let Some(nj) = emit.get_field(&node, "next_join") {
+ if emit.node_kind(&nj).is_some() {
+ let (updated, attached) = attach_constraint_to_outermost_unconstrained_join(
+ emit,
nj,
constraint.clone(),
min_attachable_depth,
current_depth + 1,
- )
- {
- return true;
+ );
+ emit.set_field(&mut node, "next_join", updated);
+ if attached {
+ return (node, true);
+ }
}
}
if current_depth < min_attachable_depth {
- return false;
+ return (node, false);
}
- // Per the grammar, only `JoinExprOp` and `JoinExprPositional` take a
- // `joinConstraintClause`. The lead `JoinExprTable` carries no `join_type`,
- // and `JoinExprCrossOp` is explicitly CROSS — refuse both.
- let accepts_constraint = matches!(
- obj.get("join_type").and_then(Value::as_str),
- Some(jt) if jt != "CROSS JOIN"
- );
+ let join_type = emit
+ .get_field(&node, "join_type")
+ .and_then(|v| emit.as_str(&v).map(|s| s.into_owned()));
+ let accepts_constraint = matches!(join_type.as_deref(), Some(jt) if jt != "CROSS JOIN");
if !accepts_constraint {
- return false;
+ return (node, false);
}
- if matches!(obj.get("constraint"), None | Some(Value::Null)) {
- obj.insert("constraint".into(), constraint);
- return true;
+ let existing = emit.get_field(&node, "constraint");
+ let is_unset = existing.as_ref().map(|v| emit.is_null(v)).unwrap_or(true);
+ if is_unset {
+ emit.set_field(&mut node, "constraint", constraint);
+ return (node, true);
}
- false
+ (node, false)
}
/// Count JoinExprs linked via `next_join`. Lead is depth 1.
-fn chain_depth(node: &Value) -> usize {
+fn chain_depth<E: Emitter>(emit: &E, node: &E::Value) -> usize {
let mut depth = 1;
- let mut cursor = node;
- while let Some(nj) = cursor.as_object().and_then(|o| o.get("next_join")) {
- if !nj.is_object() {
- break;
+ let mut cursor: E::Value = node.clone();
+ loop {
+ let nj = emit.get_field(&cursor, "next_join");
+ match nj {
+ Some(v) if emit.node_kind(&v).is_some() => {
+ depth += 1;
+ cursor = v;
+ }
+ _ => break,
}
- depth += 1;
- cursor = nj;
}
depth
}
diff --git a/rust/hogql/parser/src/parse/program.rs b/rust/hogql/parser/src/parse/program.rs
index bff5e9eb0156..cd0a02735c3b 100644
--- a/rust/hogql/parser/src/parse/program.rs
+++ b/rust/hogql/parser/src/parse/program.rs
@@ -26,17 +26,15 @@
//! - Block { declarations: [decl, ...] }
//! - Program { declarations: [decl, ...] }
-use serde_json::{json, Value};
-
use super::{identifier_text, kw_valid_as_identifier, Parser};
-use crate::emit;
+use crate::emit::Emitter;
use crate::error::ParseError;
use crate::lex::{Kw, Lexer, TokenKind};
-impl<'a> Parser<'a> {
- pub(crate) fn parse_program(&mut self) -> Result<Value, ParseError> {
+impl<'a, E: Emitter + Clone> Parser<'a, E> {
+ pub(crate) fn parse_program(&mut self) -> Result<E::Value, ParseError> {
let prog_start = self.peek0.start;
- let mut declarations: Vec<Value> = Vec::new();
+ let mut declarations: Vec<E::Value> = Vec::new();
while !matches!(self.peek(), TokenKind::Eof) {
// Empty statement (a stray `;`) is a no-op — skip it
// without producing a declaration so the AST stays clean.
@@ -53,17 +51,10 @@ impl<'a> Parser<'a> {
// source length explicitly rather than `last_consumed_end` so
// `let x := 1\n` ends at 11 (matching cpp) not 10 (the `1`).
let prog_end = self.src.len();
- Ok(self.wrap_pos_to(
- json!({
- "node": "Program",
- "declarations": declarations,
- }),
- prog_start,
- prog_end,
- ))
+ Ok(self.wrap_pos_to(self.emit.program(declarations), prog_start, prog_end))
}
- fn parse_declaration(&mut self) -> Result<Value, ParseError> {
+ fn parse_declaration(&mut self) -> Result<E::Value, ParseError> {
let decl_start = self.peek0.start;
let result = if self.peek() == TokenKind::Keyword(Kw::Let) {
self.parse_var_decl()?
@@ -78,7 +69,7 @@ impl<'a> Parser<'a> {
/// `exprStmt` — with the `stop_postfix_call_before_colon_equals`
/// guard active, so a trailing `(…) :=` opens the NEXT statement
/// instead of folding into this expression as a postfix call.
- fn parse_stmt_rhs_expr(&mut self) -> Result<Value, ParseError> {
+ fn parse_stmt_rhs_expr(&mut self) -> Result<E::Value, ParseError> {
let prev_postfix = self.stop_postfix_call_before_colon_equals;
self.stop_postfix_call_before_colon_equals = true;
let prev_recover = self.stmt_rhs_recover_on_pratt_rhs_failure;
@@ -97,7 +88,7 @@ impl<'a> Parser<'a> {
/// the trailing `;`, so wrapping with `last_consumed_end` after a
/// local `eat(Semicolon)` would over-extend the span by 1 byte
/// vs cpp's `addPositionInfo(json, ctx)`.
- fn parse_var_decl(&mut self) -> Result<Value, ParseError> {
+ fn parse_var_decl(&mut self) -> Result<E::Value, ParseError> {
self.expect_kw(Kw::Let, "let")?;
let name_tok = self.bump()?;
let name = match name_tok.kind {
@@ -118,56 +109,42 @@ impl<'a> Parser<'a> {
)));
}
};
- let mut obj = serde_json::Map::new();
- obj.insert("node".into(), Value::String("VariableDeclaration".into()));
- obj.insert("name".into(), Value::String(name));
+ let mut expr_val = self.emit.null();
if self.eat(TokenKind::ColonEquals)? {
let cp = self.checkpoint();
let expr = self.parse_stmt_rhs_expr()?;
// cpp's varDecl grammar (`LET ident (':=' expression)?`)
// has no place for a trailing `:=` after the expression.
// When one follows, cpp's ANTLR ALL(*) shortens the
- // expression to the shortest prefix (the leading single
- // token) that leaves the trailing `:=` as the START of a
- // *new* statement's varAssignment lvalue. `let x := y *
- // (z) := 3` → `let x := y` + `*(z) := 3`. Rust used to
- // greedy-parse the full `y * (z)` and then choke on the
- // dangling `:=`.
+ // expression to the shortest prefix that leaves the
+ // trailing `:=` as the START of a *new* statement's
+ // varAssignment lvalue. `let x := y * (z) := 3` →
+ // `let x := y` + `*(z) := 3`.
if self.peek() == TokenKind::ColonEquals {
- // Shorten to the leading primary form. cpp's ALL(*)
- // does the equivalent: take the shortest columnExpr
- // prefix (typically just one primary — a single token
- // for ident/number/string/`*`, or a paren-wrapped
- // group unwrapped to its inner) that leaves the
- // trailing `:=` and its rhs as a separate statement.
- // `parse_prefix` handles all primary shapes cleanly.
self.restore(cp)?;
match self.parse_prefix() {
Ok(primary) => {
- obj.insert("expr".into(), primary);
+ expr_val = primary;
}
Err(_) => {
- // Re-parse and accept the full greedy result —
- // we'll error at the next statement boundary
- // the same way the original code did.
self.restore(cp)?;
- obj.insert("expr".into(), self.parse_stmt_rhs_expr()?);
+ expr_val = self.parse_stmt_rhs_expr()?;
}
}
} else {
- obj.insert("expr".into(), expr);
+ expr_val = expr;
}
}
- Ok(Value::Object(obj))
+ Ok(self.emit.variable_declaration(&name, expr_val))
}
- fn parse_statement(&mut self) -> Result<Value, ParseError> {
+ fn parse_statement(&mut self) -> Result<E::Value, ParseError> {
let stmt_start = self.peek0.start;
let result = self.parse_statement_inner()?;
Ok(self.wrap_pos(result, stmt_start))
}
- fn parse_statement_inner(&mut self) -> Result<Value, ParseError> {
+ fn parse_statement_inner(&mut self) -> Result<E::Value, ParseError> {
match self.peek() {
TokenKind::Keyword(Kw::Return) => self.parse_return_stmt(),
TokenKind::Keyword(Kw::Throw) => self.parse_throw_stmt(),
@@ -230,16 +207,16 @@ impl<'a> Parser<'a> {
// outright in `parse_program` / `parse_block`.)
TokenKind::Semicolon => {
self.bump()?;
- Ok(json!({"node": "ExprStatement", "expr": Value::Null}))
+ Ok(self.emit.expr_statement(self.emit.null()))
}
_ => self.parse_expr_or_assignment_stmt(),
}
}
- fn parse_return_stmt(&mut self) -> Result<Value, ParseError> {
+ fn parse_return_stmt(&mut self) -> Result<E::Value, ParseError> {
self.expect_kw(Kw::Return, "return")?;
- let mut obj = serde_json::Map::new();
- obj.insert("node".into(), Value::String("ReturnStatement".into()));
+ let mut expr_val = self.emit.null();
+
// `returnStmt: RETURN expression? SEMICOLON?` — the expression
// is optional. cpp's ANTLR takes the `?` only when an
// `expression` actually parses. Two filters mirror that:
@@ -286,7 +263,7 @@ impl<'a> Parser<'a> {
self.restore(cp)?;
if self.peek() == TokenKind::Asterisk {
self.bump()?;
- obj.insert("expr".into(), emit::field(vec![Value::String("*".into())]));
+ expr_val = self.emit.field(vec![self.emit.string("*")]);
} else if matches!(
self.peek(),
TokenKind::Ident | TokenKind::QuotedIdent | TokenKind::Keyword(_)
@@ -294,50 +271,35 @@ impl<'a> Parser<'a> {
self.peek_next(),
TokenKind::Dot | TokenKind::NullProperty
) {
- // First single token as Field — cpp shortens to
- // a one-element chain regardless of what comes
- // after (call, infix, or another statement
- // keyword). The Dot / `?.` exclusion stops a
- // multi-token chain `a.b := c` from being
- // split (cpp's ANTLR backtracks past chained
- // shortening to the bare-return path in that
- // shape).
let t = self.bump()?;
let name = identifier_text(self.text(t), t.kind);
- obj.insert("expr".into(), emit::field(vec![Value::String(name)]));
- } else {
- obj.insert("expr".into(), Value::Null);
+ expr_val = self.emit.field(vec![self.emit.string(&name)]);
}
}
Ok(expr) => {
- obj.insert("expr".into(), expr);
+ expr_val = expr;
}
Err(_) => {
self.restore(cp)?;
- obj.insert("expr".into(), Value::Null);
}
}
- } else {
- obj.insert("expr".into(), Value::Null);
}
let _ = self.eat(TokenKind::Semicolon)?;
- Ok(Value::Object(obj))
+ Ok(self.emit.return_statement(expr_val))
}
- fn parse_throw_stmt(&mut self) -> Result<Value, ParseError> {
+ fn parse_throw_stmt(&mut self) -> Result<E::Value, ParseError> {
self.expect_kw(Kw::Throw, "throw")?;
- let mut obj = serde_json::Map::new();
- obj.insert("node".into(), Value::String("ThrowStatement".into()));
// `throwStmt: THROW expression SEMICOLON?` — the expression is
// MANDATORY (unlike `returnStmt`'s `expression?`). A bare
// `throw` / `throw;` is rejected. `parse_expr_bp` raises on a
// missing expression, so no explicit empty-check is needed.
- obj.insert("expr".into(), self.parse_stmt_rhs_expr()?);
+ let expr = self.parse_stmt_rhs_expr()?;
let _ = self.eat(TokenKind::Semicolon)?;
- Ok(Value::Object(obj))
+ Ok(self.emit.throw_statement(expr))
}
- fn parse_if_stmt(&mut self) -> Result<Value, ParseError> {
+ fn parse_if_stmt(&mut self) -> Result<E::Value, ParseError> {
self.expect_kw(Kw::If, "if")?;
self.expect(TokenKind::LParen, "(")?;
let cond = self.parse_expr_bp(0)?;
@@ -348,32 +310,25 @@ impl<'a> Parser<'a> {
} else {
None
};
- Ok(json!({
- "node": "IfStatement",
- "expr": cond,
- "then": then,
- "else_": else_.unwrap_or(Value::Null),
- }))
+ Ok(self
+ .emit
+ .if_statement(cond, then, else_.unwrap_or_else(|| self.emit.null())))
}
- fn parse_while_stmt(&mut self) -> Result<Value, ParseError> {
+ fn parse_while_stmt(&mut self) -> Result<E::Value, ParseError> {
self.expect_kw(Kw::While, "while")?;
self.expect(TokenKind::LParen, "(")?;
let cond = self.parse_expr_bp(0)?;
self.expect(TokenKind::RParen, ")")?;
let body = self.parse_statement()?;
let _ = self.eat(TokenKind::Semicolon)?;
- Ok(json!({
- "node": "WhileStatement",
- "expr": cond,
- "body": body,
- }))
+ Ok(self.emit.while_statement(cond, body))
}
/// `for (...)` dispatches between the C-style triple-clause form
/// and the `for (let ident (, ident)? in expr) body` for-in form
/// by probing past the `LET`.
- fn parse_for_or_for_in_stmt(&mut self) -> Result<Value, ParseError> {
+ fn parse_for_or_for_in_stmt(&mut self) -> Result<E::Value, ParseError> {
self.expect_kw(Kw::For, "for")?;
self.expect(TokenKind::LParen, "(")?;
// Detect for-in by probing: `LET ident (, ident)? IN`.
@@ -423,13 +378,13 @@ impl<'a> Parser<'a> {
self.expect(TokenKind::RParen, ")")?;
let body = self.parse_statement()?;
let _ = self.eat(TokenKind::Semicolon)?;
- return Ok(json!({
- "node": "ForInStatement",
- "keyVar": key_var.map(Value::String).unwrap_or(Value::Null),
- "valueVar": value_var,
- "expr": iter_expr,
- "body": body,
- }));
+ let key_var = key_var
+ .map(|s| self.emit.string(&s))
+ .unwrap_or_else(|| self.emit.null());
+ let value_var = self.emit.string(&value_var);
+ return Ok(self
+ .emit
+ .for_in_statement(key_var, value_var, iter_expr, body));
}
// C-style: (init?; cond?; incr?) body
let initializer = if self.peek() != TokenKind::Semicolon {
@@ -452,13 +407,13 @@ impl<'a> Parser<'a> {
self.expect(TokenKind::RParen, ")")?;
let body = self.parse_statement()?;
let _ = self.eat(TokenKind::Semicolon)?;
- Ok(json!({
- "node": "ForStatement",
- "initializer": initializer.unwrap_or(Value::Null),
- "condition": condition.unwrap_or(Value::Null),
- "increment": increment.unwrap_or(Value::Null),
- "body": body,
- }))
+ let n = self.emit.null();
+ Ok(self.emit.for_statement(
+ initializer.unwrap_or_else(|| n.clone()),
+ condition.unwrap_or_else(|| n.clone()),
+ increment.unwrap_or_else(|| n.clone()),
+ body,
+ ))
}
/// `for`'s initializer / increment slot accepts `varDecl`,
@@ -466,7 +421,7 @@ impl<'a> Parser<'a> {
/// varDecl shape is unambiguous (`LET` prefix); the other two
/// share the expression prefix and disambiguate by the trailing
/// `:=` token after the expression.
- fn parse_for_clause(&mut self) -> Result<Value, ParseError> {
+ fn parse_for_clause(&mut self) -> Result<E::Value, ParseError> {
// cpp positions the for-clause initializer / increment in the
// outer `ForStmt` ctx, so each shape needs a `start` / `end`
// matching cpp's per-node visit. Capture the slot's start and
@@ -489,16 +444,12 @@ impl<'a> Parser<'a> {
let name = identifier_text(self.text(id), id.kind);
self.bump()?; // `:=`
let right = self.parse_stmt_rhs_expr()?;
- let left =
- self.wrap_pos_to(json!({"node": "Field", "chain": [name]}), id_start, id_end);
- return Ok(self.wrap_pos(
- json!({
- "node": "VariableAssignment",
- "left": left,
- "right": right,
- }),
- clause_start,
- ));
+ let left = self.wrap_pos_to(
+ self.emit.field(vec![self.emit.string(&name)]),
+ id_start,
+ id_end,
+ );
+ return Ok(self.wrap_pos(self.emit.variable_assignment(left, right), clause_start));
}
// Leading expression — parsed without the
// `stop_postfix_call_before_colon_equals` guard (see
@@ -507,14 +458,7 @@ impl<'a> Parser<'a> {
let expr = self.parse_expr_bp(0)?;
if self.eat(TokenKind::ColonEquals)? {
let right = self.parse_stmt_rhs_expr()?;
- return Ok(self.wrap_pos(
- json!({
- "node": "VariableAssignment",
- "left": expr,
- "right": right,
- }),
- clause_start,
- ));
+ return Ok(self.wrap_pos(self.emit.variable_assignment(expr, right), clause_start));
}
Ok(expr)
}
@@ -522,7 +466,7 @@ impl<'a> Parser<'a> {
/// `LET ident (:= expression)?` without the trailing-`;` consume —
/// used inside `for (...)` where the `;` is the for-loop
/// separator, not a statement terminator.
- fn parse_var_decl_no_semicolon(&mut self) -> Result<Value, ParseError> {
+ fn parse_var_decl_no_semicolon(&mut self) -> Result<E::Value, ParseError> {
self.expect_kw(Kw::Let, "let")?;
let name_tok = self.bump()?;
let name = match name_tok.kind {
@@ -539,13 +483,12 @@ impl<'a> Parser<'a> {
)));
}
};
- let mut obj = serde_json::Map::new();
- obj.insert("node".into(), Value::String("VariableDeclaration".into()));
- obj.insert("name".into(), Value::String(name));
- if self.eat(TokenKind::ColonEquals)? {
- obj.insert("expr".into(), self.parse_stmt_rhs_expr()?);
- }
- Ok(Value::Object(obj))
+ let expr_val = if self.eat(TokenKind::ColonEquals)? {
+ self.parse_stmt_rhs_expr()?
+ } else {
+ self.emit.null()
+ };
+ Ok(self.emit.variable_declaration(&name, expr_val))
}
/// Probe: starting at the `LET` token after `for (`, look ahead for
@@ -584,7 +527,7 @@ impl<'a> Parser<'a> {
}
}
- fn parse_func_stmt(&mut self) -> Result<Value, ParseError> {
+ fn parse_func_stmt(&mut self) -> Result<E::Value, ParseError> {
// FN or FUN — both accepted, both emit the same Function node.
self.bump()?;
let name_tok = self.bump()?;
@@ -606,12 +549,11 @@ impl<'a> Parser<'a> {
// chain `a.b.c`, not a single name), and a trailing comma is
// allowed. cpp's visitor joins the chain with `.` into one
// param string (`a.b.c`).
- let mut params: Vec<Value> = Vec::new();
+ let mut params: Vec<E::Value> = Vec::new();
if self.peek() != TokenKind::RParen {
loop {
- params.push(Value::String(
- self.parse_nested_identifier_text("parameter name")?,
- ));
+ let pname = self.parse_nested_identifier_text("parameter name")?;
+ params.push(self.emit.string(&pname));
if !self.eat(TokenKind::Comma)? {
break;
}
@@ -622,19 +564,14 @@ impl<'a> Parser<'a> {
}
self.expect(TokenKind::RParen, ")")?;
let body = self.parse_block()?;
- Ok(json!({
- "node": "Function",
- "name": name,
- "params": params,
- "body": body,
- }))
+ Ok(self.emit.function_(&name, params, body))
}
/// `try block (catch (var (: type)?)? block)* (finally block)?`
- fn parse_try_catch_stmt(&mut self) -> Result<Value, ParseError> {
+ fn parse_try_catch_stmt(&mut self) -> Result<E::Value, ParseError> {
self.expect_kw(Kw::Try, "try")?;
let try_stmt = self.parse_block()?;
- let mut catches: Vec<Value> = Vec::new();
+ let mut catches: Vec<E::Value> = Vec::new();
while self.peek() == TokenKind::Keyword(Kw::Catch) {
self.bump()?; // catch
let (var, ty) = if self.eat(TokenKind::LParen)? {
@@ -678,23 +615,24 @@ impl<'a> Parser<'a> {
(None, None)
};
let catch_block = self.parse_block()?;
- catches.push(json!([
- var.map(Value::String).unwrap_or(Value::Null),
- ty.map(Value::String).unwrap_or(Value::Null),
- catch_block,
- ]));
+ let v = var
+ .map(|s| self.emit.string(&s))
+ .unwrap_or_else(|| self.emit.null());
+ let t = ty
+ .map(|s| self.emit.string(&s))
+ .unwrap_or_else(|| self.emit.null());
+ catches.push(self.emit.catch_clause(v, t, catch_block));
}
let finally_stmt = if self.eat_kw(Kw::Finally)? {
Some(self.parse_block()?)
} else {
None
};
- Ok(json!({
- "node": "TryCatchStatement",
- "try_stmt": try_stmt,
- "catches": catches,
- "finally_stmt": finally_stmt.unwrap_or(Value::Null),
- }))
+ Ok(self.emit.try_catch_statement(
+ try_stmt,
+ catches,
+ finally_stmt.unwrap_or_else(|| self.emit.null()),
+ ))
}
/// `self.peek()` is `{` — scan to its matching `}` and report
@@ -724,10 +662,10 @@ impl<'a> Parser<'a> {
)
}
- pub(crate) fn parse_block(&mut self) -> Result<Value, ParseError> {
+ pub(crate) fn parse_block(&mut self) -> Result<E::Value, ParseError> {
let block_start = self.peek0.start;
self.expect(TokenKind::LBrace, "{")?;
- let mut declarations: Vec<Value> = Vec::new();
+ let mut declarations: Vec<E::Value> = Vec::new();
while !matches!(self.peek(), TokenKind::RBrace | TokenKind::Eof) {
if self.peek() == TokenKind::Semicolon {
self.bump()?;
@@ -736,13 +674,7 @@ impl<'a> Parser<'a> {
declarations.push(self.parse_declaration()?);
}
self.expect(TokenKind::RBrace, "}")?;
- Ok(self.wrap_pos(
- json!({
- "node": "Block",
- "declarations": declarations,
- }),
- block_start,
- ))
+ Ok(self.wrap_pos(self.emit.block(declarations), block_start))
}
/// Does the cursor sit on a bare `<ident> :=` — a single
@@ -778,7 +710,7 @@ impl<'a> Parser<'a> {
/// `obj.prop := value` go through the fallback — the Field chain
/// completes before `:=` is reached, so parse_ident_lead doesn't
/// see the ColonEquals.
- fn parse_expr_or_assignment_stmt(&mut self) -> Result<Value, ParseError> {
+ fn parse_expr_or_assignment_stmt(&mut self) -> Result<E::Value, ParseError> {
if self.peek_is_bare_assignment_lead() {
let id_start = self.peek0.start;
let id_end = self.peek0.end;
@@ -797,23 +729,19 @@ impl<'a> Parser<'a> {
if self.eat(TokenKind::ColonEquals)? {
let outer_right = self.parse_stmt_rhs_expr()?;
let _ = self.eat(TokenKind::Semicolon)?;
- return Ok(json!({
- "node": "VariableAssignment",
- "left": emit::named_argument(&name, right),
- "right": outer_right,
- }));
+ let left = self.emit.named_argument(&name, right);
+ return Ok(self.emit.variable_assignment(left, outer_right));
}
// The `:=` form is an `exprStmt` (`expression (COLONEQUALS
// expression)? SEMICOLON?`) — consume the optional trailing
// `;` so `if (c) a := b ; else d` sees the `else`.
let _ = self.eat(TokenKind::Semicolon)?;
- let left =
- self.wrap_pos_to(json!({"node": "Field", "chain": [name]}), id_start, id_end);
- return Ok(json!({
- "node": "VariableAssignment",
- "left": left,
- "right": right,
- }));
+ let left = self.wrap_pos_to(
+ self.emit.field(vec![self.emit.string(&name)]),
+ id_start,
+ id_end,
+ );
+ return Ok(self.emit.variable_assignment(left, right));
}
// The leading expression is parsed WITHOUT the
// `stop_postfix_call_before_colon_equals` guard: a `(…)` here
@@ -842,17 +770,10 @@ impl<'a> Parser<'a> {
// optional trailing `;`. Without it `if (c) a := b ; else
// d` would not see the `else` (the `;` would strand).
let _ = self.eat(TokenKind::Semicolon)?;
- return Ok(json!({
- "node": "VariableAssignment",
- "left": expr,
- "right": right,
- }));
+ return Ok(self.emit.variable_assignment(expr, right));
}
let _ = self.eat(TokenKind::Semicolon)?;
- Ok(json!({
- "node": "ExprStatement",
- "expr": expr,
- }))
+ Ok(self.emit.expr_statement(expr))
}
/// Read a `nestedIdentifier` — `identifier (DOT identifier)*` —
@@ -888,9 +809,9 @@ impl<'a> Parser<'a> {
/// `{}` Block, a `{1: 2}` Dict exprStmt — is rejected so `try_alt`
/// falls through to the Block / exprStmt arms. Mirrors ANTLR
/// trying `varAssignment` before `block` / `exprStmt`.
- fn parse_brace_lvalue_assignment(&mut self) -> Result<Value, ParseError> {
+ fn parse_brace_lvalue_assignment(&mut self) -> Result<E::Value, ParseError> {
let stmt = self.parse_expr_or_assignment_stmt()?;
- if stmt.get("node").and_then(Value::as_str) == Some("VariableAssignment") {
+ if self.emit.node_kind(&stmt).as_deref() == Some("VariableAssignment") {
Ok(stmt)
} else {
Err(self.err("`{…}`-led statement is not a varAssignment"))
diff --git a/rust/hogql/parser/src/parse/select.rs b/rust/hogql/parser/src/parse/select.rs
index 4cf764aa3a8b..42261524fcad 100644
--- a/rust/hogql/parser/src/parse/select.rs
+++ b/rust/hogql/parser/src/parse/select.rs
@@ -8,29 +8,23 @@
//! ARRAY JOIN is handled here (not in `join.rs`) because the grammar
//! attaches it to the SELECT, not to the join chain.
-use serde_json::{json, Value};
-
use super::expr::is_bare_field;
use super::{
check_alias_not_reserved, format_set_op, identifier_text, inject_ctes_into_select,
kw_allowed_as_implicit_alias, merge_select_decorators, Parser, BP_MULT,
};
-use crate::emit;
+use crate::emit::Emitter;
use crate::error::ParseError;
use crate::lex::{Kw, Lexer, TokenKind};
-impl<'a> Parser<'a> {
- pub(crate) fn parse_select_set_stmt(&mut self) -> Result<Value, ParseError> {
+impl<'a, E: Emitter + Clone> Parser<'a, E> {
+ pub(crate) fn parse_select_set_stmt(&mut self) -> Result<E::Value, ParseError> {
let stmt_start = self.peek0.start;
let first = self.parse_select_stmt_with_parens()?;
- let mut subsequent: Vec<Value> = Vec::new();
+ let mut subsequent: Vec<E::Value> = Vec::new();
while let Some(op) = self.try_consume_set_op()? {
let next = self.parse_select_stmt_with_parens()?;
- subsequent.push(json!({
- "node": "SelectSetNode",
- "select_query": next,
- "set_operator": op,
- }));
+ subsequent.push(self.emit.select_set_node(next, Some(op.as_str())));
}
// Optional trailing ORDER BY / LIMIT / OFFSET at the
@@ -59,16 +53,14 @@ impl<'a> Parser<'a> {
// (lines 633-651) writes only `limit` and `offset`. Mirror
// that: drop those two fields when collapsing to a single
// SelectQuery.
- let filtered: Vec<(String, Value)> = trailing
+ let filtered: Vec<(String, E::Value)> = trailing
.into_iter()
.filter(|(k, _)| k != "limit_percent" && k != "limit_with_ties")
.collect();
// Clear the lift sentinel on the inner — it's only meaningful
// when wrapping in a SelectSetQuery.
let mut first = first;
- if let Some(obj) = first.as_object_mut() {
- obj.remove("__rust_offset_liftable");
- }
+ self.emit.remove_field(&mut first, "__rust_offset_liftable");
// A set-level LIMIT / OFFSET clause has nowhere to attach on a
// bare `{placeholder}` select body — only `SelectQuery` /
// `SelectSetQuery` carry those fields — so it is dropped, the
@@ -76,7 +68,7 @@ impl<'a> Parser<'a> {
// be written onto the `Placeholder` node and crash AST
// deserialization.
let body_takes_decorators = matches!(
- first.get("node").and_then(Value::as_str),
+ self.emit.node_kind(&first).as_deref(),
Some("SelectQuery") | Some("SelectSetQuery")
);
if !body_takes_decorators {
@@ -90,7 +82,7 @@ impl<'a> Parser<'a> {
// limit / offset / limit_with_ties / limit_percent fields
// without re-stamping positions — so the end stays at the
// last body-level clause cpp consumed. Mirror that exactly.
- let merged = merge_select_decorators(first, filtered);
+ let merged = merge_select_decorators(&self.emit, first, filtered);
// `has_set_level_trailing` is unused here (we keep it
// declared above for parity with the set-stmt branch's
// OFFSET-lift heuristic, which it still feeds).
@@ -117,9 +109,7 @@ impl<'a> Parser<'a> {
let mut first = first;
// Clean the lift sentinel off the initial SELECT — cpp's lift
// only ever applies to the LAST inner SELECT, never the first.
- if let Some(obj) = first.as_object_mut() {
- obj.remove("__rust_offset_liftable");
- }
+ self.emit.remove_field(&mut first, "__rust_offset_liftable");
// …and off every non-last subsequent SELECT (the lift only
// applies to the trailing inner).
let last_idx = subsequent.len().saturating_sub(1);
@@ -127,12 +117,9 @@ impl<'a> Parser<'a> {
if i == last_idx {
continue;
}
- if let Some(sq) = node
- .as_object_mut()
- .and_then(|n| n.get_mut("select_query"))
- .and_then(Value::as_object_mut)
- {
- sq.remove("__rust_offset_liftable");
+ if let Some(mut sq) = self.emit.get_field(node, "select_query") {
+ self.emit.remove_field(&mut sq, "__rust_offset_liftable");
+ self.emit.set_field(node, "select_query", sq);
}
}
// Lift the inner's verbose OFFSET to the outer SelectSetQuery
@@ -154,35 +141,36 @@ impl<'a> Parser<'a> {
// `has_set_level_trailing` captures the ORDER-BY case (the
// trailing decorator is consumed-and-dropped, so an
// after-the-fact `trailing.iter()` check misses it).
- let inner_offset = subsequent
- .last_mut()
- .and_then(Value::as_object_mut)
- .and_then(|n| n.get_mut("select_query"))
- .and_then(Value::as_object_mut)
- .and_then(|sq| {
- let liftable = sq
- .remove("__rust_offset_liftable")
- .and_then(|v| v.as_bool())
+ let inner_offset = if let Some(last) = subsequent.last_mut() {
+ if let Some(mut sq) = self.emit.get_field(last, "select_query") {
+ let liftable = self
+ .emit
+ .remove_field(&mut sq, "__rust_offset_liftable")
+ .and_then(|v| self.emit.as_bool(&v))
== Some(true);
- if liftable && !has_set_level_trailing {
- sq.remove("offset")
+ let off = if liftable && !has_set_level_trailing {
+ self.emit.remove_field(&mut sq, "offset")
} else {
None
- }
- });
- let mut wrap = serde_json::Map::new();
- wrap.insert("node".into(), Value::String("SelectSetQuery".into()));
- wrap.insert("initial_select_query".into(), first);
- wrap.insert("subsequent_select_queries".into(), Value::Array(subsequent));
+ };
+ self.emit.set_field(last, "select_query", sq);
+ off
+ } else {
+ None
+ }
+ } else {
+ None
+ };
+ let mut wrap = self.emit.select_set_query(first, subsequent);
if let Some(off) = inner_offset {
- wrap.insert("offset".into(), off);
+ self.emit.set_field(&mut wrap, "offset", off);
}
// Trailing decorators are applied last so they can override
// the lifted inner offset when present.
for (k, v) in trailing {
- wrap.insert(k, v);
+ self.emit.set_field(&mut wrap, &k, v);
}
- Ok(self.wrap_pos(Value::Object(wrap), stmt_start))
+ Ok(self.wrap_pos(wrap, stmt_start))
}
fn try_consume_set_op(&mut self) -> Result<Option<String>, ParseError> {
@@ -214,8 +202,8 @@ impl<'a> Parser<'a> {
Ok(Some(op))
}
- fn parse_trailing_set_decorators(&mut self) -> Result<Vec<(String, Value)>, ParseError> {
- let mut out: Vec<(String, Value)> = Vec::new();
+ fn parse_trailing_set_decorators(&mut self) -> Result<Vec<(String, E::Value)>, ParseError> {
+ let mut out: Vec<(String, E::Value)> = Vec::new();
// `selectSetStmt`'s `orderByClause?` slot at this level is
// parsed by ANTLR but cpp's `VISIT(SelectSetStmt)` never emits
// it — `(SELECT 1) ORDER BY 2` drops the ORDER BY entirely.
@@ -304,10 +292,10 @@ impl<'a> Parser<'a> {
out.push(("offset".into(), off));
}
if percent {
- out.push(("limit_percent".into(), Value::Bool(true)));
+ out.push(("limit_percent".into(), self.emit.bool(true)));
}
if with_ties {
- out.push(("limit_with_ties".into(), Value::Bool(true)));
+ out.push(("limit_with_ties".into(), self.emit.bool(true)));
}
} else if self.eat_kw(Kw::Offset)? {
// `offsetOnlyClause: OFFSET columnExpr` — a full
@@ -320,7 +308,7 @@ impl<'a> Parser<'a> {
Ok(out)
}
- fn parse_select_stmt_with_parens(&mut self) -> Result<Value, ParseError> {
+ fn parse_select_stmt_with_parens(&mut self) -> Result<E::Value, ParseError> {
// `WITH … (selectSet)` — paren'd set wrapper form with CTEs.
// Consume the WITH clause and its CTEs, then peek the next token
// to decide between the two valid continuations:
@@ -337,16 +325,14 @@ impl<'a> Parser<'a> {
let mut ctes = self.parse_with_expr_list()?;
if recursive {
for cte in ctes.iter_mut() {
- if let Some(o) = cte.as_object_mut() {
- o.insert("recursive".into(), Value::Bool(true));
- }
+ self.emit.set_field(cte, "recursive", self.emit.bool(true));
}
}
if matches!(self.peek(), TokenKind::LParen) {
self.bump()?;
let mut inner = self.parse_select_set_stmt()?;
self.expect(TokenKind::RParen, ")")?;
- inject_ctes_into_select(&mut inner, ctes);
+ inject_ctes_into_select(&self.emit, &mut inner, ctes);
// cpp's `WITH ctes (selectSet)` ctx for the outer
// SelectSetQuery starts at the `(`, NOT at WITH. The
// CTEs are injected into the inner set's SelectQuery,
@@ -376,7 +362,7 @@ impl<'a> Parser<'a> {
}
/// Single `SELECT` statement with all its clauses.
- fn parse_select_stmt(&mut self) -> Result<Value, ParseError> {
+ fn parse_select_stmt(&mut self) -> Result<E::Value, ParseError> {
// WITH at the start; consume CTEs here then delegate to the body
// helper. This lets parse_select_stmt_with_parens hand us
// already-parsed CTEs when it disambiguated WITH+`(`.
@@ -388,15 +374,13 @@ impl<'a> Parser<'a> {
} else {
None
};
- let mut ctes: Option<Vec<Value>> = None;
+ let mut ctes: Option<Vec<E::Value>> = None;
if self.eat_kw(Kw::With)? {
let recursive = self.eat_kw(Kw::Recursive)?;
let mut parsed = self.parse_with_expr_list()?;
if recursive {
for cte in parsed.iter_mut() {
- if let Some(o) = cte.as_object_mut() {
- o.insert("recursive".into(), Value::Bool(true));
- }
+ self.emit.set_field(cte, "recursive", self.emit.bool(true));
}
}
ctes = Some(parsed);
@@ -413,14 +397,14 @@ impl<'a> Parser<'a> {
/// WITH-led statement.
fn parse_select_stmt_body(
&mut self,
- pre_parsed_ctes: Option<Vec<Value>>,
+ pre_parsed_ctes: Option<Vec<E::Value>>,
override_start: Option<usize>,
- ) -> Result<Value, ParseError> {
+ ) -> Result<E::Value, ParseError> {
let stmt_start = override_start.unwrap_or(self.peek0.start);
- let mut obj = serde_json::Map::new();
- obj.insert("node".into(), Value::String("SelectQuery".into()));
+ let mut obj = self.emit.select_query_empty();
if let Some(ctes) = pre_parsed_ctes {
- obj.insert("ctes".into(), Value::Array(ctes));
+ self.emit
+ .set_field(&mut obj, "ctes", self.emit.list_value(ctes));
}
// Catch typo'd SELECT keyword (e.g. `SELEC`) with a message close
@@ -442,7 +426,8 @@ impl<'a> Parser<'a> {
self.bump()?;
let distinct = self.eat_kw(Kw::Distinct)?;
if distinct {
- obj.insert("distinct".into(), Value::Bool(true));
+ self.emit
+ .set_field(&mut obj, "distinct", self.emit.bool(true));
}
// `topClause: TOP DECIMAL_LITERAL (WITH TIES)?` — accepted by
// the grammar, rejected by the cpp visitor as unsupported. A
@@ -468,11 +453,12 @@ impl<'a> Parser<'a> {
self.peek0.start, self.peek0.end,
));
}
- obj.insert("select".into(), Value::Array(columns));
+ self.emit
+ .set_field(&mut obj, "select", self.emit.list_value(columns));
if self.eat_kw(Kw::From)? {
let join = self.parse_join_expr()?;
- obj.insert("select_from".into(), join);
+ self.emit.set_field(&mut obj, "select_from", join);
}
// ARRAY JOIN: `(LEFT|INNER)? ARRAY JOIN <expr_list>`.
let array_join_op_kw = if matches!(self.peek(), TokenKind::Keyword(Kw::Left))
@@ -498,7 +484,7 @@ impl<'a> Parser<'a> {
// `suppress_array_join_checks` skips them when this SELECT
// is a subquery inside a discarded `FILTER (WHERE …)` body
// (see `parse_optional_filter`).
- if !self.suppress_array_join_checks && !obj.contains_key("select_from") {
+ if !self.suppress_array_join_checks && !self.emit.has_field(&obj, "select_from") {
return Err(ParseError::syntax(
"Using ARRAY JOIN without a FROM clause is not permitted",
0,
@@ -512,10 +498,11 @@ impl<'a> Parser<'a> {
Some("INNER") => "INNER ARRAY JOIN",
_ => "ARRAY JOIN",
};
- obj.insert("array_join_op".into(), Value::String(op.into()));
+ self.emit
+ .set_field(&mut obj, "array_join_op", self.emit.string(op));
// Inline expr-list parsing so we can capture each item's span
// for the alias-required error.
- let mut exprs: Vec<Value> = Vec::new();
+ let mut exprs: Vec<E::Value> = Vec::new();
loop {
let item_start = self.peek0.start;
let expr = self.parse_expr_bp(0)?;
@@ -525,12 +512,12 @@ impl<'a> Parser<'a> {
let item_end = self.last_consumed_end;
// Implicit alias: `[…] alias` without AS.
let aliased = if let Some(name) = self.try_consume_implicit_alias()? {
- emit::alias(expr, &name)
+ self.emit.alias(expr, &name)
} else {
expr
};
if !self.suppress_array_join_checks
- && aliased.get("node").and_then(|v| v.as_str()) != Some("Alias")
+ && self.emit.node_kind(&aliased).as_deref() != Some("Alias")
{
return Err(ParseError::syntax(
"ARRAY JOIN arrays must have an alias",
@@ -551,13 +538,16 @@ impl<'a> Parser<'a> {
break;
}
}
- obj.insert("array_join_list".into(), Value::Array(exprs));
+ self.emit
+ .set_field(&mut obj, "array_join_list", self.emit.list_value(exprs));
}
if self.eat_kw(Kw::Prewhere)? {
- obj.insert("prewhere".into(), self.parse_expr_bp(0)?);
+ let _v = self.parse_expr_bp(0)?;
+ self.emit.set_field(&mut obj, "prewhere", _v);
}
if self.eat_kw(Kw::Where)? {
- obj.insert("where".into(), self.parse_expr_bp(0)?);
+ let _v = self.parse_expr_bp(0)?;
+ self.emit.set_field(&mut obj, "where", _v);
}
// `(USING? SAMPLE …)?` — the grammar allows a SAMPLE clause at
// SELECT level (before GROUP BY *and* after QUALIFY). Both
@@ -579,7 +569,8 @@ impl<'a> Parser<'a> {
// ALL(*) falls back to `columnExprList` with ALL as a
// plain Field.
self.bump()?;
- obj.insert("group_by_mode".into(), Value::String("all".into()));
+ self.emit
+ .set_field(&mut obj, "group_by_mode", self.emit.string("all"));
} else if matches!(self.peek(), TokenKind::Keyword(Kw::Cube | Kw::Rollup))
&& self.peek_next() == TokenKind::LParen
&& !self.peek_lparen_is_empty()
@@ -594,8 +585,10 @@ impl<'a> Parser<'a> {
self.expect(TokenKind::LParen, "(")?;
let exprs = self.parse_expr_list_until_paren()?;
self.expect(TokenKind::RParen, ")")?;
- obj.insert("group_by".into(), Value::Array(exprs));
- obj.insert("group_by_mode".into(), Value::String(kw.into()));
+ self.emit
+ .set_field(&mut obj, "group_by", self.emit.list_value(exprs));
+ self.emit
+ .set_field(&mut obj, "group_by_mode", self.emit.string(kw));
} else if matches!(self.peek(), TokenKind::Keyword(Kw::Grouping))
&& self.peek_next() == TokenKind::Keyword(Kw::Sets)
{
@@ -607,7 +600,7 @@ impl<'a> Parser<'a> {
// the Python AST can hold them in `group_by: list[Expr]`.
// The cpp ctx for `groupingSet` is `LPAREN columnExprList? RPAREN`
// so the position spans the parens themselves.
- let mut sets: Vec<Value> = Vec::new();
+ let mut sets: Vec<E::Value> = Vec::new();
loop {
let set_start = self.peek0.start;
self.expect(TokenKind::LParen, "(")?;
@@ -619,26 +612,20 @@ impl<'a> Parser<'a> {
self.expect(TokenKind::RParen, ")")?;
exprs
};
- sets.push(self.wrap_pos(
- serde_json::json!({
- "node": "GroupingSet",
- "exprs": exprs,
- }),
- set_start,
- ));
+ sets.push(self.wrap_pos(self.emit.grouping_set(exprs), set_start));
if !self.eat(TokenKind::Comma)? {
break;
}
}
self.expect(TokenKind::RParen, ")")?;
- obj.insert("group_by".into(), Value::Array(sets));
- obj.insert(
- "group_by_mode".into(),
- Value::String("grouping_sets".into()),
- );
+ self.emit
+ .set_field(&mut obj, "group_by", self.emit.list_value(sets));
+ self.emit
+ .set_field(&mut obj, "group_by_mode", self.emit.string("grouping_sets"));
} else {
let exprs = self.parse_expr_list_until_terminators()?;
- obj.insert("group_by".into(), Value::Array(exprs));
+ self.emit
+ .set_field(&mut obj, "group_by", self.emit.list_value(exprs));
}
}
// `WITH (CUBE | ROLLUP | TOTALS)` after the GROUP BY position —
@@ -679,17 +666,20 @@ impl<'a> Parser<'a> {
}
}
if self.eat_kw(Kw::Having)? {
- obj.insert("having".into(), self.parse_expr_bp(0)?);
+ let _v = self.parse_expr_bp(0)?;
+ self.emit.set_field(&mut obj, "having", _v);
}
if self.eat_kw(Kw::Qualify)? {
- obj.insert("qualify".into(), self.parse_expr_bp(0)?);
+ let _v = self.parse_expr_bp(0)?;
+ self.emit.set_field(&mut obj, "qualify", _v);
}
// Second `USING SAMPLE` opportunity per the grammar (after
// QUALIFY, before WINDOW). Same attach-to-FROM-table logic.
self.try_attach_select_level_sample(&mut obj)?;
// WINDOW clause — minimal: WINDOW name AS (...) [, ...].
if self.eat_kw(Kw::Window)? {
- let mut windows = serde_json::Map::new();
+ let mut windows: std::collections::BTreeMap<String, E::Value> =
+ std::collections::BTreeMap::new();
loop {
let name_tok = self.bump()?;
let name = match name_tok.kind {
@@ -711,21 +701,25 @@ impl<'a> Parser<'a> {
break;
}
}
- obj.insert("window_exprs".into(), Value::Object(windows));
+ let windows_pairs: Vec<(String, E::Value)> = windows.into_iter().collect();
+ self.emit.set_field(
+ &mut obj,
+ "window_exprs",
+ self.emit.string_keyed_map(windows_pairs),
+ );
}
if matches!(self.peek(), TokenKind::Keyword(Kw::Order))
&& self.peek_next() == TokenKind::Keyword(Kw::By)
{
self.bump()?;
self.bump()?;
- obj.insert(
- "order_by".into(),
- Value::Array(self.parse_order_expr_list()?),
- );
+ let ob = self.parse_order_expr_list()?;
+ self.emit
+ .set_field(&mut obj, "order_by", self.emit.list_value(ob));
// Optional `INTERPOLATE [(expr [AS expr], …)]` after ORDER BY.
if self.eat_kw(Kw::Interpolate)? {
let items = if self.eat(TokenKind::LParen)? {
- let mut items: Vec<Value> = Vec::new();
+ let mut items: Vec<E::Value> = Vec::new();
// `interpolateClause: INTERPOLATE (LPAREN interpolateExpr
// (COMMA interpolateExpr)* RPAREN)?` — when parens are
// present, at least one interpolateExpr is required.
@@ -747,13 +741,8 @@ impl<'a> Parser<'a> {
} else {
None
};
- let mut interp = serde_json::Map::new();
- interp.insert("node".into(), Value::String("InterpolateExpr".into()));
- interp.insert("expr".into(), expr);
- if let Some(v) = value {
- interp.insert("value".into(), v);
- }
- items.push(Value::Object(interp));
+ let interp = self.emit.interpolate_expr(expr, value);
+ items.push(interp);
if !self.eat(TokenKind::Comma)? {
break;
}
@@ -770,7 +759,8 @@ impl<'a> Parser<'a> {
} else {
Vec::new()
};
- obj.insert("interpolate".into(), Value::Array(items));
+ self.emit
+ .set_field(&mut obj, "interpolate", self.emit.list_value(items));
}
}
// LIMIT / LIMIT BY / OFFSET handling. The grammar allows both
@@ -791,7 +781,7 @@ impl<'a> Parser<'a> {
));
}
- Ok(self.wrap_pos(Value::Object(obj), stmt_start))
+ Ok(self.wrap_pos(obj, stmt_start))
}
/// Probe: at the GROUP BY position, peek is `ALL`. The peek_next
@@ -851,7 +841,7 @@ impl<'a> Parser<'a> {
/// `(body, percent)`. Callers raise `limit_body_depth` around this
/// so the Pratt `%` handler can resolve modulo vs the PERCENT
/// marker at any depth.
- fn parse_limit_body(&mut self) -> Result<(Value, bool), ParseError> {
+ fn parse_limit_body(&mut self) -> Result<(E::Value, bool), ParseError> {
// BP_MULT+1 stops the initial parse before a top-level `%` so
// `limit_resolve_percent` sees it undigested; a compound body
// (additive / comparison / AND / OR) is then extended at BP=0.
@@ -883,10 +873,7 @@ impl<'a> Parser<'a> {
/// anything else means regular limit-and-offset. `%` (PERCENT) and
/// `WITH TIES` rule out limit-by mid-parse — they are only valid in the
/// limit-and-offset form.
- fn parse_limit_clauses(
- &mut self,
- obj: &mut serde_json::Map<String, Value>,
- ) -> Result<(), ParseError> {
+ fn parse_limit_clauses(&mut self, obj: &mut E::Value) -> Result<(), ParseError> {
// Capture the LIMIT keyword's start so the eventual LimitByExpr
// (cpp's `limitByClause` ctx, `LIMIT limitExpr BY columnExprList`)
// gets a span starting at LIMIT, not at the first BY-expr.
@@ -894,7 +881,8 @@ impl<'a> Parser<'a> {
if !self.eat_kw(Kw::Limit)? {
// No LIMIT — accept a standalone OFFSET clause (offsetOnlyClause).
if self.eat_kw(Kw::Offset)? {
- obj.insert("offset".into(), self.parse_expr_bp(0)?);
+ let _v = self.parse_expr_bp(0)?;
+ self.emit.set_field(obj, "offset", _v);
}
return Ok(());
}
@@ -927,10 +915,10 @@ impl<'a> Parser<'a> {
// limit-and-offset; we capture which separator was used and decide
// later. Both operands parse at full bp (no `%` ambiguity here —
// PERCENT only attaches to the first LIMIT operand).
- enum Tail {
+ enum Tail<V> {
None,
- Comma(Value),
- Offset(Value),
+ Comma(V),
+ Offset(V),
}
let tail = if self.eat(TokenKind::Comma)? {
Tail::Comma(self.parse_expr_bp(0)?)
@@ -987,17 +975,9 @@ impl<'a> Parser<'a> {
// `LIMIT a OFFSET b BY ...` → n=a, offset_value=b
Tail::Offset(s) => (first, Some(s)),
};
- let mut lb = serde_json::Map::new();
- lb.insert("node".into(), Value::String("LimitByExpr".into()));
- lb.insert("n".into(), n);
- lb.insert("exprs".into(), Value::Array(cols));
- if let Some(o) = offset_value {
- lb.insert("offset_value".into(), o);
- }
- obj.insert(
- "limit_by".into(),
- self.wrap_pos(Value::Object(lb), limit_start),
- );
+ let lb = self.emit.limit_by_expr(n, cols, offset_value);
+ self.emit
+ .set_field(obj, "limit_by", self.wrap_pos(lb, limit_start));
// After the limit-by clause, an optional outer
// limit-and-offset (or bare OFFSET) may follow.
@@ -1009,22 +989,25 @@ impl<'a> Parser<'a> {
// form (Tail::Offset) is liftable to the outer SelectSetQuery
// when wrapped in a set-stmt; the compact `, m` form is not.
// See `parse_select_set_stmt` for the lift logic.
- obj.insert("limit".into(), first);
+ self.emit.set_field(obj, "limit", first);
if percent {
- obj.insert("limit_percent".into(), Value::Bool(true));
+ self.emit
+ .set_field(obj, "limit_percent", self.emit.bool(true));
}
match tail {
Tail::Comma(s) => {
- obj.insert("offset".into(), s);
+ self.emit.set_field(obj, "offset", s);
}
Tail::Offset(s) => {
- obj.insert("offset".into(), s);
- obj.insert("__rust_offset_liftable".into(), Value::Bool(true));
+ self.emit.set_field(obj, "offset", s);
+ self.emit
+ .set_field(obj, "__rust_offset_liftable", self.emit.bool(true));
}
Tail::None => {}
}
if with_ties {
- obj.insert("limit_with_ties".into(), Value::Bool(true));
+ self.emit
+ .set_field(obj, "limit_with_ties", self.emit.bool(true));
}
Ok(())
}
@@ -1032,10 +1015,7 @@ impl<'a> Parser<'a> {
/// Outer limit/offset that may follow a `LIMIT BY` clause. Same
/// grammar as `limitAndOffsetClause | offsetOnlyClause`, but `BY` is
/// not legal here.
- fn parse_trailing_limit_and_offset(
- &mut self,
- obj: &mut serde_json::Map<String, Value>,
- ) -> Result<(), ParseError> {
+ fn parse_trailing_limit_and_offset(&mut self, obj: &mut E::Value) -> Result<(), ParseError> {
if self.eat_kw(Kw::Limit)? {
// Full `columnExpr` body — `parse_limit_body` covers the
// compound case (`limit (x) ?? y`) and the `%`/PERCENT
@@ -1045,9 +1025,10 @@ impl<'a> Parser<'a> {
let body = self.parse_limit_body();
self.limit_body_depth -= 1;
let (limit, percent) = body?;
- obj.insert("limit".into(), limit);
+ self.emit.set_field(obj, "limit", limit);
if percent {
- obj.insert("limit_percent".into(), Value::Bool(true));
+ self.emit
+ .set_field(obj, "limit_percent", self.emit.bool(true));
}
// Grammar (line 107–110): limitAndOffsetClause has two
// alternatives that differ in where WITH TIES sits relative
@@ -1066,31 +1047,37 @@ impl<'a> Parser<'a> {
// OFFSET branch.
if self.eat(TokenKind::Comma)? {
// Compact form.
- obj.insert("offset".into(), self.parse_expr_bp(0)?);
+ let _v = self.parse_expr_bp(0)?;
+ self.emit.set_field(obj, "offset", _v);
if self.peek_kw2(Kw::With, Kw::Ties) {
self.bump()?;
self.bump()?;
- obj.insert("limit_with_ties".into(), Value::Bool(true));
+ self.emit
+ .set_field(obj, "limit_with_ties", self.emit.bool(true));
}
} else {
// Verbose form (or no second operand).
if self.peek_kw2(Kw::With, Kw::Ties) {
self.bump()?;
self.bump()?;
- obj.insert("limit_with_ties".into(), Value::Bool(true));
+ self.emit
+ .set_field(obj, "limit_with_ties", self.emit.bool(true));
}
if self.eat_kw(Kw::Offset)? {
- obj.insert("offset".into(), self.parse_expr_bp(0)?);
+ let _v = self.parse_expr_bp(0)?;
+ self.emit.set_field(obj, "offset", _v);
// Sentinel for the SelectSetStmt wrapper's
// conditional lift logic — only the verbose form
// is liftable.
- obj.insert("__rust_offset_liftable".into(), Value::Bool(true));
+ self.emit
+ .set_field(obj, "__rust_offset_liftable", self.emit.bool(true));
}
}
} else if self.eat_kw(Kw::Offset)? {
// Bare `OFFSET m` (no preceding LIMIT). cpp keeps this on
// the inner SELECT — don't mark liftable.
- obj.insert("offset".into(), self.parse_expr_bp(0)?);
+ let _v = self.parse_expr_bp(0)?;
+ self.emit.set_field(obj, "offset", _v);
}
Ok(())
}
@@ -1111,9 +1098,9 @@ impl<'a> Parser<'a> {
/// continuation), otherwise `%` is the PERCENT marker.
fn limit_resolve_percent(
&mut self,
- expr: Value,
+ expr: E::Value,
expr_start: usize,
- ) -> Result<(Value, bool), ParseError> {
+ ) -> Result<(E::Value, bool), ParseError> {
if self.peek0.kind != TokenKind::Percent {
return Ok((expr, false));
}
@@ -1144,14 +1131,14 @@ impl<'a> Parser<'a> {
/// LIMIT body (`limit_body_depth > 0`).
pub(crate) fn try_limit_modulo_extension(
&mut self,
- lhs: Value,
+ lhs: E::Value,
lhs_start: usize,
- ) -> Result<Option<Value>, ParseError> {
+ ) -> Result<Option<E::Value>, ParseError> {
let cp = self.checkpoint();
- let trial = (|p: &mut Self| -> Result<Option<Value>, ParseError> {
+ let trial = (|p: &mut Self| -> Result<Option<E::Value>, ParseError> {
p.bump()?; // %
let rhs = p.parse_expr_bp(BP_MULT + 1)?;
- let combined = emit::arith(lhs.clone(), "%", rhs);
+ let combined = p.emit.arith(lhs.clone(), "%", rhs);
// Extend the whole columnExpr (BP=0) — cpp parses the
// LIMIT body greedily, so a lower-precedence tail
// (`% 2 + 3`, `% 2 AND 3`) stays part of the modulo body.
@@ -1289,10 +1276,7 @@ impl<'a> Parser<'a> {
/// building the JoinExpr) ends up on `JoinExpr.sample`. We mirror
/// the silent-drop behaviour here so the parser accepts the syntax
/// without diverging from cpp.
- fn try_attach_select_level_sample(
- &mut self,
- _obj: &mut serde_json::Map<String, Value>,
- ) -> Result<(), ParseError> {
+ fn try_attach_select_level_sample(&mut self, _obj: &mut E::Value) -> Result<(), ParseError> {
let saw_sample = if self.peek_kw2(Kw::Using, Kw::Sample) {
self.bump()?; // USING
true
@@ -1334,7 +1318,7 @@ impl<'a> Parser<'a> {
/// continues the list, but the probe returns false (treating
/// COLUMNS-with-paren as the body of `OFFSET *`). Override OFFSET
/// specifically with a more permissive infix-or-postfix check.
- fn parse_limit_by_exprs(&mut self) -> Result<Vec<Value>, ParseError> {
+ fn parse_limit_by_exprs(&mut self) -> Result<Vec<E::Value>, ParseError> {
let mut out = Vec::new();
out.push(self.parse_expr_bp(0)?);
while self.eat(TokenKind::Comma)? {
@@ -1373,7 +1357,7 @@ impl<'a> Parser<'a> {
// clause instead.
let cp = self.checkpoint();
let speculated = match self.parse_expr_bp(0) {
- Ok(expr) if is_bare_field(&expr) => {
+ Ok(expr) if is_bare_field(&self.emit, &expr) => {
self.restore(cp)?;
None
}
@@ -1404,7 +1388,7 @@ impl<'a> Parser<'a> {
/// appears. Without this RANGE/ROWS would be consumed as Field
/// identifiers (per the keyword rule) and BETWEEN that follows
/// them would over-greedily eat the window frame body.
- fn parse_window_partition_by_exprs(&mut self) -> Result<Vec<Value>, ParseError> {
+ fn parse_window_partition_by_exprs(&mut self) -> Result<Vec<E::Value>, ParseError> {
let mut out = Vec::new();
loop {
out.push(self.parse_expr_bp(0)?);
@@ -1428,10 +1412,9 @@ impl<'a> Parser<'a> {
Ok(out)
}
- pub(crate) fn parse_window_expr(&mut self) -> Result<Value, ParseError> {
+ pub(crate) fn parse_window_expr(&mut self) -> Result<E::Value, ParseError> {
let we_start = self.peek0.start;
- let mut obj = serde_json::Map::new();
- obj.insert("node".into(), Value::String("WindowExpr".into()));
+ let mut obj = self.emit.window_expr_empty();
if matches!(self.peek(), TokenKind::Keyword(Kw::Partition))
&& self.peek_next() == TokenKind::Keyword(Kw::By)
{
@@ -1441,17 +1424,17 @@ impl<'a> Parser<'a> {
// following frame/order keywords (RANGE / ROWS / ORDER) or
// the closing paren of the windowExpr.
let exprs = self.parse_window_partition_by_exprs()?;
- obj.insert("partition_by".into(), Value::Array(exprs));
+ self.emit
+ .set_field(&mut obj, "partition_by", self.emit.list_value(exprs));
}
if matches!(self.peek(), TokenKind::Keyword(Kw::Order))
&& self.peek_next() == TokenKind::Keyword(Kw::By)
{
self.bump()?;
self.bump()?;
- obj.insert(
- "order_by".into(),
- Value::Array(self.parse_order_expr_list()?),
- );
+ let ob = self.parse_order_expr_list()?;
+ self.emit
+ .set_field(&mut obj, "order_by", self.emit.list_value(ob));
}
// Frame clause: ROWS|RANGE bound [BETWEEN bound AND bound].
let frame_method = if self.eat_kw(Kw::Rows)? {
@@ -1462,7 +1445,8 @@ impl<'a> Parser<'a> {
None
};
if let Some(m) = frame_method {
- obj.insert("frame_method".into(), Value::String(m.into()));
+ self.emit
+ .set_field(&mut obj, "frame_method", self.emit.string(m));
// `BETWEEN` after ROWS / RANGE is ambiguous: the
// `frameBetween` alt (`BETWEEN bound AND bound`) or a
// `frameStart` bound whose `columnExpr` is the `between`
@@ -1473,7 +1457,7 @@ impl<'a> Parser<'a> {
// re-read as the Field of a `frameStart` bound.
let cp = self.checkpoint();
let between_frame = if self.eat_kw(Kw::Between)? {
- (|p: &mut Self| -> Result<(Value, Value), ParseError> {
+ (|p: &mut Self| -> Result<(E::Value, E::Value), ParseError> {
let start = p.parse_window_frame_bound()?;
p.expect_kw(Kw::And, "AND")?;
let end = p.parse_window_frame_bound()?;
@@ -1484,26 +1468,27 @@ impl<'a> Parser<'a> {
None
};
if let Some((start, end)) = between_frame {
- obj.insert("frame_start".into(), start);
- obj.insert("frame_end".into(), end);
+ self.emit.set_field(&mut obj, "frame_start", start);
+ self.emit.set_field(&mut obj, "frame_end", end);
} else {
self.restore(cp)?;
let start = self.parse_window_frame_bound()?;
- obj.insert("frame_start".into(), start);
+ self.emit.set_field(&mut obj, "frame_start", start);
}
}
// cpp's `VISIT(WindowExpr)` calls `addPositionInfo(json, ctx)`,
// so the JSON has `start` / `end` spanning the window-expr body
// (between the parens — `OVER ( PARTITION BY ... ROWS ... )`).
- Ok(self.wrap_pos(Value::Object(obj), we_start))
+ Ok(self.wrap_pos(obj, we_start))
}
- fn parse_window_frame_bound(&mut self) -> Result<Value, ParseError> {
+ fn parse_window_frame_bound(&mut self) -> Result<E::Value, ParseError> {
let bound_start = self.peek0.start;
if self.eat_kw(Kw::Current)? {
self.expect_kw(Kw::Row, "ROW")?;
+ let null_val = self.emit.null();
return Ok(self.wrap_pos(
- json!({"node": "WindowFrameExpr", "frame_type": "CURRENT ROW", "frame_value": Value::Null}),
+ self.emit.window_frame_bound("CURRENT ROW", null_val),
bound_start,
));
}
@@ -1515,10 +1500,8 @@ impl<'a> Parser<'a> {
} else {
return Err(self.err("expected PRECEDING or FOLLOWING after UNBOUNDED"));
};
- return Ok(self.wrap_pos(
- json!({"node": "WindowFrameExpr", "frame_type": ty, "frame_value": Value::Null}),
- bound_start,
- ));
+ let null_val = self.emit.null();
+ return Ok(self.wrap_pos(self.emit.window_frame_bound(ty, null_val), bound_start));
}
// `winFrameBound: columnExpr PRECEDING | columnExpr FOLLOWING`
// — the value is a full `columnExpr`, so parse it at binding
@@ -1538,26 +1521,22 @@ impl<'a> Parser<'a> {
// to a bare number only when the value `isInt()`; a float or
// string Constant keeps its full object form. Mirror that —
// unwrap only an integer-valued Constant.
- let frame_value = match val.as_object() {
- Some(obj)
- if obj.get("node").and_then(Value::as_str) == Some("Constant")
- && obj.get("value").is_some_and(Value::is_i64) =>
- {
- obj.get("value").cloned().unwrap_or(Value::Null)
+ let frame_value = if self.emit.node_kind(&val).as_deref() == Some("Constant") {
+ match self.emit.get_field(&val, "value") {
+ Some(v) if self.emit.as_i64(&v).is_some() => v,
+ _ => val,
}
- _ => val,
+ } else {
+ val
};
- Ok(self.wrap_pos(
- json!({"node": "WindowFrameExpr", "frame_type": ty, "frame_value": frame_value}),
- bound_start,
- ))
+ Ok(self.wrap_pos(self.emit.window_frame_bound(ty, frame_value), bound_start))
}
- fn parse_select_columns(&mut self) -> Result<Vec<Value>, ParseError> {
+ fn parse_select_columns(&mut self) -> Result<Vec<E::Value>, ParseError> {
// `selectColumnExprList` with optional trailing comma. Each item is
// either `IDENT COLON expr` (alias-before), `expr [implicitAlias]`,
// or `expr AS alias` (`AS` already handled by Pratt as an infix).
- let mut cols: Vec<Value> = Vec::new();
+ let mut cols: Vec<E::Value> = Vec::new();
loop {
if matches!(
self.peek(),
@@ -1613,7 +1592,7 @@ impl<'a> Parser<'a> {
// (`IDENT COLON columnExpr`) spans from the alias ident
// through the value expression. Wrap so the column's
// `start` / `end` match cpp's `addPositionInfo`.
- cols.push(self.wrap_pos(emit::alias(expr, &name), col_start));
+ cols.push(self.wrap_pos(self.emit.alias(expr, &name), col_start));
} else {
let expr = self.parse_expr_bp(0)?;
// Implicit alias: a trailing identifier (or one of the
@@ -1627,7 +1606,7 @@ impl<'a> Parser<'a> {
// deliberate footgun-catcher — cpp's visitor rejects
// it. (`from AS x` is fine; the `AS` form folds into
// the expr above and never reaches here.)
- if is_bare_from_field(&expr) {
+ if is_bare_from_field(&self.emit, &expr) {
return Err(self.err("Cannot use \"from\" before an implicit alias"));
}
// cpp's `ColumnExprAlias` ctx for the implicit-alias
@@ -1635,7 +1614,7 @@ impl<'a> Parser<'a> {
// expression through the alias identifier — wrap
// with the column's running start so the Alias
// carries the cpp span.
- self.wrap_pos(emit::alias(expr, &name), col_start)
+ self.wrap_pos(self.emit.alias(expr, &name), col_start)
} else {
expr
};
@@ -1674,18 +1653,15 @@ impl<'a> Parser<'a> {
/// True when `expr` is a bare `from` Field — a `Field` whose chain is
/// the single element `from` (any case). Used to flag the grammar's
/// `ColumnExprInvalidFromImplicitAlias` footgun (`select from x`).
-fn is_bare_from_field(expr: &Value) -> bool {
- let Some(obj) = expr.as_object() else {
- return false;
- };
- if obj.get("node").and_then(Value::as_str) != Some("Field") {
+fn is_bare_from_field<E: Emitter>(emit: &E, expr: &E::Value) -> bool {
+ if emit.node_kind(expr).as_deref() != Some("Field") {
return false;
}
- match obj.get("chain").and_then(Value::as_array) {
+ match emit.get_field(expr, "chain").and_then(|c| emit.as_list(&c)) {
Some(chain) => {
chain.len() == 1
- && chain[0]
- .as_str()
+ && emit
+ .as_str(&chain[0])
.is_some_and(|s| s.eq_ignore_ascii_case("from"))
}
None => false,
diff --git a/rust/hogql/parser/src/parse/template.rs b/rust/hogql/parser/src/parse/template.rs
index c47a23d02b75..2214a20ae887 100644
--- a/rust/hogql/parser/src/parse/template.rs
+++ b/rust/hogql/parser/src/parse/template.rs
@@ -6,10 +6,8 @@
//! to the byte after `{`, then advance past the closing `}` it stopped
//! on.
-use serde_json::Value;
-
use super::Parser;
-use crate::emit;
+use crate::emit::Emitter;
use crate::error::ParseError;
use crate::lex::{Lexer, TokenKind};
@@ -33,57 +31,108 @@ use crate::lex::{Lexer, TokenKind};
/// `\X`, and starts a fresh token, so the body splitter does the same:
/// it closes the current literal chunk and opens a new one (an extra
/// `concat` argument).
-pub(super) fn parse_template_body(
+pub(super) fn parse_template_body<E: Emitter + Clone>(
+ emit: &E,
full_src: &str,
body_offset: usize,
body_end: usize,
-) -> Result<Value, ParseError> {
+) -> Result<E::Value, ParseError> {
let body = &full_src[body_offset..body_end];
let bytes = body.as_bytes();
// (start_in_body, end_in_body, value) — absolute positions wrap on
// each push so callers receive cpp-shaped `start` / `end` spans.
- let mut chunks: Vec<Value> = Vec::new();
+ let mut chunks: Vec<E::Value> = Vec::new();
let mut literal = String::new();
let mut literal_start = 0; // byte offset within `body` where the current literal began
let mut i = 0;
while i < bytes.len() {
let c = bytes[i];
+ // `\` always introduces an escape: cpp's `STRING_TEXT` lexer
+ // sweeps over `ESCAPE_CHAR_COMMON`, then `parse_string_text_ctx`
+ // decodes recognised ones and drops the byte for unrecognised
+ // ones. We do both in one pass.
if c == b'\\' && i + 1 < bytes.len() {
let next = bytes[i + 1];
- // Escapes the f-string `STRING_TEXT` lexer rule admits
- // (`BACKSLASH LBRACE` / `BACKSLASH QUOTE_SINGLE` /
- // `ESCAPE_CHAR_COMMON`) stay inside the current literal
- // chunk; their decoded value follows the cpp
- // `parse_string_text_ctx` + `replace_common_escape_characters`
- // pair — note `\0` is dropped (NUL ignored) and `\xHH` is
- // left verbatim (the cpp escape map has no `\x` case).
match next {
- b'{' => literal.push('{'),
- b'\'' => literal.push('\''),
- b'\\' => literal.push('\\'),
- b'n' => literal.push('\n'),
- b't' => literal.push('\t'),
- b'r' => literal.push('\r'),
- b'b' => literal.push('\u{08}'),
- b'f' => literal.push('\u{0C}'),
- b'a' => literal.push('\u{07}'),
- b'v' => literal.push('\u{0B}'),
- b'0' => { /* NUL is ignored, contributing nothing */ }
- b'x' if i + 4 <= bytes.len()
- && bytes[i + 2].is_ascii_hexdigit()
- && bytes[i + 3].is_ascii_hexdigit() =>
- {
- literal.push_str(&body[i..i + 4]);
- i += 4;
+ b'{' => {
+ literal.push('{');
+ i += 2;
+ continue;
+ }
+ b'}' => {
+ literal.push('}');
+ i += 2;
+ continue;
+ }
+ b'\'' => {
+ literal.push('\'');
+ i += 2;
+ continue;
+ }
+ b'\\' => {
+ literal.push('\\');
+ i += 2;
+ continue;
+ }
+ b'n' => {
+ literal.push('\n');
+ i += 2;
+ continue;
+ }
+ b't' => {
+ literal.push('\t');
+ i += 2;
+ continue;
+ }
+ b'r' => {
+ literal.push('\r');
+ i += 2;
+ continue;
+ }
+ b'b' => {
+ literal.push('\u{08}');
+ i += 2;
+ continue;
+ }
+ b'f' => {
+ literal.push('\u{0C}');
+ i += 2;
+ continue;
+ }
+ b'a' => {
+ literal.push('\u{07}');
+ i += 2;
+ continue;
+ }
+ b'v' => {
+ literal.push('\u{0B}');
+ i += 2;
+ continue;
+ }
+ b'0' => {
+ // cpp's `parse_string_text_ctx` drops `\0` (NUL is
+ // not emitted, contributing nothing to the output).
+ i += 2;
+ continue;
+ }
+ b'x' => {
+ // cpp keeps `\xHH` verbatim as `\xHH` — the lexer
+ // doesn't decode it, and `parse_string_text_ctx`
+ // copies the backslash + the 'x' + the two hex
+ // digits literally.
+ literal.push('\\');
+ i += 1;
continue;
}
_ => {
- // An escape the lexer rule cannot span: cpp's
- // `STRING_TEXT` token ends here, the offending
- // `\X` is dropped by lexer error recovery, and a
- // fresh `STRING_TEXT` (a new concat chunk) begins.
+ // Unknown `\X` — cpp ends the current `STRING_TEXT`
+ // token at the `\`, then starts a fresh token on
+ // the next valid character. The body splitter
+ // models that by closing the current literal chunk
+ // and dropping the two-byte `\X` sequence.
if !literal.is_empty() {
chunks.push(wrap_literal_chunk(
+ emit,
full_src,
std::mem::take(&mut literal),
body_offset + literal_start,
@@ -95,28 +144,29 @@ pub(super) fn parse_template_body(
continue;
}
}
- i += 2;
- continue;
}
if c == b'{' {
if !literal.is_empty() {
chunks.push(wrap_literal_chunk(
+ emit,
full_src,
std::mem::take(&mut literal),
body_offset + literal_start,
body_offset + i,
));
}
- // Locate the matching `}` with a raw-lexer brace scan
- // before sub-parsing. The Lexer consumes string / quoted-
- // identifier / nested-template tokens whole, so a `}`
- // inside a literal is never miscounted. The expression is
- // then sub-parsed from a slice that *ends at* the `}` —
- // this is what keeps the sub-parser's two-token lookahead
- // from lexing on into the literal template text that
- // follows the block. That trailing text is not a valid
- // default-mode token stream (a bare `\` escape, for one),
- // so letting the lookahead reach it spuriously fails the
+ // The body inside `{ … }` is parsed as a `columnExpr`. cpp's
+ // `parse_string_template` lifts the `{ … }` lexer mode into
+ // a sub-`columnExpr` parse — paren-balance via the
+ // sub-lexer so nested `{}` (Hog blocks, dicts) within the
+ // expression don't terminate the substitution. We mirror
+ // that here by lexing through `{`/`}` until the matching
+ // close-brace lands at depth zero.
+ //
+ // Positions stay absolute in `full_src`. cpp's grammar
+ // emits ctx spans relative to the *outer* source — the
+ // visitor doesn't reset them per template chunk — so the
+ // sub-parser's nodes share an `offset` space with the
// whole template.
//
// Scan via the FULL source so the lexer's positions are
@@ -152,7 +202,11 @@ pub(super) fn parse_template_body(
// `full_src` keeps the absolute offsets up to that point —
// a Parser::with_pos started at `abs_brace_start + 1`
// emits absolute positions in `full_src`.
- let mut sub = Parser::with_pos(&full_src[..close_brace_start], abs_brace_start + 1)?;
+ let mut sub = Parser::<'_, E>::with_pos_emit(
+ &full_src[..close_brace_start],
+ abs_brace_start + 1,
+ emit.clone(),
+ )?;
let expr = sub.parse_expr_bp(0)?;
if !matches!(sub.peek(), TokenKind::Eof) {
return Err(ParseError::syntax(
@@ -180,6 +234,7 @@ pub(super) fn parse_template_body(
}
if !literal.is_empty() {
chunks.push(wrap_literal_chunk(
+ emit,
full_src,
literal,
body_offset + literal_start,
@@ -190,6 +245,7 @@ pub(super) fn parse_template_body(
// Empty body — cpp emits an empty-string Constant spanning the
// body (between the quotes). Position it accordingly.
return Ok(wrap_literal_chunk(
+ emit,
full_src,
String::new(),
body_offset,
@@ -205,7 +261,7 @@ pub(super) fn parse_template_body(
// The outer concat Call wraps the chunks. Its position spans the
// whole template body — the caller adds the outer wrap based on
// the `f'…'` token bounds via the standard pratt-loop wrap.
- Ok(emit::call("concat", chunks))
+ Ok(emit.call("concat", chunks))
}
/// Wrap a literal-chunk Constant with the cpp `STRING_TEXT` ctx span.
@@ -214,18 +270,24 @@ pub(super) fn parse_template_body(
/// envelope without spinning up a fresh `Parser` (which would try to
/// lex the rest of the source starting from `start`, and inside an
/// `f'…'` body that lex would fail on the trailing unclosed `'`).
-fn wrap_literal_chunk(full_src: &str, value: String, start: usize, end: usize) -> Value {
- let constant = emit::constant(Value::String(value));
- let start_pos = pos_in_source(full_src, start);
- let end_pos = pos_in_source(full_src, end);
- emit::with_pos(constant, start_pos, end_pos)
+fn wrap_literal_chunk<E: Emitter>(
+ emit: &E,
+ full_src: &str,
+ value: String,
+ start: usize,
+ end: usize,
+) -> E::Value {
+ let constant = emit.constant(emit.string(&value));
+ let start_pos = pos_in_source(emit, full_src, start);
+ let end_pos = pos_in_source(emit, full_src, end);
+ emit.with_pos(constant, start_pos, end_pos)
}
/// Compute the cpp-shape `{line, column, offset}` envelope for an
/// absolute byte offset in `src`. `offset` is the character index
/// (Unicode code points), matching cpp's ANTLR `getStartIndex()`
/// semantics; `column` is character-position-in-line.
-fn pos_in_source(src: &str, byte_offset: usize) -> Value {
+fn pos_in_source<E: Emitter>(emit: &E, src: &str, byte_offset: usize) -> E::Value {
// Line: count `\n` bytes before `byte_offset`.
let preceding = &src[..byte_offset.min(src.len())];
let line_breaks = preceding.bytes().filter(|&b| b == b'\n').count();
@@ -238,5 +300,5 @@ fn pos_in_source(src: &str, byte_offset: usize) -> Value {
} else {
preceding.chars().count()
};
- emit::position(line, column, char_offset)
+ emit.position(line, column, char_offset)
}
diff --git a/rust/hogql/parser/src/pyobject.rs b/rust/hogql/parser/src/pyobject.rs
new file mode 100644
index 000000000000..3052e49837b1
--- /dev/null
+++ b/rust/hogql/parser/src/pyobject.rs
@@ -0,0 +1,256 @@
+//! Convert a parser-built `serde_json::Value` AST into `posthog.hogql.ast` dataclass instances directly, skipping the JSON-string serialise step on the Rust side AND the orjson + `_deserialize_node` walk on the Python side. Mirrors [`posthog/hogql/json_ast.py`].
+//!
+//! Used by the `parse_*_py` PyO3 entry points in [`crate::lib`]. The `parse_*_json` entry points stay alongside for callers that need the string form (tests, future WASM build that can't link to CPython).
+//!
+//! Strategy: walk the existing `Value` tree once and construct Python objects via PyO3. The intermediate `Value` is still built by the parser; a later iteration that emits Python objects directly during parsing would skip that too, but the value→PyObject converter proves out the integration first and lets us measure the JSON-elimination win on its own.
+
+use pyo3::exceptions::PyValueError;
+use pyo3::prelude::*;
+use pyo3::types::{PyDict, PyList, PyTuple};
+use serde_json::Value;
+
+/// Cached refs: AST module, two error classes, two StrEnum types from `_ENUM_FIELDS` in `json_ast.py`, and the `int` builtin for big-int parsing. Built once per call and reused across the walk; cheaper than `import` + `getattr` per node.
+pub struct Converter<'py> {
+ py: Python<'py>,
+ ast_module: Bound<'py, PyModule>,
+ exposed_error: Bound<'py, PyAny>,
+ syntax_error: Bound<'py, PyAny>,
+ arith_op_enum: Bound<'py, PyAny>,
+ compare_op_enum: Bound<'py, PyAny>,
+ /// Python builtin `int` class. Mirrors `PyEmitter::cls_int`; cached so big-int literals don't pay `py.eval_bound("int", ...)` per call.
+ cls_int: Bound<'py, PyAny>,
+}
+
+impl<'py> Converter<'py> {
+ pub fn new(py: Python<'py>) -> PyResult<Self> {
+ let ast_module = py.import_bound("posthog.hogql.ast")?;
+ let errors_module = py.import_bound("posthog.hogql.errors")?;
+ let exposed_error = errors_module.getattr("ExposedHogQLError")?;
+ let syntax_error = errors_module.getattr("SyntaxError")?;
+ let arith_op_enum = ast_module.getattr("ArithmeticOperationOp")?;
+ let compare_op_enum = ast_module.getattr("CompareOperationOp")?;
+ let cls_int = py.import_bound("builtins")?.getattr("int")?;
+ Ok(Self {
+ py,
+ ast_module,
+ exposed_error,
+ syntax_error,
+ arith_op_enum,
+ compare_op_enum,
+ cls_int,
+ })
+ }
+
+ /// Top-level entry: convert the root `Value` to a Python AST instance. Raises `ExposedHogQLError` / `SyntaxError` if the parser returned an error envelope.
+ pub fn convert_root(&self, value: &Value) -> PyResult<PyObject> {
+ self.convert(value)
+ }
+
+ /// Recursive walk. Mirrors `_deserialize_node` in `json_ast.py`.
+ fn convert(&self, value: &Value) -> PyResult<PyObject> {
+ match value {
+ Value::Null => Ok(self.py.None()),
+ Value::Bool(b) => Ok(b.into_py(self.py)),
+ Value::Number(n) => {
+ if let Some(i) = n.as_i64() {
+ Ok(i.into_py(self.py))
+ } else if let Some(u) = n.as_u64() {
+ Ok(u.into_py(self.py))
+ } else if let Some(f) = n.as_f64() {
+ Ok(f.into_py(self.py))
+ } else {
+ Err(PyValueError::new_err(format!("Invalid JSON number: {n}")))
+ }
+ }
+ Value::String(s) => Ok(s.as_str().into_py(self.py)),
+ Value::Array(items) => {
+ let list = PyList::empty_bound(self.py);
+ for item in items {
+ list.append(self.convert(item)?)?;
+ }
+ Ok(list.into())
+ }
+ Value::Object(map) => {
+ // Error envelope per `_deserialize_node`'s `data.get("error") is True` branch.
+ if matches!(map.get("error"), Some(Value::Bool(true))) {
+ return Err(self.build_error(map));
+ }
+
+ let node_type = match map.get("node") {
+ Some(Value::String(s)) => s.as_str(),
+ _ => {
+ return Err(PyValueError::new_err(
+ "Invalid AST node: missing 'node' field",
+ ))
+ }
+ };
+
+ let ast_class = self.ast_module.getattr(node_type).map_err(|_| {
+ PyValueError::new_err(format!("Unknown AST node type: {node_type}"))
+ })?;
+
+ let is_constant = node_type == "Constant";
+ let value_type = if is_constant {
+ map.get("value_type").and_then(Value::as_str)
+ } else {
+ None
+ };
+
+ let kwargs = PyDict::new_bound(self.py);
+ for (key, val) in map.iter() {
+ if key == "node" || key == "value_type" {
+ continue;
+ }
+
+ // Position envelopes `{offset: N}` → offset int.
+ if (key == "start" || key == "end") && val.is_object() {
+ if let Some(offset) = val.get("offset").and_then(Value::as_u64) {
+ kwargs.set_item(key, offset)?;
+ continue;
+ }
+ if let Some(offset) = val.get("offset").and_then(Value::as_i64) {
+ kwargs.set_item(key, offset)?;
+ continue;
+ }
+ }
+
+ // Numeric Constants serialised as strings: non-finite floats (Infinity / NaN) and integer literals wider than int64.
+ if is_constant && key == "value" && value_type == Some("number") {
+ if let Value::String(s) = val {
+ if let Some(f) = parse_special_float(s) {
+ kwargs.set_item(key, f)?;
+ continue;
+ }
+ if let Some(py_int) = self.parse_large_int_literal(s)? {
+ kwargs.set_item(key, py_int)?;
+ continue;
+ }
+ return Err(PyValueError::new_err(format!(
+ "Unknown numeric constant value: {s:?}"
+ )));
+ }
+ }
+
+ // `ctes` may arrive as a list of nodes carrying `name` — fold into a dict keyed by name, preserving order.
+ if key == "ctes" {
+ if let Value::Array(items) = val {
+ let dict = PyDict::new_bound(self.py);
+ for item in items {
+ let name =
+ item.get("name").and_then(Value::as_str).ok_or_else(|| {
+ PyValueError::new_err(
+ "cte entry missing 'name' field for dict folding",
+ )
+ })?;
+ dict.set_item(name, self.convert(item)?)?;
+ }
+ kwargs.set_item(key, dict)?;
+ continue;
+ }
+ }
+
+ // `window_exprs`, `replace`, and `ctes`-as-dict: dict-shaped fields whose values are child nodes.
+ if (key == "window_exprs" || key == "replace" || key == "ctes")
+ && val.is_object()
+ && !val.as_object().is_some_and(|m| m.contains_key("node"))
+ {
+ let map = val.as_object().unwrap();
+ let dict = PyDict::new_bound(self.py);
+ for (k, v) in map.iter() {
+ dict.set_item(k, self.convert(v)?)?;
+ }
+ kwargs.set_item(key, dict)?;
+ continue;
+ }
+
+ let converted = self.convert(val)?;
+
+ // Enum coercion for `ArithmeticOperation.op` and `CompareOperation.op` — both StrEnums; pull the member via `cls[name]`.
+ if let Value::String(s) = val {
+ let enum_cls = match (node_type, key.as_str()) {
+ ("ArithmeticOperation", "op") => Some(&self.arith_op_enum),
+ ("CompareOperation", "op") => Some(&self.compare_op_enum),
+ _ => None,
+ };
+ if let Some(cls) = enum_cls {
+ if let Ok(member) = cls.get_item(s) {
+ kwargs.set_item(key, member)?;
+ continue;
+ }
+ // Fall through to the converted string on KeyError — matches the Python deserializer's `except KeyError: pass`.
+ }
+ }
+
+ kwargs.set_item(key, converted)?;
+ }
+
+ let args = PyTuple::empty_bound(self.py);
+ Ok(ast_class.call(&args, Some(&kwargs))?.unbind())
+ }
+ }
+ }
+
+ /// Build a Python exception object from a parser error envelope `{error: true, type, message, start: {offset}, end: {offset}}` as set by `ParseError::to_json_value` in `error.rs`.
+ fn build_error(&self, map: &serde_json::Map<String, Value>) -> PyErr {
+ let error_type = map
+ .get("type")
+ .and_then(Value::as_str)
+ .unwrap_or("ExposedHogQLError");
+ let message = map
+ .get("message")
+ .and_then(Value::as_str)
+ .unwrap_or("Unknown error");
+ let start = map
+ .get("start")
+ .and_then(|v| v.get("offset"))
+ .and_then(Value::as_u64);
+ let end = map
+ .get("end")
+ .and_then(|v| v.get("offset"))
+ .and_then(Value::as_u64);
+
+ let cls = match error_type {
+ "SyntaxError" => &self.syntax_error,
+ _ => &self.exposed_error,
+ };
+
+ let kwargs = PyDict::new_bound(self.py);
+ if let Err(e) = kwargs.set_item("start", start) {
+ return e;
+ }
+ if let Err(e) = kwargs.set_item("end", end) {
+ return e;
+ }
+ let args = PyTuple::new_bound(self.py, [message]);
+ match cls.call(&args, Some(&kwargs)) {
+ Ok(exc) => PyErr::from_value_bound(exc),
+ Err(e) => e,
+ }
+ }
+
+ /// Build a Python `int` from an integer literal in the lossless-string envelope (decimal or `0x…` hex, optional leading `-`). Rust can't natively represent arbitrary-precision ints, so we hand the raw digits to Python's `int(text, base)` constructor via the cached `cls_int`.
+ fn parse_large_int_literal(&self, value: &str) -> PyResult<Option<PyObject>> {
+ let body = value.strip_prefix('-').unwrap_or(value);
+ let is_hex = body.starts_with("0x") || body.starts_with("0X");
+ let base = if is_hex { 16 } else { 10 };
+ // Validate by trying as Rust i128 first for the common in-range case; fall through to Python `int(...)` for true bignums.
+ let body_no_prefix = if is_hex { &body[2..] } else { body };
+ if !body_no_prefix.chars().all(|c| c.is_ascii_alphanumeric()) {
+ return Ok(None);
+ }
+ let args = PyTuple::new_bound(self.py, [value.into_py(self.py), base.into_py(self.py)]);
+ match self.cls_int.call(&args, None) {
+ Ok(obj) => Ok(Some(obj.unbind())),
+ Err(_) => Ok(None),
+ }
+ }
+}
+
+fn parse_special_float(s: &str) -> Option<f64> {
+ match s {
+ "Infinity" => Some(f64::INFINITY),
+ "-Infinity" => Some(f64::NEG_INFINITY),
+ "NaN" => Some(f64::NAN),
+ _ => None,
+ }
+}
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 1050aa66fd50..a8e36dfe303d 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -1468,6 +1468,8 @@ export namespace Schemas {
CppWithRustShadow: 'cpp_with_rust_shadow',
RustWithCppShadow: 'rust_with_cpp_shadow',
RustOnly: 'rust_only',
+ RustPyOnly: 'rust_py_only',
+ RustPyWithCppShadow: 'rust_py_with_cpp_shadow',
} as const;
export type PersonsArgMaxVersion = typeof PersonsArgMaxVersion[keyof typeof PersonsArgMaxVersion];
@@ -1540,7 +1542,7 @@ export namespace Schemas {
materializedColumnsOptimizationMode?: MaterializedColumnsOptimizationMode | null;
optimizeJoinedFilters?: boolean | null;
optimizeProjections?: boolean | null;
- /** HogQL parser backend; absent → `cpp_only`. `*_shadow` modes return the primary result and sample-compare against the other parser, reporting divergences without failing the request. */
+ /** HogQL parser backend; absent → `cpp_only`. `*_shadow` modes return the primary result and sample-compare against the other parser, reporting divergences without failing the request. The `rust_py_*` modes drive the same hand-rolled Rust parser as `rust_*` but build `posthog.hogql.ast` dataclass instances directly via PyO3, skipping the JSON round-trip. */
parserMode?: ParserMode | null;
personsArgMaxVersion?: PersonsArgMaxVersion | null;
personsJoinMode?: PersonsJoinMode | null;
diff --git a/uv.lock b/uv.lock
index 1572ad903f3c..01069f1f90ba 100644
--- a/uv.lock
+++ b/uv.lock
@@ -11,7 +11,7 @@ resolution-markers = [
]
[options]
-exclude-newer = "2026-05-14T17:05:01.112803428Z"
+exclude-newer = "2026-05-15T14:24:42.622753923Z"
exclude-newer-span = "P7D"
[options.exclude-newer-package]
@@ -3027,16 +3027,16 @@ wheels = [
[[package]]
name = "hogql-parser-rs"
-version = "1.3.69"
+version = "1.3.71"
source = { registry = "https://pypi.org/simple" }
-sdist = { url = "https://files.pythonhosted.org/packages/68/b6/5f0d55d2c32de2e2e3476efdaa4799fbd7ad4af42b47965e0287c2ae6c78/hogql_parser_rs-1.3.69.tar.gz", hash = "sha256:8dc68e902bbb115bd910be114f8dc978a1f80e3db0880de4f807a2e70c72ce33", size = 237540, upload-time = "2026-05-21T17:04:30.835Z" }
+sdist = { url = "https://files.pythonhosted.org/packages/34/03/a1c7dbd1cbfec77b49c9d4b9cb6734d577948a68ab49b7a86d1b6a958192/hogql_parser_rs-1.3.71.tar.gz", hash = "sha256:9761fb1720fb68dd005a0335fe2193466571a5e398cb8e7059ef14bbaa451a55", size = 257342, upload-time = "2026-05-22T14:24:24.232Z" }
wheels = [
- { url = "https://files.pythonhosted.org/packages/c7/ab/9c340d58c66632bd6e521629f673392edb45c6df520c6655536836fe6f16/hogql_parser_rs-1.3.69-cp312-abi3-macosx_10_12_x86_64.whl", hash = "sha256:db160a453cf5c3cc0c69ce03ee2345d3079f077d9f0ee49353e95778a9417ed3", size = 502626, upload-time = "2026-05-21T17:04:20.856Z" },
- { url = "https://files.pythonhosted.org/packages/0b/71/5c808362e83027e8e39c55f31058384a1dcd061ee41fdaa94a1f61394fae/hogql_parser_rs-1.3.69-cp312-abi3-macosx_11_0_arm64.whl", hash = "sha256:9f6614d531efc5787922404da9c025a394f4e987b3b31b861f7dfeb8b4967fac", size = 477612, upload-time = "2026-05-21T17:04:22.544Z" },
- { url = "https://files.pythonhosted.org/packages/26/f3/fa5df3157cfbe0289f4cba46db707d3d05e12691062525bf0b0effeeb537/hogql_parser_rs-1.3.69-cp312-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:ac6401570c3945c6c450484aabf5cec73c60993460cf06a5157ff5d27cef8974", size = 1928571, upload-time = "2026-05-21T17:04:23.897Z" },
- { url = "https://files.pythonhosted.org/packages/ee/d6/89881cbc5f3948d3fe4943cfc34f7a1fe65e6b53d73387bab89fc217eb54/hogql_parser_rs-1.3.69-cp312-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:20c77d302ae9d2e6c3ffaff8a7d6f33234b7eeef00dbf9fc9e8847af3e784536", size = 2169683, upload-time = "2026-05-21T17:04:25.375Z" },
- { url = "https://files.pythonhosted.org/packages/4d/7a/7f7d54f63e7ac136991f8cd1defe67e0f4088477d4cb65eb6a9922aaf5be/hogql_parser_rs-1.3.69-cp312-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:57ba7655c7efb19638e1dcb77cd32fdf763b1d44cd0816a9a929d5f6485d5e01", size = 2099178, upload-time = "2026-05-21T17:04:27.181Z" },
- { url = "https://files.pythonhosted.org/packages/8a/10/87c2a2fa981e1a96dddd7d688588d1fe3c8c992a74768421b3f0e32dcce0/hogql_parser_rs-1.3.69-cp312-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:fdf499cee104fa9d1f28b8dd3b525775c530ebc638af138941fb043c80d11b10", size = 2152315, upload-time = "2026-05-21T17:04:28.886Z" },
+ { url = "https://files.pythonhosted.org/packages/0c/23/be275691f68bd1b6d611ffa398fd6b2d263502c24ae85bf298db9981fecd/hogql_parser_rs-1.3.71-cp312-abi3-macosx_10_12_x86_64.whl", hash = "sha256:96541e331b9e11175392a0fc4acb6f05aa509b1345d5389dcc519f4c93c4c6e2", size = 701321, upload-time = "2026-05-22T14:24:10.771Z" },
+ { url = "https://files.pythonhosted.org/packages/a6/27/0c7d1f9b739c5ee0c77803faca87bba9cede6efe151ad0eb3bbf77c906e3/hogql_parser_rs-1.3.71-cp312-abi3-macosx_11_0_arm64.whl", hash = "sha256:986593ac3fb366b753e47ed8fb0c015818b180b8fc97b4901014d4885fd83c10", size = 662953, upload-time = "2026-05-22T14:24:12.734Z" },
+ { url = "https://files.pythonhosted.org/packages/6f/eb/45bc3f8cc05c514d3c9704dcef1d4d0b6ae94c0bd0b66303bf43a0ee3c6d/hogql_parser_rs-1.3.71-cp312-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:93aed9372e3fa2aa1775622a2df68741b6c928a83c90363c24f2d11a2d357551", size = 2407360, upload-time = "2026-05-22T14:24:15.06Z" },
+ { url = "https://files.pythonhosted.org/packages/aa/fc/d865fc82b167ba77ed797ca13482afd37723d59829de9314ff11746ff079/hogql_parser_rs-1.3.71-cp312-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:d73c11a37ca40de3fd022d714e62f6c725b3eb78884cc5a90f4d1300dbe9fa97", size = 2658541, upload-time = "2026-05-22T14:24:17.32Z" },
+ { url = "https://files.pythonhosted.org/packages/9b/4b/a072d993a8373e17e7f4406475c0847d49c84e1cf13c53d9cf7206c4a015/hogql_parser_rs-1.3.71-cp312-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:47a9e66f76e1d5d897cff6b6f773f6989d94ca4b7d83b7cd39576a4fd3be4b7b", size = 2579339, upload-time = "2026-05-22T14:24:19.8Z" },
+ { url = "https://files.pythonhosted.org/packages/b5/a4/d3d0ee2d42283a175c3b63af866eac9e3b640af0315262d5442a224b4cdd/hogql_parser_rs-1.3.71-cp312-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:6c5e4283ab7634f6946da67e04492f4a7f0801e36eab1bc1e352f1b1cc677453", size = 2626413, upload-time = "2026-05-22T14:24:21.484Z" },
]
[[package]]
@@ -5567,7 +5567,7 @@ requires-dist = [
{ name = "grpcio", specifier = "~=1.71.0" },
{ name = "gspread", specifier = "==6.2.1" },
{ name = "hogql-parser", specifier = "==1.3.65" },
- { name = "hogql-parser-rs", specifier = "==1.3.69" },
+ { name = "hogql-parser-rs", specifier = "==1.3.71" },
{ name = "humanize", specifier = "~=4.12.3" },
{ name = "infi-clickhouse-orm", git = "https://github.com/PostHog/infi.clickhouse_orm?rev=4e3996becf66bf5c26580aff12a80425d9d56fe5" },
{ name = "jsonref", specifier = "==1.1.0" },