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.

feat(hogql): add parse_string_literal_text to the rust parser (#65277)

Robbie3dd75e1b5a17
diff --git a/posthog/hogql/scripts/_diagnostic_common.py b/posthog/hogql/scripts/_diagnostic_common.py
index cc4dd58c3a51..32f175257e8e 100644
--- a/posthog/hogql/scripts/_diagnostic_common.py
+++ b/posthog/hogql/scripts/_diagnostic_common.py
@@ -40,7 +40,10 @@ from collections.abc import Callable, Iterator
from pathlib import Path
from typing import Any, NoReturn
-from posthog.hogql.errors import BaseHogQLError
+from hogql_parser import parse_string_literal_text as _cpp_parse_string_literal_text
+from hogql_parser_rs import parse_string_literal_text as _rust_parse_string_literal_text
+
+from posthog.hogql.errors import BaseHogQLError, ParsingError
from posthog.hogql.parser import (
HogQLParserShadowMismatch,
parse_expr,
@@ -61,6 +64,16 @@ def _parse_full_template_string(query: str, backend: Any = None) -> Any:
return parse_string_template(body, backend=backend)
+def _parse_string_literal_text(query: str, backend: Any = None) -> str:
+ """Dispatch the unquoter by backend family (`cpp*`/`rust*`) for parity fuzzing; raises like both wheels."""
+ use_cpp = backend is None or str(backend).startswith("cpp")
+ # cpp wheel aborts the process on "" (uncaught C++ ParsingError); raise the class it declares so the grind survives.
+ if use_cpp and query == "":
+ raise ParsingError("Encountered an unexpected empty string input")
+ fn = _cpp_parse_string_literal_text if use_cpp else _rust_parse_string_literal_text
+ return fn(query)
+
+
# Maps a diagnostic `--rule` value to its parser entry point. `program`
# covers the Hog imperative-statement layer (let / if / while / for /
# fn / try-catch / return / throw / blocks); `full_template_string` is the
@@ -72,6 +85,7 @@ _PARSER_FOR_RULE: dict[str, Callable[..., Any]] = {
"select": parse_select,
"program": parse_program,
"full_template_string": _parse_full_template_string,
+ "string_literal": _parse_string_literal_text,
}
# ---------------------------------------------------------------------------
diff --git a/posthog/hogql/scripts/pbt_diagnostic.py b/posthog/hogql/scripts/pbt_diagnostic.py
index 3b524dc29899..98b65b702e9c 100644
--- a/posthog/hogql/scripts/pbt_diagnostic.py
+++ b/posthog/hogql/scripts/pbt_diagnostic.py
@@ -64,8 +64,8 @@ Typical usage:
"""
# ruff: noqa: T201 (this is a CLI script — print is the output channel)
-# ruff: noqa: E402 (django.setup() must run between import django and the
-# project-app imports below)
+# ruff: noqa: E402 (DJANGO_SETTINGS_MODULE must be set before the project-app
+# imports below)
from __future__ import annotations
@@ -75,14 +75,18 @@ import json
import argparse
import traceback
from collections import Counter
+from collections.abc import Callable
from typing import Any
-import django
-
+# Skip django.setup(): parser core only reads settings.TEST, so settings alone avoids ready()-hook DB/redis init.
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "posthog.settings")
-django.setup()
-from hypothesis import assume, given, settings
+from hypothesis import (
+ assume,
+ given,
+ settings,
+ strategies as st,
+)
# Eager so a missing `hogql-parser-parity` dep group fails at script-load,
# not mid-grind where shrink_to_shape would lose every finding so far.
@@ -111,6 +115,23 @@ from posthog.hogql.test.test_parser_grammar_pbt import (
_apply_mutation,
)
+# ---------------------------------------------------------------------------
+# string_literal strategy
+# ---------------------------------------------------------------------------
+# No generated strategy (the unquoter isn't a grammar rule): build quoted literals over a branch-driving alphabet.
+_SL_QUOTE_PAIRS = [("'", "'"), ('"', '"'), ("`", "`"), ("{", "}")]
+# Excludes NUL: the cpp wheel's PyArg_ParseTuple("s") rejects it (ValueError) while PyO3's &str accepts it.
+_SL_ALPHABET = "'\"`{}\\bfrnt0avxyo ab\n\té£"
+
+
+def string_literal_strategy() -> st.SearchStrategy[str]:
+ body = st.text(alphabet=_SL_ALPHABET, max_size=12)
+ quoted = st.builds(lambda pair, b: pair[0] + b + pair[1], st.sampled_from(_SL_QUOTE_PAIRS), body)
+ # Raw never-empty forms (mismatched/unquoted) exercise the SyntaxError path; min_size=1 so cpp never sees "".
+ raw = st.text(alphabet=_SL_ALPHABET, min_size=1, max_size=14)
+ return st.one_of(quoted, raw)
+
+
# ---------------------------------------------------------------------------
# Auto-shrinker
# ---------------------------------------------------------------------------
@@ -158,7 +179,11 @@ def _print_failure_sample(
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--n", type=int, default=int(os.environ.get("N", "500")))
- parser.add_argument("--rule", choices=("expr", "select", "program", "full_template_string"), default="expr")
+ parser.add_argument(
+ "--rule",
+ choices=("expr", "select", "program", "full_template_string", "string_literal"),
+ default="expr",
+ )
parser.add_argument("--jiggle", action="store_true")
parser.add_argument(
"--mutate",
@@ -253,12 +278,15 @@ def main() -> int:
# abort the whole grind. Keyed by normalised `<ExcType>: …`.
crash_buckets: dict[str, list[str]] = {}
- base_strategy = {
+ # `Callable[..., ...]` so the no-arg `string_literal_strategy` and the `depth`-taking grammar strategies unify.
+ strategies_by_rule: dict[str, Callable[..., st.SearchStrategy[str]]] = {
"expr": expr_strategy,
"select": select_strategy,
"program": program_strategy,
"full_template_string": fullTemplateString_strategy,
- }[args.rule]()
+ "string_literal": string_literal_strategy,
+ }
+ base_strategy = strategies_by_rule[args.rule]()
strategy = base_strategy
# Grammar-aware mutation runs first, on the clean space-separated query —
# the whitespace jiggle below would otherwise break its tokenisation.
diff --git a/posthog/hogql/test/_test_parse_string.py b/posthog/hogql/test/_test_parse_string.py
index 84dd8c47c257..7c7ece2f8706 100644
--- a/posthog/hogql/test/_test_parse_string.py
+++ b/posthog/hogql/test/_test_parse_string.py
@@ -1,6 +1,9 @@
+from collections.abc import Callable
+
from posthog.test.base import BaseTest
from hogql_parser import parse_string_literal_text as parse_string_cpp
+from hogql_parser_rs import parse_string_literal_text as parse_string_rust
from posthog.hogql.constants import HogQLParserBackend
from posthog.hogql.errors import SyntaxError
@@ -8,7 +11,13 @@ from posthog.hogql.parse_string import parse_string_literal_text as parse_string
def parse_string_test_factory(backend: HogQLParserBackend):
- parse_string = parse_string_py if backend == "python" else parse_string_cpp
+ parse_string: Callable[[str], str]
+ if backend == "python":
+ parse_string = parse_string_py
+ elif backend.startswith("rust"):
+ parse_string = parse_string_rust
+ else:
+ parse_string = parse_string_cpp
class TestParseString(BaseTest):
def test_quote_types(self):
@@ -24,6 +33,12 @@ def parse_string_test_factory(backend: HogQLParserBackend):
self.assertEqual(parse_string("{a{{sd}"), "a{sd")
self.assertEqual(parse_string("{a}sd}"), "a}sd")
+ def test_quote_run_collapse(self):
+ # Odd/long quote runs pin sequential-replace semantics (rust str::replace vs cpp replace_all).
+ self.assertEqual(parse_string("''''''"), "''")
+ self.assertEqual(parse_string("'a'''b'"), "a''b")
+ self.assertEqual(parse_string("`a```b`"), "a``b")
+
def test_escaped_quotes_slash(self):
self.assertEqual(parse_string("`a\\`sd`"), "a`sd")
self.assertEqual(parse_string("'a\\'sd'"), "a'sd")
diff --git a/posthog/hogql/test/test_parse_string_rust.py b/posthog/hogql/test/test_parse_string_rust.py
new file mode 100644
index 000000000000..d72ce0d146c5
--- /dev/null
+++ b/posthog/hogql/test/test_parse_string_rust.py
@@ -0,0 +1,18 @@
+from unittest import TestCase
+
+from hogql_parser_rs import parse_string_literal_text
+
+from posthog.hogql.errors import ParsingError
+
+from ._test_parse_string import parse_string_test_factory
+
+
+class TestParseStringRust(parse_string_test_factory("rust-json")): # type: ignore
+ pass
+
+
+class TestParseStringRustEmptyInput(TestCase):
+ # Empty input can't go in the shared factory: cpp's wheel aborts the process on "", python raises SyntaxError.
+ def test_empty_input_raises_parsing_error(self):
+ with self.assertRaises(ParsingError):
+ parse_string_literal_text("")
diff --git a/pyproject.toml b/pyproject.toml
index 28ee2bbb7bd1..d5660d3a9478 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -68,7 +68,7 @@ dependencies = [
"grpcio~=1.71.0",
"gspread==6.2.1",
"hogql-parser==1.3.72",
- "hogql-parser-rs==1.3.96", # 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.99", # 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 00119b6c4003..e800d804f3bb 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -4359,7 +4359,7 @@ dependencies = [
[[package]]
name = "hogql_parser_rs"
-version = "1.3.96"
+version = "1.3.99"
dependencies = [
"pyo3",
"serde_json",
diff --git a/rust/hogql/parser/Cargo.toml b/rust/hogql/parser/Cargo.toml
index edc39286979b..1ebe7bbd95b3 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 (cpp is currently 1.3.72, this is 1.3.96); each ships as its own PyPI wheel.
-version = "1.3.96"
+# 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 (cpp is currently 1.3.72, this is 1.3.99); each ships as its own PyPI wheel.
+version = "1.3.99"
edition = "2021"
publish = false
diff --git a/rust/hogql/parser/pyproject.toml b/rust/hogql/parser/pyproject.toml
index 97e460e3062c..6ee63a9a1ec3 100644
--- a/rust/hogql/parser/pyproject.toml
+++ b/rust/hogql/parser/pyproject.toml
@@ -8,8 +8,8 @@ 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 (cpp is currently 1.3.72, this is 1.3.96).
-version = "1.3.96"
+# 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 (cpp is currently 1.3.72, this is 1.3.99).
+version = "1.3.99"
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/error.rs b/rust/hogql/parser/src/error.rs
index a0073107f1b1..94779b8500d0 100644
--- a/rust/hogql/parser/src/error.rs
+++ b/rust/hogql/parser/src/error.rs
@@ -28,13 +28,16 @@ pub struct ParseError {
pub enum ErrorKind {
Syntax,
NotImplemented,
+ /// Parser-layer error → `ParsingError` (cpp parity); emitted by `parse_string_literal_text` on empty input.
+ Parsing,
}
impl ErrorKind {
- fn type_str(self) -> &'static str {
+ pub(crate) fn type_str(self) -> &'static str {
match self {
ErrorKind::Syntax => "SyntaxError",
ErrorKind::NotImplemented => "NotImplementedError",
+ ErrorKind::Parsing => "ParsingError",
}
}
}
@@ -60,6 +63,16 @@ impl ParseError {
}
}
+ pub fn parsing(message: impl Into<String>, start: usize, end: usize) -> Self {
+ Self {
+ message: message.into(),
+ start,
+ end,
+ kind: ErrorKind::Parsing,
+ fatal: false,
+ }
+ }
+
/// 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 {
diff --git a/rust/hogql/parser/src/lib.rs b/rust/hogql/parser/src/lib.rs
index 00212777e2c0..d87f5087630f 100644
--- a/rust/hogql/parser/src/lib.rs
+++ b/rust/hogql/parser/src/lib.rs
@@ -164,6 +164,32 @@ fn parse_full_template_string_py(py: Python<'_>, string: &str) -> PyResult<PyObj
})
}
+/// Byte-for-byte twin of the C++ wheel's `parse_string_literal_text`, closing the last cpp/rust API gap.
+/// Errors route through the shared converter so `SyntaxError`/`ParsingError` match the C++ wheel's classes.
+#[pyfunction]
+fn parse_string_literal_text(py: Python<'_>, text: &str) -> PyResult<String> {
+ // catch_unwind like the other entry points: a future panic in the decoder must not cross FFI as a PanicException.
+ match std::panic::catch_unwind(AssertUnwindSafe(|| parse::parse_string_literal_text(text))) {
+ Ok(Ok(decoded)) => Ok(decoded),
+ Ok(Err(err)) => Err(raise_parse_error(py, err)),
+ Err(_) => Err(raise_parse_error(
+ py,
+ error::ParseError::not_implemented("internal panic in parse_string_literal_text", 0, 0),
+ )),
+ }
+}
+
+/// Raise the matching `posthog.hogql.errors` exception for `err`, importing only the errors module (not the AST/enum-laden `Converter`).
+fn raise_parse_error(py: Python<'_>, err: error::ParseError) -> PyErr {
+ pyobject::raise_error_envelope(
+ py,
+ err.kind.type_str(),
+ &err.message,
+ Some(err.start as u64),
+ Some(err.end as u64),
+ )
+}
+
#[pymodule]
fn hogql_parser_rs(m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_function(wrap_pyfunction!(parse_expr_json, m)?)?;
@@ -176,6 +202,7 @@ fn hogql_parser_rs(m: &Bound<'_, PyModule>) -> PyResult<()> {
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)?)?;
+ m.add_function(wrap_pyfunction!(parse_string_literal_text, m)?)?;
#[cfg(feature = "coverage")]
{
diff --git a/rust/hogql/parser/src/parse.rs b/rust/hogql/parser/src/parse.rs
index 5a18298a0ab7..292760235ad4 100644
--- a/rust/hogql/parser/src/parse.rs
+++ b/rust/hogql/parser/src/parse.rs
@@ -975,6 +975,117 @@ pub(crate) fn identifier_text(src: &str, kind: TokenKind) -> String {
}
}
+/// Lenient cpp `parse_string_literal_text` twin (`string.cpp`), exposed via PyO3 for cpp-wheel API parity.
+/// Accepts doubled + backslash-escaped quotes (4 quote types, incl. `{...}`) unlike the strict [`decode_quoted_body`].
+pub(crate) fn parse_string_literal_text(text: &str) -> Result<String, ParseError> {
+ if text.is_empty() {
+ return Err(ParseError::parsing(
+ "Encountered an unexpected empty string input",
+ 0,
+ 0,
+ ));
+ }
+ let bytes = text.as_bytes();
+ let first = bytes[0];
+ let last = bytes[bytes.len() - 1];
+ // Quote bytes are ASCII, so the byte 1/len-1 slice is char-boundary-safe; the `_` arm never slices.
+ let stripped = match (first, last) {
+ (b'\'', b'\'') => inner_between_quotes(text)
+ .replace("''", "'")
+ .replace("\\'", "'"),
+ (b'"', b'"') => inner_between_quotes(text)
+ .replace("\"\"", "\"")
+ .replace("\\\"", "\""),
+ (b'`', b'`') => inner_between_quotes(text)
+ .replace("``", "`")
+ .replace("\\`", "`"),
+ (b'{', b'}') => inner_between_quotes(text)
+ .replace("{{", "{")
+ .replace("\\{", "{"),
+ _ => {
+ return Err(ParseError::syntax(
+ format!(
+ "Invalid string literal, must start and end with the same quote type: {text}"
+ ),
+ 0,
+ 0,
+ ));
+ }
+ };
+ Ok(replace_common_escape_characters(&stripped))
+}
+
+/// Drop the surrounding quote bytes, cpp `substr(1, size-2)`-style: a length-1 input yields `""`, not a panic.
+fn inner_between_quotes(text: &str) -> &str {
+ if text.len() < 2 {
+ ""
+ } else {
+ &text[1..text.len() - 1]
+ }
+}
+
+/// Twin of cpp's `replace_common_escape_characters`: single pass, `\0` dropped, unknown `\X` keeps the backslash.
+fn replace_common_escape_characters(text: &str) -> String {
+ let mut out = String::with_capacity(text.len());
+ let mut chars = text.chars().peekable();
+ while let Some(c) = chars.next() {
+ if c == '\\' {
+ if let Some(&next) = chars.peek() {
+ match next {
+ 'b' => {
+ out.push('\u{08}');
+ chars.next();
+ continue;
+ }
+ 'f' => {
+ out.push('\u{0C}');
+ chars.next();
+ continue;
+ }
+ 'r' => {
+ out.push('\r');
+ chars.next();
+ continue;
+ }
+ 'n' => {
+ out.push('\n');
+ chars.next();
+ continue;
+ }
+ 't' => {
+ out.push('\t');
+ chars.next();
+ continue;
+ }
+ // cpp drops the NUL: `\0` consumes both and emits nothing.
+ '0' => {
+ chars.next();
+ continue;
+ }
+ 'a' => {
+ out.push('\u{07}');
+ chars.next();
+ continue;
+ }
+ 'v' => {
+ out.push('\u{0B}');
+ chars.next();
+ continue;
+ }
+ '\\' => {
+ out.push('\\');
+ chars.next();
+ continue;
+ }
+ _ => {}
+ }
+ }
+ }
+ out.push(c);
+ }
+ out
+}
+
/// Keywords accepted as the type-cast target on the `::` postfix. Maps to
/// the grammar's `columnTypeCastIdentifier` rule: IDENTIFIER /
/// QUOTED_IDENTIFIER / interval-units / `DATE` / `TIME` / `TIMESTAMP` /
@@ -1349,6 +1460,81 @@ fn build_char_offsets(src: &str) -> Vec<usize> {
#[cfg(test)]
mod tests {
use super::*;
+ use crate::error::ErrorKind;
+
+ /// Parity cases mirroring the DB-bound `_test_parse_string.py` factory, pinned DB-free here.
+ #[test]
+ fn parse_string_literal_text_matches_cpp() {
+ let f = |s: &str| parse_string_literal_text(s).expect("should decode");
+
+ // Quote types.
+ assert_eq!(f("`asd`"), "asd");
+ assert_eq!(f("'asd'"), "asd");
+ assert_eq!(f("\"asd\""), "asd");
+ assert_eq!(f("{asd}"), "asd");
+
+ // Doubled-quote escapes.
+ assert_eq!(f("`a``sd`"), "a`sd");
+ assert_eq!(f("'a''sd'"), "a'sd");
+ assert_eq!(f("\"a\"\"sd\""), "a\"sd");
+ assert_eq!(f("{a{{sd}"), "a{sd");
+ assert_eq!(f("{a}sd}"), "a}sd");
+
+ // Odd / long quote runs — pins str::replace against cpp's sequential replace_all.
+ assert_eq!(f("''''''"), "''");
+ assert_eq!(f("'a'''b'"), "a''b");
+ assert_eq!(f("`a```b`"), "a``b");
+
+ // Backslash-escaped quotes (the lenient form the strict in-parser decoder rejects).
+ assert_eq!(f("`a\\`sd`"), "a`sd");
+ assert_eq!(f("'a\\'sd'"), "a'sd");
+ assert_eq!(f("\"a\\\"sd\""), "a\"sd");
+ assert_eq!(f("{a\\{sd}"), "a{sd");
+
+ // Common escapes; `\0` is dropped.
+ assert_eq!(f("`a\nsd`"), "a\nsd");
+ assert_eq!(f("`a\\bsd`"), "a\u{08}sd");
+ assert_eq!(f("`a\\fsd`"), "a\u{0C}sd");
+ assert_eq!(f("`a\\rsd`"), "a\rsd");
+ assert_eq!(f("`a\\nsd`"), "a\nsd");
+ assert_eq!(f("`a\\tsd`"), "a\tsd");
+ assert_eq!(f("`a\\asd`"), "a\u{07}sd");
+ assert_eq!(f("`a\\vsd`"), "a\u{0B}sd");
+ assert_eq!(f("`a\\\\sd`"), "a\\sd");
+ assert_eq!(f("`a\\0sd`"), "asd");
+
+ // Unknown escapes keep the backslash.
+ assert_eq!(f("`a\\xsd`"), "a\\xsd");
+ assert_eq!(f("`a\\ysd`"), "a\\ysd");
+ assert_eq!(f("`a\\osd`"), "a\\osd");
+
+ // Backslash sequencing.
+ assert_eq!(f("`a\\\\nsd`"), "a\\nsd");
+ assert_eq!(f("`a\\\\n\\sd`"), "a\\n\\sd");
+ assert_eq!(f("`a\\\\n\\\\tsd`"), "a\\n\\tsd");
+
+ // Multibyte content survives the byte-level quote strip.
+ assert_eq!(f("`café`"), "café");
+ assert_eq!(f("{ünïcödé}"), "ünïcödé");
+ }
+
+ /// Mismatched quotes raise `SyntaxError`; empty input raises `ParsingError` (cpp's declared class).
+ #[test]
+ fn parse_string_literal_text_error_paths() {
+ let mismatched = parse_string_literal_text("`asd'").expect_err("mismatched quotes");
+ assert!(matches!(mismatched.kind, ErrorKind::Syntax));
+ assert_eq!(
+ mismatched.message,
+ "Invalid string literal, must start and end with the same quote type: `asd'"
+ );
+
+ let empty = parse_string_literal_text("").expect_err("empty input");
+ assert!(matches!(empty.kind, ErrorKind::Parsing));
+ assert_eq!(
+ empty.message,
+ "Encountered an unexpected empty string input"
+ );
+ }
/// `checkpoint` + `restore` on a freshly-constructed parser must
/// leave it indistinguishable from one constructed at the same
diff --git a/rust/hogql/parser/src/pyobject.rs b/rust/hogql/parser/src/pyobject.rs
index 3052e49837b1..a2d5c9eab3dd 100644
--- a/rust/hogql/parser/src/pyobject.rs
+++ b/rust/hogql/parser/src/pyobject.rs
@@ -9,12 +9,45 @@ 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.
+/// 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.
+pub(crate) fn raise_error_envelope(
+ py: Python<'_>,
+ error_type: &str,
+ message: &str,
+ start: Option<u64>,
+ end: Option<u64>,
+) -> PyErr {
+ let errors_module = match py.import_bound("posthog.hogql.errors") {
+ Ok(m) => m,
+ Err(e) => return e,
+ };
+ let cls_name = match error_type {
+ "SyntaxError" => "SyntaxError",
+ "ParsingError" => "ParsingError",
+ _ => "ExposedHogQLError",
+ };
+ let cls = match errors_module.getattr(cls_name) {
+ Ok(c) => c,
+ Err(e) => return e,
+ };
+ let kwargs = PyDict::new_bound(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]);
+ match cls.call(&args, Some(&kwargs)) {
+ Ok(exc) => PyErr::from_value_bound(exc),
+ Err(e) => e,
+ }
+}
+
+/// Cached refs: AST module, 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.
@@ -24,24 +57,19 @@ pub struct Converter<'py> {
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.
+ /// 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> {
self.convert(value)
}
@@ -208,24 +236,7 @@ impl<'py> Converter<'py> {
.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,
- }
+ raise_error_envelope(self.py, error_type, message, start, end)
}
/// 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`.
diff --git a/uv.lock b/uv.lock
index 0a587af42857..857dd7adf780 100644
--- a/uv.lock
+++ b/uv.lock
@@ -11,7 +11,7 @@ resolution-markers = [
]
[options]
-exclude-newer = "2026-06-15T10:42:02.393902Z"
+exclude-newer = "0001-01-01T00:00:00Z" # This has no effect and is included for backwards compatibility when using relative exclude-newer values.
exclude-newer-span = "P7D"
[options.exclude-newer-package]
@@ -3145,16 +3145,16 @@ wheels = [
[[package]]
name = "hogql-parser-rs"
-version = "1.3.96"
+version = "1.3.99"
source = { registry = "https://pypi.org/simple" }
-sdist = { url = "https://files.pythonhosted.org/packages/96/60/cac3721a48f28bdfa77db1db58648fb1549403d7046049d1cdc824996103/hogql_parser_rs-1.3.96.tar.gz", hash = "sha256:3816a9cf46402613de5f091cacb53bd7ef47ef75a07b3883a8cf751ba8205b96", size = 299083, upload-time = "2026-06-19T14:47:07.992Z" }
+sdist = { url = "https://files.pythonhosted.org/packages/19/89/3724e75e34ebcf5309f05ff3d2dd8f85ef84bbc21bd385f98f16689c9ae3/hogql_parser_rs-1.3.99.tar.gz", hash = "sha256:aaf8cbbf3d9e77706b3c8b35f016a3b39da6529f8172b1dccc5a7ed6b5489728", size = 301257, upload-time = "2026-06-23T16:17:47.323Z" }
wheels = [
- { url = "https://files.pythonhosted.org/packages/13/2d/a61b36fc1182663666a61852f5707407a66a1098d646aff32cb823b0abec/hogql_parser_rs-1.3.96-cp312-abi3-macosx_10_12_x86_64.whl", hash = "sha256:54a3fde8bff8b7520fd6d694ad3d7b0f2a9fbf31b011138d0a792e1d11f6a8b4", size = 737814, upload-time = "2026-06-19T14:46:58.479Z" },
- { url = "https://files.pythonhosted.org/packages/24/2f/20bce1c5e9f36d7ef091c68ec336f378c9642649d0ffde4fa4ddd270b44d/hogql_parser_rs-1.3.96-cp312-abi3-macosx_11_0_arm64.whl", hash = "sha256:71532f82f48346a214eab561aa507a9af141dac4c58197bdddbb8026f555f353", size = 691868, upload-time = "2026-06-19T14:47:00.141Z" },
- { url = "https://files.pythonhosted.org/packages/45/4d/e6e2d27d36faf02716137e74345900890d1214f5780435870d7d46d0e1f8/hogql_parser_rs-1.3.96-cp312-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:9d20d0b614b73755c7ab371dd0cb35880dff6aa1760ba02f22aebf31d629306a", size = 2491584, upload-time = "2026-06-19T14:47:01.56Z" },
- { url = "https://files.pythonhosted.org/packages/b3/85/93deb3367b6ed59eedb4df973c4d896643af221c061a508c8e1336923c4d/hogql_parser_rs-1.3.96-cp312-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:1506600700ea429cd143bfdfe1202f9a2a9125ac07b7dbe396bba30751bdde36", size = 2755411, upload-time = "2026-06-19T14:47:02.955Z" },
- { url = "https://files.pythonhosted.org/packages/47/ff/f0964b0dc341e8e0b07c7b27e79cc87da0c411b837bad1bf756f173d8dc7/hogql_parser_rs-1.3.96-cp312-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:e4616e02a46c607855c62ba91c76fb7a2201b3b478aa745c47b0f805a7b60fdf", size = 2663214, upload-time = "2026-06-19T14:47:04.623Z" },
- { url = "https://files.pythonhosted.org/packages/b4/9d/9f48796c76ad3e6ad5beb97d36e558f1ccb10196730ddbd6c41d9975c0e3/hogql_parser_rs-1.3.96-cp312-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:80db7f3ccb2d55fa748c6f12400c9f1c11aabc835aa4ec330332e630e32a71c1", size = 2714547, upload-time = "2026-06-19T14:47:06.476Z" },
+ { url = "https://files.pythonhosted.org/packages/69/b0/7d4d58eea85de62802baaeb32c36b3c6c759966d6bf7d86a7cd0592e19c3/hogql_parser_rs-1.3.99-cp312-abi3-macosx_10_12_x86_64.whl", hash = "sha256:03bc570d3febd063e13619f69630f1ca979a4eeb65648611b0a0636db500fd0a", size = 741679, upload-time = "2026-06-23T16:17:36.031Z" },
+ { url = "https://files.pythonhosted.org/packages/ea/79/ff03eb9dbc1a49eb1ce9798e357d6c70756965d53ab7c0f281871020d7c9/hogql_parser_rs-1.3.99-cp312-abi3-macosx_11_0_arm64.whl", hash = "sha256:27790a9533636a0cbe00edc62ac1df882a08f503ea35ce01f519a76a7738ad6c", size = 698323, upload-time = "2026-06-23T16:17:37.838Z" },
+ { url = "https://files.pythonhosted.org/packages/60/16/4bd3ef88afdfc9eab8fdb0f50d3f5c28f74c0de034513005aa9dea1be120/hogql_parser_rs-1.3.99-cp312-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:211db8cdc9b996b85f945a92ccc2716f4ae39d4bcce4c3b80d76b4a8ddd9ec3b", size = 2501932, upload-time = "2026-06-23T16:17:40.181Z" },
+ { url = "https://files.pythonhosted.org/packages/21/a5/6c26c5af1d47e9be5077149bbf5d67d3d80ea23e766018164b87d9a89353/hogql_parser_rs-1.3.99-cp312-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:c8639d89da19b8760e5b89a79ac4b37d52272f45d61c5b7f78f65cecf171f275", size = 2763536, upload-time = "2026-06-23T16:17:42.159Z" },
+ { url = "https://files.pythonhosted.org/packages/f5/38/154333afcab0b24ff9c34e6058ad3d208daa2c9749f463dac8f036cb0f90/hogql_parser_rs-1.3.99-cp312-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:334a43a4dd4488e578efa7fc79198399acc8eca8d20b736788eb291108d5888c", size = 2675863, upload-time = "2026-06-23T16:17:43.839Z" },
+ { url = "https://files.pythonhosted.org/packages/8f/a6/e984a79999a15dedb70140ba72a658863927d239bc94052c468656fa1254/hogql_parser_rs-1.3.99-cp312-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:0b2f18f897dfd0467980e4e21a5889ccf727fa24d9ec10d8995e280151f16284", size = 2725837, upload-time = "2026-06-23T16:17:45.703Z" },
]
[[package]]
@@ -5865,7 +5865,7 @@ requires-dist = [
{ name = "grpcio", specifier = "~=1.71.0" },
{ name = "gspread", specifier = "==6.2.1" },
{ name = "hogql-parser", specifier = "==1.3.72" },
- { name = "hogql-parser-rs", specifier = "==1.3.96" },
+ { name = "hogql-parser-rs", specifier = "==1.3.99" },
{ 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" },