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.

chore(hogql): migrate hogql_parser_rs from pyo3 0.22 to 0.28 (#73619)

Tom Owersf6b8cf972bad
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index ee11e9510736..50dc62dc8793 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -1997,7 +1997,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fb693542bcafa528e198be0ebd9d3632ca5b7c93dbe7237460e199910835997c"
dependencies = [
"smallvec",
- "target-lexicon 0.13.5",
+ "target-lexicon",
]
[[package]]
@@ -4761,7 +4761,7 @@ dependencies = [
[[package]]
name = "hogql_parser_rs"
-version = "1.3.106"
+version = "1.3.107"
dependencies = [
"pyo3",
"serde_json",
@@ -5367,15 +5367,6 @@ dependencies = [
"serde_core",
]
-[[package]]
-name = "indoc"
-version = "2.0.7"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "79cf5c93f93228cf8efb3ba362535fb11199ac548a09ce117c9b1adc3030d706"
-dependencies = [
- "rustversion",
-]
-
[[package]]
name = "inferno"
version = "0.11.21"
@@ -8823,37 +8814,32 @@ checksum = "e0c5ccf5294c6ccd63a74f1565028353830a9c2f5eb0c682c355c471726a6e3f"
[[package]]
name = "pyo3"
-version = "0.22.6"
+version = "0.28.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f402062616ab18202ae8319da13fa4279883a2b8a9d9f83f20dbade813ce1884"
+checksum = "91fd8e38a3b50ed1167fb981cd6fd60147e091784c427b8f7183a7ee32c31c12"
dependencies = [
- "cfg-if",
- "indoc",
"libc",
- "memoffset",
"once_cell",
"portable-atomic",
"pyo3-build-config",
"pyo3-ffi",
"pyo3-macros",
- "unindent",
]
[[package]]
name = "pyo3-build-config"
-version = "0.22.6"
+version = "0.28.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b14b5775b5ff446dd1056212d778012cbe8a0fbffd368029fd9e25b514479c38"
+checksum = "e368e7ddfdeb98c9bca7f8383be1648fd84ab466bf2bc015e94008db6d35611e"
dependencies = [
- "once_cell",
- "target-lexicon 0.12.16",
+ "target-lexicon",
]
[[package]]
name = "pyo3-ffi"
-version = "0.22.6"
+version = "0.28.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9ab5bcf04a2cdcbb50c7d6105de943f543f9ed92af55818fd17b660390fc8636"
+checksum = "7f29e10af80b1f7ccaf7f69eace800a03ecd13e883acfacc1e5d0988605f651e"
dependencies = [
"libc",
"pyo3-build-config",
@@ -8861,9 +8847,9 @@ dependencies = [
[[package]]
name = "pyo3-macros"
-version = "0.22.6"
+version = "0.28.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0fd24d897903a9e6d80b968368a34e1525aeb719d568dba8b3d4bfa5dc67d453"
+checksum = "df6e520eff47c45997d2fc7dd8214b25dd1310918bbb2642156ef66a67f29813"
dependencies = [
"proc-macro2",
"pyo3-macros-backend",
@@ -8873,9 +8859,9 @@ dependencies = [
[[package]]
name = "pyo3-macros-backend"
-version = "0.22.6"
+version = "0.28.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "36c011a03ba1e50152b4b394b479826cad97e7a21eb52df179cd91ac411cbfbe"
+checksum = "c4cdc218d835738f81c2338f822078af45b4afdf8b2e33cbb5916f108b813acb"
dependencies = [
"heck",
"proc-macro2",
@@ -11310,12 +11296,6 @@ version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369"
-[[package]]
-name = "target-lexicon"
-version = "0.12.16"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "61c41af27dd6d1e27b1b16b489db798443478cef1f06a660c96db617ba5de3b1"
-
[[package]]
name = "target-lexicon"
version = "0.13.5"
@@ -11331,7 +11311,7 @@ dependencies = [
"cfg-expr",
"guppy-workspace-hack",
"serde",
- "target-lexicon 0.13.5",
+ "target-lexicon",
]
[[package]]
@@ -12370,12 +12350,6 @@ version = "0.2.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853"
-[[package]]
-name = "unindent"
-version = "0.2.4"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7264e107f553ccae879d21fbea1d6724ac785e8c3bfc762137959b5802826ef3"
-
[[package]]
name = "unsafe-libyaml"
version = "0.2.11"
diff --git a/rust/hogql/parser/Cargo.toml b/rust/hogql/parser/Cargo.toml
index f4e2e8a3cd8b..359bbbaa3007 100644
--- a/rust/hogql/parser/Cargo.toml
+++ b/rust/hogql/parser/Cargo.toml
@@ -1,7 +1,7 @@
[package]
name = "hogql_parser_rs"
# Versioned independently from the cpp parser in `common/hogql_parser/setup.py`. Both started from the same HogQL grammar revision, but the Rust port is bumped on its own whenever the hand-rolled parser changes; each ships as its own PyPI wheel.
-version = "1.3.106"
+version = "1.3.107"
edition = "2021"
publish = false
@@ -19,7 +19,10 @@ workspace = true
serde_json.workspace = true
# `abi3-py312` lets one wheel work on every Python 3.12+ via the stable
# CPython ABI — avoids shipping a separate wheel per minor Python.
-pyo3 = { version = "0.22", features = ["extension-module", "abi3-py312"] }
+# 0.28: cargo allows one pyo3 version per workspace (pyo3 has `links = "python"`),
+# and rust/deltalite/python's pyarrow ingest (arrow 58 `pyarrow` feature) requires
+# 0.28 — keep the two in lockstep or the workspace stops resolving.
+pyo3 = { version = "0.28", features = ["extension-module", "abi3-py312"] }
[features]
default = []
diff --git a/rust/hogql/parser/pyproject.toml b/rust/hogql/parser/pyproject.toml
index c1359fad8443..889622493fbf 100644
--- a/rust/hogql/parser/pyproject.toml
+++ b/rust/hogql/parser/pyproject.toml
@@ -9,7 +9,7 @@ build-backend = "maturin"
[project]
name = "hogql_parser_rs"
# Mirrors `rust/hogql/parser/Cargo.toml` (always identical). Tracks but is NOT locked to `common/hogql_parser/setup.py`: the Rust port is versioned independently and bumped on its own whenever the hand-rolled parser changes.
-version = "1.3.106"
+version = "1.3.107"
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/cov.rs b/rust/hogql/parser/src/cov.rs
index 072cc6bfa227..aae6f33495ab 100644
--- a/rust/hogql/parser/src/cov.rs
+++ b/rust/hogql/parser/src/cov.rs
@@ -76,12 +76,12 @@ pub unsafe extern "C" fn __sanitizer_cov_trace_pc_guard(guard: *mut u32) {
/// `target()` call. A 64KiB copy per example is well inside the per-example
/// budget (microseconds vs the millisecond per-parse cost).
#[pyfunction]
-pub fn cov_snapshot(py: Python<'_>) -> PyObject {
+pub fn cov_snapshot(py: Python<'_>) -> Py<PyAny> {
let mut buf = [0u8; BITMAP_SIZE];
for (i, cell) in COVERAGE.iter().enumerate() {
buf[i] = cell.load(Ordering::Relaxed);
}
- PyBytes::new_bound(py, &buf).into()
+ PyBytes::new(py, &buf).into()
}
/// Zero the bitmap. The diagnostic calls this before each example so the
diff --git a/rust/hogql/parser/src/emit_py.rs b/rust/hogql/parser/src/emit_py.rs
index 390a3fd86d27..40964bc512f7 100644
--- a/rust/hogql/parser/src/emit_py.rs
+++ b/rust/hogql/parser/src/emit_py.rs
@@ -15,6 +15,7 @@
use pyo3::prelude::*;
use pyo3::types::{PyDict, PyList, PyTuple};
+use pyo3::IntoPyObjectExt;
use std::borrow::Cow;
use std::collections::HashMap;
@@ -47,7 +48,7 @@ impl PyAst {
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 {
+ Python::attach(|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).
@@ -137,7 +138,7 @@ pub struct PyEmitter<'py> {
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.
+ /// Python builtin `int` class — used by `constant_number_string` for arbitrary-precision integer literals (i64-wider hex/decimal). Cached once instead of `py.eval("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`.
@@ -170,7 +171,7 @@ pub struct PyEmitter<'py> {
impl<'py> PyEmitter<'py> {
pub fn new(py: Python<'py>) -> PyResult<Self> {
- let ast_module = py.import_bound("posthog.hogql.ast")?;
+ let ast_module = py.import("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")?;
@@ -237,7 +238,7 @@ impl<'py> PyEmitter<'py> {
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")?,
+ cls_int: py.import("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")?,
@@ -309,7 +310,7 @@ impl<'py> PyEmitter<'py> {
/// 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 {
- match class.call(PyTuple::empty_bound(self.py), Some(kwargs)) {
+ match class.call(PyTuple::empty(self.py), Some(kwargs)) {
Ok(obj) => PyAst {
obj: obj.unbind(),
positions_locked: false,
@@ -326,7 +327,7 @@ impl<'py> PyEmitter<'py> {
}
/// 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 {
+ fn wrap_prim(&self, obj: Py<PyAny>) -> PyAst {
PyAst {
obj,
positions_locked: false,
@@ -348,29 +349,29 @@ impl<'py> Emitter for PyEmitter<'py> {
self.wrap_prim(self.py.None())
}
fn bool(&self, v: bool) -> PyAst {
- self.wrap_prim(v.into_py(self.py))
+ self.wrap_prim(v.into_py_any(self.py).unwrap())
}
fn int(&self, v: i64) -> PyAst {
- self.wrap_prim(v.into_py(self.py))
+ self.wrap_prim(v.into_py_any(self.py).unwrap())
}
fn string(&self, v: &str) -> PyAst {
- self.wrap_prim(v.into_py(self.py))
+ self.wrap_prim(v.into_py_any(self.py).unwrap())
}
fn float(&self, v: f64) -> PyAst {
- self.wrap_prim(v.into_py(self.py))
+ self.wrap_prim(v.into_py_any(self.py).unwrap())
}
fn uint(&self, v: u64) -> PyAst {
- self.wrap_prim(v.into_py(self.py))
+ self.wrap_prim(v.into_py_any(self.py).unwrap())
}
fn list_value(&self, items: Vec<PyAst>) -> PyAst {
- let list = PyList::empty_bound(self.py);
+ let list = PyList::empty(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);
+ let dict = PyDict::new(self.py);
for (k, v) in pairs {
dict.set_item(k, v.obj.bind(self.py)).unwrap();
}
@@ -380,7 +381,7 @@ impl<'py> Emitter for PyEmitter<'py> {
// ===== AST node constructors =====
fn constant(&self, value: PyAst) -> PyAst {
- let kw = PyDict::new_bound(self.py);
+ let kw = PyDict::new(self.py);
kw.set_item("value", value.obj.bind(self.py)).unwrap();
self.build(&self.cls_constant, &kw)
}
@@ -392,7 +393,7 @@ impl<'py> Emitter for PyEmitter<'py> {
"NaN" => f64::NAN,
_ => panic!("unknown special number name `{name}`"),
};
- let kw = PyDict::new_bound(self.py);
+ let kw = PyDict::new(self.py);
kw.set_item("value", f).unwrap();
self.build(&self.cls_constant, &kw)
}
@@ -401,26 +402,33 @@ impl<'py> Emitter for PyEmitter<'py> {
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 args = PyTuple::new(
+ self.py,
+ [
+ text.into_py_any(self.py).unwrap(),
+ base.into_py_any(self.py).unwrap(),
+ ],
+ )
+ .unwrap();
let int_obj = self.cls_int.call(&args, None).unwrap();
- let kw = PyDict::new_bound(self.py);
+ let kw = PyDict::new(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);
+ let kw = PyDict::new(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);
+ let kw = PyDict::new(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);
+ let kw = PyDict::new(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();
@@ -428,7 +436,7 @@ impl<'py> Emitter for PyEmitter<'py> {
}
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);
+ let kw = PyDict::new(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))
@@ -443,14 +451,14 @@ impl<'py> Emitter for PyEmitter<'py> {
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);
+ let kw = PyDict::new(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);
+ let kw = PyDict::new(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();
@@ -458,32 +466,32 @@ impl<'py> Emitter for PyEmitter<'py> {
self.build(&self.cls_between_expr, &kw)
}
fn not_(&self, expr: PyAst) -> PyAst {
- let kw = PyDict::new_bound(self.py);
+ let kw = PyDict::new(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);
+ let kw = PyDict::new(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);
+ let kw = PyDict::new(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);
+ let kw = PyDict::new(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);
+ let kw = PyDict::new(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);
+ let kw = PyDict::new(self.py);
kw.set_item("array", array.obj.bind(self.py)).unwrap();
kw.set_item("property", property.obj.bind(self.py)).unwrap();
if nullish {
@@ -492,7 +500,7 @@ impl<'py> Emitter for PyEmitter<'py> {
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);
+ let kw = PyDict::new(self.py);
kw.set_item("tuple", tuple_.obj.bind(self.py)).unwrap();
kw.set_item("index", index).unwrap();
if nullish {
@@ -501,13 +509,13 @@ impl<'py> Emitter for PyEmitter<'py> {
self.build(&self.cls_tuple_access, &kw)
}
fn alias(&self, expr: PyAst, name: &str) -> PyAst {
- let kw = PyDict::new_bound(self.py);
+ let kw = PyDict::new(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);
+ let kw = PyDict::new(self.py);
kw.set_item("name", name).unwrap();
kw.set_item("args", build_list(self.py, args)).unwrap();
self.build(&self.cls_call, &kw)
@@ -522,7 +530,7 @@ impl<'py> Emitter for PyEmitter<'py> {
filter_expr: Option<PyAst>,
within_group: Option<Vec<PyAst>>,
) -> PyAst {
- let kw = PyDict::new_bound(self.py);
+ let kw = PyDict::new(self.py);
kw.set_item("name", name).unwrap();
kw.set_item("args", build_list(self.py, args)).unwrap();
if let Some(p) = params {
@@ -544,8 +552,8 @@ impl<'py> Emitter for PyEmitter<'py> {
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);
+ let kw = PyDict::new(self.py);
+ let args_list = PyList::empty(self.py);
for a in args {
args_list.append(a).unwrap();
}
@@ -554,25 +562,25 @@ impl<'py> Emitter for PyEmitter<'py> {
self.build(&self.cls_lambda, &kw)
}
fn expr_call(&self, expr: PyAst, args: Vec<PyAst>) -> PyAst {
- let kw = PyDict::new_bound(self.py);
+ let kw = PyDict::new(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);
+ let kw = PyDict::new(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);
+ let kw = PyDict::new(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);
+ let kw = PyDict::new(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();
@@ -583,22 +591,22 @@ impl<'py> Emitter for PyEmitter<'py> {
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);
+ let kw = PyDict::new(self.py);
+ let items_list = PyList::empty(self.py);
for (k, v) in items {
- let pair = PyTuple::new_bound(self.py, [k.obj, v.obj]);
+ let pair = PyTuple::new(self.py, [k.obj, v.obj]).unwrap();
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);
+ let kw = PyDict::new(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);
+ let kw = PyDict::new(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);
@@ -607,7 +615,7 @@ impl<'py> Emitter for PyEmitter<'py> {
node
}
fn order_expr(&self, expr: PyAst, order: &str, with_fill: Option<PyAst>) -> PyAst {
- let kw = PyDict::new_bound(self.py);
+ let kw = PyDict::new(self.py);
kw.set_item("expr", expr.obj.bind(self.py)).unwrap();
kw.set_item("order", order).unwrap();
if let Some(wf) = with_fill {
@@ -623,7 +631,7 @@ impl<'py> Emitter for PyEmitter<'py> {
exclude: Option<Vec<String>>,
replace: Option<Vec<(String, PyAst)>>,
) -> PyAst {
- let kw = PyDict::new_bound(self.py);
+ let kw = PyDict::new(self.py);
if let Some(r) = regex {
kw.set_item("regex", r).unwrap();
}
@@ -634,14 +642,14 @@ impl<'py> Emitter for PyEmitter<'py> {
kw.set_item("all_columns", true).unwrap();
}
if let Some(ex) = exclude {
- let ex_list = PyList::empty_bound(self.py);
+ let ex_list = PyList::empty(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);
+ let rep_dict = PyDict::new(self.py);
for (k, v) in rep {
rep_dict.set_item(k, v.obj.bind(self.py)).unwrap();
}
@@ -650,12 +658,12 @@ impl<'py> Emitter for PyEmitter<'py> {
self.build(&self.cls_columns_expr, &kw)
}
fn spread_expr(&self, expr: PyAst) -> PyAst {
- let kw = PyDict::new_bound(self.py);
+ let kw = PyDict::new(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);
+ let kw = PyDict::new(self.py);
kw.set_item("index", index).unwrap();
self.build(&self.cls_positional_ref, &kw)
}
@@ -663,31 +671,31 @@ impl<'py> Emitter for PyEmitter<'py> {
// ===== Statement / program builders =====
fn program(&self, declarations: Vec<PyAst>) -> PyAst {
- let kw = PyDict::new_bound(self.py);
+ let kw = PyDict::new(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);
+ let kw = PyDict::new(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);
+ let kw = PyDict::new(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);
+ let kw = PyDict::new(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);
+ let kw = PyDict::new(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)
@@ -699,7 +707,7 @@ impl<'py> Emitter for PyEmitter<'py> {
expr: PyAst,
body: PyAst,
) -> PyAst {
- let kw = PyDict::new_bound(self.py);
+ let kw = PyDict::new(self.py);
kw.set_item("keyVar", key_var.obj.bind(self.py)).unwrap();
kw.set_item("valueVar", value_var.obj.bind(self.py))
.unwrap();
@@ -714,7 +722,7 @@ impl<'py> Emitter for PyEmitter<'py> {
increment: PyAst,
body: PyAst,
) -> PyAst {
- let kw = PyDict::new_bound(self.py);
+ let kw = PyDict::new(self.py);
kw.set_item("initializer", initializer.obj.bind(self.py))
.unwrap();
kw.set_item("condition", condition.obj.bind(self.py))
@@ -725,20 +733,20 @@ impl<'py> Emitter for PyEmitter<'py> {
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);
+ let kw = PyDict::new(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);
+ let kw = PyDict::new(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);
+ let kw = PyDict::new(self.py);
kw.set_item("expr", expr.obj.bind(self.py)).unwrap();
self.build(&self.cls_return_statement, &kw)
}
@@ -748,7 +756,7 @@ impl<'py> Emitter for PyEmitter<'py> {
catches: Vec<PyAst>,
finally_stmt: PyAst,
) -> PyAst {
- let kw = PyDict::new_bound(self.py);
+ let kw = PyDict::new(self.py);
kw.set_item("try_stmt", try_stmt.obj.bind(self.py)).unwrap();
kw.set_item("catches", build_list(self.py, catches))
.unwrap();
@@ -757,12 +765,12 @@ impl<'py> Emitter for PyEmitter<'py> {
self.build(&self.cls_try_catch_statement, &kw)
}
fn throw_statement(&self, expr: PyAst) -> PyAst {
- let kw = PyDict::new_bound(self.py);
+ let kw = PyDict::new(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);
+ let kw = PyDict::new(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)
@@ -773,14 +781,14 @@ impl<'py> Emitter for PyEmitter<'py> {
// (matching what `CloningVisitor.visit_try_catch_statement` builds and what
// `json_ast._TUPLE_INNER_FIELDS` now deserialises cpp/rust-json arrays into).
// Build a tuple here so `rust-py` produces the canonical shape directly.
- let pair = PyTuple::new_bound(self.py, [var.obj, ty.obj, body.obj]);
+ let pair = PyTuple::new(self.py, [var.obj, ty.obj, body.obj]).unwrap();
self.wrap_prim(pair.into_any().unbind())
}
// ===== Query / clause builders =====
fn cte(&self, name: &str, expr: PyAst, cte_type: &str) -> PyAst {
- let kw = PyDict::new_bound(self.py);
+ let kw = PyDict::new(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();
@@ -794,19 +802,19 @@ impl<'py> Emitter for PyEmitter<'py> {
using_key: Option<Vec<String>>,
materialized: Option<bool>,
) -> PyAst {
- let kw = PyDict::new_bound(self.py);
+ let kw = PyDict::new(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);
+ let l = PyList::empty(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);
+ let l = PyList::empty(self.py);
for s in uk {
l.append(s).unwrap();
}
@@ -818,18 +826,18 @@ impl<'py> Emitter for PyEmitter<'py> {
self.build(&self.cls_cte, &kw)
}
fn join_constraint(&self, expr: PyAst, constraint_type: &str) -> PyAst {
- let kw = PyDict::new_bound(self.py);
+ let kw = PyDict::new(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);
+ let kw = PyDict::new(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);
+ let kw = PyDict::new(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)
@@ -840,7 +848,7 @@ impl<'py> Emitter for PyEmitter<'py> {
name_columns: PyAst,
unpivot_values: Vec<PyAst>,
) -> PyAst {
- let kw = PyDict::new_bound(self.py);
+ let kw = PyDict::new(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))
@@ -850,25 +858,25 @@ impl<'py> Emitter for PyEmitter<'py> {
self.build(&self.cls_unpivot_column, &kw)
}
fn grouping_set(&self, exprs: Vec<PyAst>) -> PyAst {
- let kw = PyDict::new_bound(self.py);
+ let kw = PyDict::new(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);
+ let kw = PyDict::new(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);
+ let kw = PyDict::new(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);
+ let kw = PyDict::new(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))
@@ -877,17 +885,17 @@ impl<'py> Emitter for PyEmitter<'py> {
}
fn window_expr_empty(&self) -> PyAst {
// `WindowExpr()` with all-defaults.
- self.build(&self.cls_window_expr, &PyDict::new_bound(self.py))
+ self.build(&self.cls_window_expr, &PyDict::new(self.py))
}
fn window_frame_bound(&self, frame_type: &str, frame_value: PyAst) -> PyAst {
- let kw = PyDict::new_bound(self.py);
+ let kw = PyDict::new(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);
+ let kw = PyDict::new(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();
@@ -895,7 +903,7 @@ impl<'py> Emitter for PyEmitter<'py> {
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);
+ let kw = PyDict::new(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 {
@@ -905,12 +913,12 @@ impl<'py> Emitter for PyEmitter<'py> {
}
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();
+ let kw = PyDict::new(self.py);
+ kw.set_item("select", PyList::empty(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);
+ let kw = PyDict::new(self.py);
kw.set_item("select_query", select_query.obj.bind(self.py))
.unwrap();
if let Some(op) = set_operator {
@@ -919,7 +927,7 @@ impl<'py> Emitter for PyEmitter<'py> {
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);
+ let kw = PyDict::new(self.py);
kw.set_item("sample_value", sample_value.obj.bind(self.py))
.unwrap();
if let Some(o) = offset_value {
@@ -928,7 +936,7 @@ impl<'py> Emitter for PyEmitter<'py> {
self.build(&self.cls_sample_expr, &kw)
}
fn ratio_expr(&self, left: PyAst, right: Option<PyAst>) -> PyAst {
- let kw = PyDict::new_bound(self.py);
+ let kw = PyDict::new(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();
@@ -942,7 +950,7 @@ impl<'py> Emitter for PyEmitter<'py> {
columns: Vec<PyAst>,
group_by: Option<Vec<PyAst>>,
) -> PyAst {
- let kw = PyDict::new_bound(self.py);
+ let kw = PyDict::new(self.py);
kw.set_item("table", table.obj.bind(self.py)).unwrap();
kw.set_item("aggregates", build_list(self.py, aggregates))
.unwrap();
@@ -954,7 +962,7 @@ impl<'py> Emitter for PyEmitter<'py> {
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);
+ let kw = PyDict::new(self.py);
kw.set_item("table", table.obj.bind(self.py)).unwrap();
kw.set_item("columns", build_list(self.py, columns))
.unwrap();
@@ -970,7 +978,7 @@ impl<'py> Emitter for PyEmitter<'py> {
table_final: bool,
sample: Option<PyAst>,
) -> PyAst {
- let kw = PyDict::new_bound(self.py);
+ let kw = PyDict::new(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();
@@ -985,7 +993,7 @@ impl<'py> Emitter for PyEmitter<'py> {
kw.set_item("sample", s.obj.bind(self.py)).unwrap();
}
if let Some(ca) = column_aliases {
- let l = PyList::empty_bound(self.py);
+ let l = PyList::empty(self.py);
for s in ca {
l.append(s).unwrap();
}
@@ -1001,7 +1009,7 @@ impl<'py> Emitter for PyEmitter<'py> {
over_expr: Option<PyAst>,
over_identifier: Option<String>,
) -> PyAst {
- let kw = PyDict::new_bound(self.py);
+ let kw = PyDict::new(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();
@@ -1019,7 +1027,7 @@ impl<'py> Emitter for PyEmitter<'py> {
to_value: Option<PyAst>,
step_value: Option<PyAst>,
) -> PyAst {
- let kw = PyDict::new_bound(self.py);
+ let kw = PyDict::new(self.py);
if let Some(v) = from_value {
kw.set_item("from_value", v.obj.bind(self.py)).unwrap();
}
@@ -1035,7 +1043,7 @@ impl<'py> Emitter for PyEmitter<'py> {
// ===== 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))
+ self.wrap_prim(offset.into_py_any(self.py).unwrap())
}
fn with_pos(&self, value: PyAst, start: PyAst, end: PyAst) -> PyAst {
if value.positions_locked {
@@ -1095,8 +1103,8 @@ impl<'py> Emitter for PyEmitter<'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);
+ if let Ok(dict) = got.cast::<PyDict>() {
+ let list = PyList::empty(self.py);
for (_, val) in dict.iter() {
list.append(val).unwrap();
}
@@ -1137,7 +1145,7 @@ impl<'py> Emitter for PyEmitter<'py> {
}
fn as_list(&self, v: &PyAst) -> Option<Vec<PyAst>> {
let bound = v.obj.bind(self.py);
- let list = bound.downcast::<PyList>().ok()?;
+ let list = bound.cast::<PyList>().ok()?;
let mut out = Vec::with_capacity(list.len());
for item in list.iter() {
out.push(PyAst {
@@ -1200,8 +1208,8 @@ impl<'py> Emitter for PyEmitter<'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);
+ if let Ok(list) = val_bound.cast::<PyList>() {
+ let dict = PyDict::new(self.py);
for item in list.iter() {
let cte_name = item
.getattr("name")
@@ -1238,7 +1246,7 @@ impl<'py> Emitter for PyEmitter<'py> {
// ============================================================================
fn build_list(py: Python<'_>, items: Vec<PyAst>) -> Bound<'_, PyList> {
- let list = PyList::empty_bound(py);
+ let list = PyList::empty(py);
for item in items {
list.append(item.obj).unwrap();
}
diff --git a/rust/hogql/parser/src/lib.rs b/rust/hogql/parser/src/lib.rs
index d87f5087630f..21ef24cb504c 100644
--- a/rust/hogql/parser/src/lib.rs
+++ b/rust/hogql/parser/src/lib.rs
@@ -13,7 +13,7 @@
//! 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.
+// `#[pyfunction]`'s expansion does an `.into()` on the `PyResult<Py<PyAny>>` 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)]
// Style lints that conflict with the parser's deliberate shape: a few internal helpers return wide tuples (the table-alias chain, function-arg bundles) rather than one-off structs; some builder-style helpers are named `from_*` but take `&self`; and the heavily-prose doc comments use markdown lists clippy's `doc_lazy_continuation` flags. None are actionable without churning the parser, so allow them crate-wide.
#![allow(
@@ -69,7 +69,7 @@ where
/// 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>
+fn run_py<'py, F>(py: Python<'py>, f: F) -> PyResult<Py<PyAny>>
where
F: FnOnce(emit_py::PyEmitter<'py>) -> Result<emit_py::PyAst, error::ParseError>,
{
@@ -134,31 +134,31 @@ fn parse_full_template_string_json(string: &str) -> String {
#[pyfunction]
#[pyo3(signature = (statement, is_internal=false))]
-fn parse_expr_py(py: Python<'_>, statement: &str, is_internal: bool) -> PyResult<PyObject> {
+fn parse_expr_py(py: Python<'_>, statement: &str, is_internal: bool) -> PyResult<Py<PyAny>> {
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> {
+fn parse_order_expr_py(py: Python<'_>, statement: &str) -> PyResult<Py<PyAny>> {
run_py(py, |emit| {
parse::parse_order_expr_with_emit(emit, statement)
})
}
#[pyfunction]
-fn parse_select_py(py: Python<'_>, statement: &str) -> PyResult<PyObject> {
+fn parse_select_py(py: Python<'_>, statement: &str) -> PyResult<Py<PyAny>> {
run_py(py, |emit| parse::parse_select_with_emit(emit, statement))
}
#[pyfunction]
-fn parse_program_py(py: Python<'_>, source: &str) -> PyResult<PyObject> {
+fn parse_program_py(py: Python<'_>, source: &str) -> PyResult<Py<PyAny>> {
run_py(py, |emit| parse::parse_program_with_emit(emit, source))
}
#[pyfunction]
-fn parse_full_template_string_py(py: Python<'_>, string: &str) -> PyResult<PyObject> {
+fn parse_full_template_string_py(py: Python<'_>, string: &str) -> PyResult<Py<PyAny>> {
run_py(py, |emit| {
parse::parse_full_template_string_with_emit(emit, string)
})
diff --git a/rust/hogql/parser/src/pyobject.rs b/rust/hogql/parser/src/pyobject.rs
index a2d5c9eab3dd..ed6415c4cfb8 100644
--- a/rust/hogql/parser/src/pyobject.rs
+++ b/rust/hogql/parser/src/pyobject.rs
@@ -7,6 +7,7 @@
use pyo3::exceptions::PyValueError;
use pyo3::prelude::*;
use pyo3::types::{PyDict, PyList, PyTuple};
+use pyo3::IntoPyObjectExt;
use serde_json::Value;
/// Raise the matching `posthog.hogql.errors` exception for a parser error envelope, importing ONLY the errors module — error paths don't pay for the success-path converter's AST/enum imports. Mirrors `json_ast.py`'s `SyntaxError`/`ParsingError`/else mapping; shared by `Converter::build_error` and the standalone `parse_string_literal_text` entry point.
@@ -17,7 +18,7 @@ pub(crate) fn raise_error_envelope(
start: Option<u64>,
end: Option<u64>,
) -> PyErr {
- let errors_module = match py.import_bound("posthog.hogql.errors") {
+ let errors_module = match py.import("posthog.hogql.errors") {
Ok(m) => m,
Err(e) => return e,
};
@@ -30,16 +31,19 @@ pub(crate) fn raise_error_envelope(
Ok(c) => c,
Err(e) => return e,
};
- let kwargs = PyDict::new_bound(py);
+ let kwargs = PyDict::new(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(py, [message]);
+ let args = match PyTuple::new(py, [message]) {
+ Ok(a) => a,
+ Err(e) => return e,
+ };
match cls.call(&args, Some(&kwargs)) {
- Ok(exc) => PyErr::from_value_bound(exc),
+ Ok(exc) => PyErr::from_value(exc),
Err(e) => e,
}
}
@@ -50,16 +54,16 @@ pub struct Converter<'py> {
ast_module: Bound<'py, PyModule>,
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.
+ /// Python builtin `int` class. Mirrors `PyEmitter::cls_int`; cached so big-int literals don't pay `py.eval("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 ast_module = py.import("posthog.hogql.ast")?;
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")?;
+ let cls_int = py.import("builtins")?.getattr("int")?;
Ok(Self {
py,
ast_module,
@@ -70,29 +74,29 @@ impl<'py> Converter<'py> {
}
/// Top-level entry: convert the root `Value` to a Python AST instance. Raises `ExposedHogQLError` / `SyntaxError` / `ParsingError` if the parser returned an error envelope.
- pub fn convert_root(&self, value: &Value) -> PyResult<PyObject> {
+ pub fn convert_root(&self, value: &Value) -> PyResult<Py<PyAny>> {
self.convert(value)
}
/// Recursive walk. Mirrors `_deserialize_node` in `json_ast.py`.
- fn convert(&self, value: &Value) -> PyResult<PyObject> {
+ fn convert(&self, value: &Value) -> PyResult<Py<PyAny>> {
match value {
Value::Null => Ok(self.py.None()),
- Value::Bool(b) => Ok(b.into_py(self.py)),
+ Value::Bool(b) => b.into_py_any(self.py),
Value::Number(n) => {
if let Some(i) = n.as_i64() {
- Ok(i.into_py(self.py))
+ i.into_py_any(self.py)
} else if let Some(u) = n.as_u64() {
- Ok(u.into_py(self.py))
+ u.into_py_any(self.py)
} else if let Some(f) = n.as_f64() {
- Ok(f.into_py(self.py))
+ f.into_py_any(self.py)
} else {
Err(PyValueError::new_err(format!("Invalid JSON number: {n}")))
}
}
- Value::String(s) => Ok(s.as_str().into_py(self.py)),
+ Value::String(s) => s.as_str().into_py_any(self.py),
Value::Array(items) => {
- let list = PyList::empty_bound(self.py);
+ let list = PyList::empty(self.py);
for item in items {
list.append(self.convert(item)?)?;
}
@@ -124,7 +128,7 @@ impl<'py> Converter<'py> {
None
};
- let kwargs = PyDict::new_bound(self.py);
+ let kwargs = PyDict::new(self.py);
for (key, val) in map.iter() {
if key == "node" || key == "value_type" {
continue;
@@ -162,7 +166,7 @@ impl<'py> Converter<'py> {
// `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);
+ let dict = PyDict::new(self.py);
for item in items {
let name =
item.get("name").and_then(Value::as_str).ok_or_else(|| {
@@ -183,7 +187,7 @@ impl<'py> Converter<'py> {
&& !val.as_object().is_some_and(|m| m.contains_key("node"))
{
let map = val.as_object().unwrap();
- let dict = PyDict::new_bound(self.py);
+ let dict = PyDict::new(self.py);
for (k, v) in map.iter() {
dict.set_item(k, self.convert(v)?)?;
}
@@ -212,7 +216,7 @@ impl<'py> Converter<'py> {
kwargs.set_item(key, converted)?;
}
- let args = PyTuple::empty_bound(self.py);
+ let args = PyTuple::empty(self.py);
Ok(ast_class.call(&args, Some(&kwargs))?.unbind())
}
}
@@ -240,7 +244,7 @@ impl<'py> Converter<'py> {
}
/// 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>> {
+ fn parse_large_int_literal(&self, value: &str) -> PyResult<Option<Py<PyAny>>> {
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 };
@@ -249,7 +253,10 @@ impl<'py> Converter<'py> {
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)]);
+ let args = PyTuple::new(
+ self.py,
+ [value.into_py_any(self.py)?, base.into_py_any(self.py)?],
+ )?;
match self.cls_int.call(&args, None) {
Ok(obj) => Ok(Some(obj.unbind())),
Err(_) => Ok(None),