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.

fix(hogql): align rust parser with cpp on divergences from template string, mysql grammar, prod shadow mode (#64158)

Robbiede25074d800f
diff --git a/posthog/hogql/scripts/_diagnostic_common.py b/posthog/hogql/scripts/_diagnostic_common.py
index 78ab3bb64385..cc4dd58c3a51 100644
--- a/posthog/hogql/scripts/_diagnostic_common.py
+++ b/posthog/hogql/scripts/_diagnostic_common.py
@@ -30,6 +30,7 @@ import os
import re
import sys
import json
+import math
import signal
import traceback
import subprocess
@@ -40,16 +41,37 @@ from pathlib import Path
from typing import Any, NoReturn
from posthog.hogql.errors import BaseHogQLError
-from posthog.hogql.parser import HogQLParserShadowMismatch, parse_expr, parse_program, parse_select
+from posthog.hogql.parser import (
+ HogQLParserShadowMismatch,
+ parse_expr,
+ parse_program,
+ parse_select,
+ parse_string_template,
+)
from posthog.hogql.visitor import clear_locations
+
+def _parse_full_template_string(query: str, backend: Any = None) -> Any:
+ """Entry point for the `full_template_string` rule. The `fullTemplateString`
+ grammar strategy emits the `F'…` form (`QUOTE_SINGLE_TEMPLATE_FULL` then the
+ body, no closing quote), but `parse_string_template` takes only the body and
+ re-adds the `F'` itself — so strip the leading `F'`. Mirrors the pytest PBT
+ (`test_parser_grammar_pbt.py`)."""
+ body = query[2:] if query.startswith("F'") else query
+ return parse_string_template(body, backend=backend)
+
+
# 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).
+# fn / try-catch / return / throw / blocks); `full_template_string` is the
+# standalone `F'…` template parser (`parse_string_template`), a separate
+# EOF-terminated grammar entry that inline `f'…` columnExpr templates don't
+# exercise.
_PARSER_FOR_RULE: dict[str, Callable[..., Any]] = {
"expr": parse_expr,
"select": parse_select,
"program": parse_program,
+ "full_template_string": _parse_full_template_string,
}
# ---------------------------------------------------------------------------
@@ -72,6 +94,41 @@ def _node_fields(node: Any) -> list[tuple[str, Any]]:
return [(f.name, getattr(node, f.name, None)) for f in dataclasses.fields(node)]
+def _nan_tolerant_equal(a: Any, b: Any, depth: int = 0) -> bool:
+ """Deep structural equality that treats two NaNs as equal (`float("nan") !=
+ float("nan")`) and otherwise defers to `==`, which already treats a str-enum
+ member as equal to its value (`CompareOperationOp.Eq == '=='`). Needed because
+ cpp-json leaves enum-shaped fields (`op`) as raw strings while rust-py emits
+ the enum, so an AST carrying BOTH a NaN constant AND such a field satisfies
+ neither dataclass `==` (NaN) nor `repr` equality (str vs enum) even though the
+ two parses are identical. Only ever upgrades a mismatch to agreement — a real
+ structural / positional / value difference still surfaces."""
+ if depth > 80:
+ return repr(a) == repr(b)
+ if isinstance(a, float) and isinstance(b, float):
+ return a == b or (math.isnan(a) and math.isnan(b))
+ if isinstance(a, list) and isinstance(b, list):
+ return len(a) == len(b) and all(_nan_tolerant_equal(x, y, depth + 1) for x, y in zip(a, b))
+ if isinstance(a, dict) and isinstance(b, dict):
+ return set(a) == set(b) and all(_nan_tolerant_equal(a[k], b[k], depth + 1) for k in a)
+ if dataclasses.is_dataclass(a) and dataclasses.is_dataclass(b):
+ return type(a) is type(b) and all(
+ _nan_tolerant_equal(getattr(a, f.name, None), getattr(b, f.name, None), depth + 1)
+ for f in dataclasses.fields(a)
+ )
+ return bool(a == b)
+
+
+def asts_agree(oracle: Any, candidate: Any) -> bool:
+ """True when two parsed ASTs are equivalent. Mirrors the production shadow
+ comparison in `posthog/hogql/parser.py` (dataclass `==`), then falls back to
+ a NaN-tolerant deep walk so a NaN-bearing AST doesn't read as a spurious
+ mismatch (`float("nan") != float("nan")`) — including when an enum-vs-str
+ field rules out the simpler `repr()` equality. Only ever upgrades a mismatch
+ to agreement, so it can't mask a real structural / positional divergence."""
+ return oracle == candidate or _nan_tolerant_equal(oracle, candidate)
+
+
def _diff_path(oracle: Any, candidate: Any, path: list | None = None, depth: int = 0) -> list:
"""Walk both ASTs together; return the `.field` / `[i]` breadcrumbs
from root to the first divergence, terminating with a 3-tuple
@@ -385,7 +442,7 @@ def _shape_for(
return DivergenceShape(kind="candidate_reject", reject_signature=c_detail)
if c_status == "crash":
return None
- if o_ast == c_ast:
+ if asts_agree(o_ast, c_ast):
return None
return _ast_mismatch_shape((_node_type(o_ast), _node_type(c_ast)), _diff_path(o_ast, c_ast))
@@ -833,7 +890,7 @@ def run_corpus_parity(
crash_buckets[crash_signature(c_detail or "")] += 1
failures.append(Failure("candidate_crash", query, c_detail or "<no traceback>", n_occ))
continue
- if o_ast == c_ast:
+ if asts_agree(o_ast, c_ast):
counts["pass"] += 1
continue
counts["ast_mismatch"] += 1
diff --git a/posthog/hogql/scripts/pbt_diagnostic.py b/posthog/hogql/scripts/pbt_diagnostic.py
index 19fc4c174bef..3b524dc29899 100644
--- a/posthog/hogql/scripts/pbt_diagnostic.py
+++ b/posthog/hogql/scripts/pbt_diagnostic.py
@@ -95,9 +95,15 @@ from posthog.hogql.scripts._diagnostic_common import (
_node_type,
_probe_backend,
_safe_parse,
+ asts_agree,
shrink_to_shape,
)
-from posthog.hogql.test._generated_grammar_strategies import expr_strategy, program_strategy, select_strategy
+from posthog.hogql.test._generated_grammar_strategies import (
+ expr_strategy,
+ fullTemplateString_strategy,
+ program_strategy,
+ select_strategy,
+)
from posthog.hogql.test.test_parser_grammar_pbt import (
_PBT_SETTINGS,
_apply_grammar_mutation,
@@ -152,7 +158,7 @@ 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"), default="expr")
+ parser.add_argument("--rule", choices=("expr", "select", "program", "full_template_string"), default="expr")
parser.add_argument("--jiggle", action="store_true")
parser.add_argument(
"--mutate",
@@ -251,6 +257,7 @@ def main() -> int:
"expr": expr_strategy,
"select": select_strategy,
"program": program_strategy,
+ "full_template_string": fullTemplateString_strategy,
}[args.rule]()
strategy = base_strategy
# Grammar-aware mutation runs first, on the clean space-separated query —
@@ -384,7 +391,7 @@ def main() -> int:
)
return
- if o_ast == c_ast:
+ if asts_agree(o_ast, c_ast):
counts["match"] += 1
return
diff --git a/posthog/hogql/test/__snapshots__/parser_ast.ambr b/posthog/hogql/test/__snapshots__/parser_ast.ambr
index 0a3206f2e535..e772b335ab05 100644
--- a/posthog/hogql/test/__snapshots__/parser_ast.ambr
+++ b/posthog/hogql/test/__snapshots__/parser_ast.ambr
@@ -2093,6 +2093,62 @@
}
'''
# ---
+# name: test_cast_type_param_admits_date_literal_as_raw_text[cast_0_as_a_a_date_date-686a8c1d]
+ '''
+ {
+ end: 37
+ expr: {
+ end: 6
+ start: 5
+ value: 0
+ }
+ start: 0
+ type_name: "a(a(date'', date''))"
+ }
+ '''
+# ---
+# name: test_cast_type_param_admits_date_literal_as_raw_text[cast_0_as_a_date-62774d40]
+ '''
+ {
+ end: 21
+ expr: {
+ end: 6
+ start: 5
+ value: 0
+ }
+ start: 0
+ type_name: "a(date'')"
+ }
+ '''
+# ---
+# name: test_cast_type_param_admits_date_literal_as_raw_text[cast_0_as_a_date_date-58ea95cb]
+ '''
+ {
+ end: 32
+ expr: {
+ end: 6
+ start: 5
+ value: 0
+ }
+ start: 0
+ type_name: "a(date'', date'')"
+ }
+ '''
+# ---
+# name: test_cast_type_param_admits_date_literal_as_raw_text[cast_0_as_a_timestamp-a5dc2724]
+ '''
+ {
+ end: 26
+ expr: {
+ end: 6
+ start: 5
+ value: 0
+ }
+ start: 0
+ type_name: "a(timestamp'')"
+ }
+ '''
+# ---
# name: test_cast_type_param_group_mode_classification[cast_x_as_DateTime64_3_UTC-416fe76a]
'''
{
@@ -2657,26 +2713,460 @@
}
'''
# ---
-# name: test_columns_replace_item_name_is_the_as_keyword[replace_a_as_b_as_as-26f77129]
+# name: test_columns_replace_item_name_is_the_as_keyword[replace_a_as_b_as_as-26f77129]
+ '''
+ {
+ all_columns: True
+ end: 25
+ replace: {
+ as: {
+ alias: "b"
+ end: 17
+ expr: {
+ chain: [
+ "a"
+ ]
+ end: 12
+ from_asterisk: False
+ start: 11
+ }
+ from_asterisk: False
+ hidden: False
+ start: 11
+ }
+ }
+ start: 0
+ }
+ '''
+# ---
+# name: test_cross_join_after_join_on_constraint[SELECT_0_FROM_a_JOIN_a_ON_a_a-a7392f7f]
+ '''
+ {
+ end: 33
+ select: [
+ {
+ end: 8
+ start: 7
+ value: 0
+ }
+ ]
+ select_from: {
+ end: 15
+ next_join: {
+ constraint: {
+ constraint_type: "ON"
+ end: 28
+ expr: {
+ end: 28
+ start: 26
+ value: ""
+ }
+ start: 23
+ }
+ end: 22
+ join_type: "JOIN"
+ next_join: {
+ alias: "a"
+ end: 33
+ join_type: "CROSS JOIN"
+ start: 30
+ table: {
+ chain: [
+ "a"
+ ]
+ end: 31
+ from_asterisk: False
+ start: 30
+ }
+ }
+ start: 21
+ table: {
+ chain: [
+ "a"
+ ]
+ end: 22
+ from_asterisk: False
+ start: 21
+ }
+ }
+ start: 14
+ table: {
+ chain: [
+ "a"
+ ]
+ end: 15
+ from_asterisk: False
+ start: 14
+ }
+ }
+ start: 0
+ }
+ '''
+# ---
+# name: test_cross_join_after_join_on_constraint[SELECT_0_FROM_a_JOIN_a_ON_x_y_b_b-67d4e208]
+ '''
+ {
+ end: 36
+ select: [
+ {
+ end: 8
+ start: 7
+ value: 0
+ }
+ ]
+ select_from: {
+ end: 15
+ next_join: {
+ constraint: {
+ constraint_type: "ON"
+ end: 31
+ expr: {
+ end: 31
+ left: {
+ chain: [
+ "x"
+ ]
+ end: 27
+ from_asterisk: False
+ start: 26
+ }
+ op: "=="
+ right: {
+ chain: [
+ "y"
+ ]
+ end: 31
+ from_asterisk: False
+ start: 30
+ }
+ start: 26
+ }
+ start: 23
+ }
+ end: 22
+ join_type: "JOIN"
+ next_join: {
+ alias: "b"
+ end: 36
+ join_type: "CROSS JOIN"
+ start: 33
+ table: {
+ chain: [
+ "b"
+ ]
+ end: 34
+ from_asterisk: False
+ start: 33
+ }
+ }
+ start: 21
+ table: {
+ chain: [
+ "a"
+ ]
+ end: 22
+ from_asterisk: False
+ start: 21
+ }
+ }
+ start: 14
+ table: {
+ chain: [
+ "a"
+ ]
+ end: 15
+ from_asterisk: False
+ start: 14
+ }
+ }
+ start: 0
+ }
+ '''
+# ---
+# name: test_cross_join_after_join_on_constraint[SELECT_1_FROM_a_JOIN_b_ON_1_c_c-18367b47]
+ '''
+ {
+ end: 32
+ select: [
+ {
+ end: 8
+ start: 7
+ value: 1
+ }
+ ]
+ select_from: {
+ end: 15
+ next_join: {
+ constraint: {
+ constraint_type: "ON"
+ end: 27
+ expr: {
+ end: 27
+ start: 26
+ value: 1
+ }
+ start: 23
+ }
+ end: 22
+ join_type: "JOIN"
+ next_join: {
+ alias: "c"
+ end: 32
+ join_type: "CROSS JOIN"
+ start: 29
+ table: {
+ chain: [
+ "c"
+ ]
+ end: 30
+ from_asterisk: False
+ start: 29
+ }
+ }
+ start: 21
+ table: {
+ chain: [
+ "b"
+ ]
+ end: 22
+ from_asterisk: False
+ start: 21
+ }
+ }
+ start: 14
+ table: {
+ chain: [
+ "a"
+ ]
+ end: 15
+ from_asterisk: False
+ start: 14
+ }
+ }
+ start: 0
+ }
+ '''
+# ---
+# name: test_cross_join_after_join_on_constraint[SELECT_FROM_a_JOIN_b_ON_x_select_1_s-124faa4f]
+ '''
+ {
+ end: 41
+ select: [
+ {
+ chain: [
+ "*"
+ ]
+ end: 8
+ from_asterisk: False
+ start: 7
+ }
+ ]
+ select_from: {
+ end: 15
+ next_join: {
+ constraint: {
+ constraint_type: "ON"
+ end: 27
+ expr: {
+ chain: [
+ "x"
+ ]
+ end: 27
+ from_asterisk: False
+ start: 26
+ }
+ start: 23
+ }
+ end: 22
+ join_type: "JOIN"
+ next_join: {
+ alias: "s"
+ end: 41
+ join_type: "CROSS JOIN"
+ start: 29
+ table: {
+ end: 38
+ select: [
+ {
+ end: 38
+ start: 37
+ value: 1
+ }
+ ]
+ start: 30
+ }
+ }
+ start: 21
+ table: {
+ chain: [
+ "b"
+ ]
+ end: 22
+ from_asterisk: False
+ start: 21
+ }
+ }
+ start: 14
+ table: {
+ chain: [
+ "a"
+ ]
+ end: 15
+ from_asterisk: False
+ start: 14
+ }
+ }
+ start: 0
+ }
+ '''
+# ---
+# name: test_cross_join_after_join_on_constraint[SELECT_FROM_a_JOIN_b_ON_x_y_FINAL-03644779]
+ '''
+ {
+ end: 36
+ select: [
+ {
+ chain: [
+ "*"
+ ]
+ end: 8
+ from_asterisk: False
+ start: 7
+ }
+ ]
+ select_from: {
+ end: 15
+ next_join: {
+ constraint: {
+ constraint_type: "ON"
+ end: 27
+ expr: {
+ chain: [
+ "x"
+ ]
+ end: 27
+ from_asterisk: False
+ start: 26
+ }
+ start: 23
+ }
+ end: 22
+ join_type: "JOIN"
+ next_join: {
+ end: 36
+ join_type: "CROSS JOIN"
+ start: 29
+ table: {
+ chain: [
+ "y"
+ ]
+ end: 30
+ from_asterisk: False
+ start: 29
+ }
+ table_final: True
+ }
+ start: 21
+ table: {
+ chain: [
+ "b"
+ ]
+ end: 22
+ from_asterisk: False
+ start: 21
+ }
+ }
+ start: 14
+ table: {
+ chain: [
+ "a"
+ ]
+ end: 15
+ from_asterisk: False
+ start: 14
+ }
+ }
+ start: 0
+ }
+ '''
+# ---
+# name: test_cross_join_after_join_on_constraint[SELECT_FROM_a_JOIN_b_ON_x_y_z_w-431f4637]
'''
{
- all_columns: True
- end: 25
- replace: {
- as: {
- alias: "b"
- end: 17
- expr: {
+ end: 35
+ select: [
+ {
+ chain: [
+ "*"
+ ]
+ end: 8
+ from_asterisk: False
+ start: 7
+ }
+ ]
+ select_from: {
+ end: 15
+ next_join: {
+ constraint: {
+ constraint_type: "ON"
+ end: 27
+ expr: {
+ chain: [
+ "x"
+ ]
+ end: 27
+ from_asterisk: False
+ start: 26
+ }
+ start: 23
+ }
+ end: 22
+ join_type: "JOIN"
+ next_join: {
+ alias: "z"
+ end: 32
+ join_type: "CROSS JOIN"
+ next_join: {
+ end: 35
+ join_type: "CROSS JOIN"
+ start: 34
+ table: {
+ chain: [
+ "w"
+ ]
+ end: 35
+ from_asterisk: False
+ start: 34
+ }
+ }
+ start: 29
+ table: {
+ chain: [
+ "y"
+ ]
+ end: 30
+ from_asterisk: False
+ start: 29
+ }
+ }
+ start: 21
+ table: {
chain: [
- "a"
+ "b"
]
- end: 12
+ end: 22
from_asterisk: False
- start: 11
+ start: 21
}
+ }
+ start: 14
+ table: {
+ chain: [
+ "a"
+ ]
+ end: 15
from_asterisk: False
- hidden: False
- start: 11
+ start: 14
}
}
start: 0
@@ -3625,20 +4115,246 @@
}
}
]
- end: 41
- include_nulls: False
- start: 15
- table: {
- chain: [
- "t"
- ]
- end: 16
- from_asterisk: False
- start: 15
- }
+ end: 41
+ include_nulls: False
+ start: 15
+ table: {
+ chain: [
+ "t"
+ ]
+ end: 16
+ from_asterisk: False
+ start: 15
+ }
+ }
+ table_final: True
+ }
+ start: 0
+ }
+ '''
+# ---
+# name: test_distinct_with_empty_parens_is_a_function_call[SELECT_distinct-1e756ee3]
+ '''
+ {
+ end: 17
+ select: [
+ {
+ args: []
+ distinct: False
+ end: 17
+ name: "distinct"
+ start: 7
+ }
+ ]
+ start: 0
+ }
+ '''
+# ---
+# name: test_distinct_with_empty_parens_is_a_function_call[SELECT_distinct_FROM_a-4a6b925e]
+ '''
+ {
+ end: 24
+ select: [
+ {
+ args: []
+ distinct: False
+ end: 17
+ name: "distinct"
+ start: 7
+ }
+ ]
+ select_from: {
+ end: 24
+ start: 23
+ table: {
+ chain: [
+ "a"
+ ]
+ end: 24
+ from_asterisk: False
+ start: 23
+ }
+ }
+ start: 0
+ }
+ '''
+# ---
+# name: test_distinct_with_empty_parens_is_a_function_call[SELECT_distinct_x-5ba596b3]
+ '''
+ {
+ distinct: True
+ end: 18
+ select: [
+ {
+ chain: [
+ "x"
+ ]
+ end: 17
+ from_asterisk: False
+ start: 16
+ }
+ ]
+ start: 0
+ }
+ '''
+# ---
+# name: test_distinct_with_empty_parens_is_a_function_call[SELECT_distinct_x_y-53d4dfad]
+ '''
+ {
+ distinct: True
+ end: 21
+ select: [
+ {
+ chain: [
+ "x"
+ ]
+ end: 17
+ from_asterisk: False
+ start: 16
+ },
+ {
+ chain: [
+ "y"
+ ]
+ end: 21
+ from_asterisk: False
+ start: 20
+ }
+ ]
+ start: 0
+ }
+ '''
+# ---
+# name: test_distinct_with_empty_parens_is_a_function_call[count_distinct-a497c582]
+ '''
+ {
+ args: [
+ {
+ args: []
+ distinct: False
+ end: 16
+ name: "distinct"
+ start: 6
+ }
+ ]
+ distinct: False
+ end: 17
+ name: "count"
+ start: 0
+ }
+ '''
+# ---
+# name: test_distinct_with_empty_parens_is_a_function_call[count_distinct_1-bd3399dd]
+ '''
+ {
+ args: [
+ {
+ end: 20
+ left: {
+ args: []
+ distinct: False
+ end: 16
+ name: "distinct"
+ start: 6
+ }
+ op: "+"
+ right: {
+ end: 20
+ start: 19
+ value: 1
+ }
+ start: 6
+ }
+ ]
+ distinct: False
+ end: 21
+ name: "count"
+ start: 0
+ }
+ '''
+# ---
+# name: test_distinct_with_empty_parens_is_a_function_call[count_distinct_x-89c223b1]
+ '''
+ {
+ args: [
+ {
+ chain: [
+ "x"
+ ]
+ end: 16
+ from_asterisk: False
+ start: 15
+ }
+ ]
+ distinct: True
+ end: 18
+ name: "count"
+ start: 0
+ }
+ '''
+# ---
+# name: test_distinct_with_empty_parens_is_a_function_call[count_distinct_x-ba7e2428]
+ '''
+ {
+ args: [
+ {
+ chain: [
+ "x"
+ ]
+ end: 16
+ from_asterisk: False
+ start: 15
+ }
+ ]
+ distinct: True
+ end: 17
+ name: "count"
+ start: 0
+ }
+ '''
+# ---
+# name: test_distinct_with_empty_parens_is_a_function_call[f_distinct-390b20d3]
+ '''
+ {
+ args: [
+ {
+ args: []
+ distinct: False
+ end: 12
+ name: "distinct"
+ start: 2
+ }
+ ]
+ distinct: False
+ end: 13
+ name: "f"
+ start: 0
+ }
+ '''
+# ---
+# name: test_distinct_with_empty_parens_is_a_function_call[f_x_distinct-55bb2ea1]
+ '''
+ {
+ args: [
+ {
+ chain: [
+ "x"
+ ]
+ end: 3
+ from_asterisk: False
+ start: 2
+ },
+ {
+ args: []
+ distinct: False
+ end: 15
+ name: "distinct"
+ start: 5
}
- table_final: True
- }
+ ]
+ distinct: False
+ end: 16
+ name: "f"
start: 0
}
'''
@@ -3876,6 +4592,33 @@
}
'''
# ---
+# name: test_full_template_string_empty_body_span[1-4927ce04]
+ '''
+ {
+ end: 4
+ start: 3
+ value: 1
+ }
+ '''
+# ---
+# name: test_full_template_string_empty_body_span[da39a3ee]
+ '''
+ {
+ end: 2
+ start: 0
+ value: ""
+ }
+ '''
+# ---
+# name: test_full_template_string_empty_body_span[x-11f6ad8e]
+ '''
+ {
+ end: 3
+ start: 2
+ value: "x"
+ }
+ '''
+# ---
# name: test_group_by_all_falls_back_to_columns_on_postfix[SELECT_a_FROM_t_GROUP_BY_ALL-b4b19bc3]
'''
{
@@ -5013,19 +5756,213 @@
}
'''
# ---
-# name: test_hogqlx_tag_text_accepts_arbitrary_non_brace_non_lt[a_1_2_a-89f59c93]
+# name: test_hogqlx_tag_text_accepts_arbitrary_non_brace_non_lt[a_1_2_a-89f59c93]
+ '''
+ {
+ attributes: [
+ {
+ name: "children"
+ value: [
+ {
+ end: 8
+ start: 3
+ value: "1 + 2"
+ }
+ ]
+ }
+ ]
+ end: 12
+ kind: "a"
+ start: 0
+ }
+ '''
+# ---
+# name: test_hogqlx_tag_text_accepts_arbitrary_non_brace_non_lt[a_a-ce80326f]
+ '''
+ {
+ attributes: [
+ {
+ name: "children"
+ value: [
+ {
+ end: 11
+ start: 3
+ value: "!@#%^*()"
+ }
+ ]
+ }
+ ]
+ end: 15
+ kind: "a"
+ start: 0
+ }
+ '''
+# ---
+# name: test_hogqlx_tag_text_accepts_arbitrary_non_brace_non_lt[a_foo_a-016dc367]
+ '''
+ {
+ attributes: [
+ {
+ name: "children"
+ value: [
+ {
+ end: 7
+ start: 3
+ value: "foo!"
+ }
+ ]
+ }
+ ]
+ end: 11
+ kind: "a"
+ start: 0
+ }
+ '''
+# ---
+# name: test_hogqlx_tag_text_accepts_arbitrary_non_brace_non_lt[a_foo_bar_a-2724e3a6]
+ '''
+ {
+ attributes: [
+ {
+ name: "children"
+ value: [
+ {
+ end: 10
+ start: 3
+ value: "foo@bar"
+ }
+ ]
+ }
+ ]
+ end: 14
+ kind: "a"
+ start: 0
+ }
+ '''
+# ---
+# name: test_hogqlx_tag_text_accepts_arbitrary_non_brace_non_lt[a_foo_bar_a-44116ebf]
+ '''
+ {
+ attributes: [
+ {
+ name: "children"
+ value: [
+ {
+ end: 10
+ start: 3
+ value: "foo&bar"
+ }
+ ]
+ }
+ ]
+ end: 14
+ kind: "a"
+ start: 0
+ }
+ '''
+# ---
+# name: test_hogqlx_tag_text_accepts_arbitrary_non_brace_non_lt[outer_inner_foo_bar_inner_baz_qux_outer-ed8b2082]
+ '''
+ {
+ attributes: [
+ {
+ name: "children"
+ value: [
+ {
+ attributes: [
+ {
+ name: "children"
+ value: [
+ {
+ end: 21
+ start: 14
+ value: "foo!bar"
+ }
+ ]
+ }
+ ]
+ end: 29
+ kind: "inner"
+ start: 7
+ },
+ {
+ end: 36
+ start: 29
+ value: "baz&qux"
+ }
+ ]
+ }
+ ]
+ end: 44
+ kind: "outer"
+ start: 0
+ }
+ '''
+# ---
+# name: test_hogqlx_tight_vs_loose_tags[a_a-10320115]
+ '''
+ {
+ attributes: []
+ end: 11
+ kind: "a"
+ start: 0
+ }
+ '''
+# ---
+# name: test_hogqlx_tight_vs_loose_tags[a_a-c1b9c988]
+ '''
+ {
+ attributes: [
+ {
+ name: "children"
+ value: [
+ {
+ end: 4
+ start: 3
+ value: " "
+ }
+ ]
+ }
+ ]
+ end: 8
+ kind: "a"
+ start: 0
+ }
+ '''
+# ---
+# name: test_hogqlx_tight_vs_loose_tags[a_a-f61bc7e2]
+ '''
+ {
+ attributes: []
+ end: 7
+ kind: "a"
+ start: 0
+ }
+ '''
+# ---
+# name: test_hogqlx_tight_vs_loose_tags[a_a-f78190c8]
+ '''
+ {
+ attributes: []
+ end: 12
+ kind: "a"
+ start: 0
+ }
+ '''
+# ---
+# name: test_hogqlx_tight_vs_loose_tags[a_b_1-b6770467]
'''
{
attributes: [
{
- name: "children"
- value: [
- {
- end: 8
- start: 3
- value: "1 + 2"
- }
- ]
+ end: 9
+ name: "b"
+ start: 4
+ value: {
+ end: 8
+ start: 7
+ value: 1
+ }
}
]
end: 12
@@ -5034,28 +5971,28 @@
}
'''
# ---
-# name: test_hogqlx_tag_text_accepts_arbitrary_non_brace_non_lt[a_a-ce80326f]
+# name: test_hogqlx_tight_vs_loose_tags[a_b_1-d73b5c66]
'''
{
attributes: [
{
- name: "children"
- value: [
- {
- end: 11
- start: 3
- value: "!@#%^*()"
- }
- ]
+ end: 8
+ name: "b"
+ start: 3
+ value: {
+ end: 7
+ start: 6
+ value: 1
+ }
}
]
- end: 15
+ end: 10
kind: "a"
start: 0
}
'''
# ---
-# name: test_hogqlx_tag_text_accepts_arbitrary_non_brace_non_lt[a_foo_a-016dc367]
+# name: test_hogqlx_tight_vs_loose_tags[a_b_a-7f014af6]
'''
{
attributes: [
@@ -5063,41 +6000,42 @@
name: "children"
value: [
{
- end: 7
- start: 3
- value: "foo!"
+ attributes: []
+ end: 11
+ kind: "b"
+ start: 5
}
]
}
]
- end: 11
+ end: 17
kind: "a"
start: 0
}
'''
# ---
-# name: test_hogqlx_tag_text_accepts_arbitrary_non_brace_non_lt[a_foo_bar_a-2724e3a6]
+# name: test_hogqlx_tight_vs_loose_tags[a_b_f_x-ac22291c]
'''
{
attributes: [
{
- name: "children"
- value: [
- {
- end: 10
- start: 3
- value: "foo@bar"
- }
- ]
+ end: 10
+ name: "b"
+ start: 4
+ value: {
+ end: 9
+ start: 8
+ value: "x"
+ }
}
]
- end: 14
+ end: 13
kind: "a"
start: 0
}
'''
# ---
-# name: test_hogqlx_tag_text_accepts_arbitrary_non_brace_non_lt[a_foo_bar_a-44116ebf]
+# name: test_hogqlx_tight_vs_loose_tags[a_x_a-08a3bec8]
'''
{
attributes: [
@@ -5105,53 +6043,25 @@
name: "children"
value: [
{
- end: 10
+ end: 4
start: 3
- value: "foo&bar"
+ value: "x"
}
]
}
]
- end: 14
+ end: 8
kind: "a"
start: 0
}
'''
# ---
-# name: test_hogqlx_tag_text_accepts_arbitrary_non_brace_non_lt[outer_inner_foo_bar_inner_baz_qux_outer-ed8b2082]
+# name: test_hogqlx_tight_vs_loose_tags[x-b5b588c7]
'''
{
- attributes: [
- {
- name: "children"
- value: [
- {
- attributes: [
- {
- name: "children"
- value: [
- {
- end: 21
- start: 14
- value: "foo!bar"
- }
- ]
- }
- ]
- end: 29
- kind: "inner"
- start: 7
- },
- {
- end: 36
- start: 29
- value: "baz&qux"
- }
- ]
- }
- ]
- end: 44
- kind: "outer"
+ attributes: []
+ end: 8
+ kind: "x"
start: 0
}
'''
@@ -9940,35 +10850,266 @@
}
'''
# ---
-# name: test_null_inf_nan_rejected_in_hog_identifier_slots[x_y_x_y-510bd16e]
+# name: test_null_inf_nan_rejected_in_hog_identifier_slots[x_y_x_y-510bd16e]
+ '''
+ {
+ args: [
+ "x",
+ "y"
+ ]
+ end: 15
+ expr: {
+ end: 15
+ left: {
+ chain: [
+ "x"
+ ]
+ end: 11
+ from_asterisk: False
+ start: 10
+ }
+ op: "+"
+ right: {
+ chain: [
+ "y"
+ ]
+ end: 15
+ from_asterisk: False
+ start: 14
+ }
+ start: 10
+ }
+ start: 0
+ }
+ '''
+# ---
+# name: test_parenthesized_between_high_end_position_with_hoist[0_between_0_and_0-791e981a]
+ '''
+ {
+ end: 19
+ expr: {
+ end: 1
+ start: 0
+ value: 0
+ }
+ high: {
+ end: 18
+ start: 17
+ value: 0
+ }
+ low: {
+ end: 11
+ start: 10
+ value: 0
+ }
+ negated: False
+ start: 0
+ }
+ '''
+# ---
+# name: test_parenthesized_between_high_end_position_with_hoist[0_between_0_and_0_as_x-17fd83ba]
+ '''
+ {
+ alias: "x"
+ end: 26
+ expr: {
+ end: 21
+ expr: {
+ end: 1
+ start: 0
+ value: 0
+ }
+ high: {
+ end: 19
+ start: 18
+ value: 0
+ }
+ low: {
+ end: 11
+ start: 10
+ value: 0
+ }
+ negated: False
+ start: 0
+ }
+ from_asterisk: False
+ hidden: False
+ start: 0
+ }
+ '''
+# ---
+# name: test_parenthesized_between_high_end_position_with_hoist[0_between_0_and_0_as_x-ed0ebee8]
+ '''
+ {
+ alias: "x"
+ end: 24
+ expr: {
+ end: 19
+ expr: {
+ end: 1
+ start: 0
+ value: 0
+ }
+ high: {
+ end: 18
+ start: 17
+ value: 0
+ }
+ low: {
+ end: 11
+ start: 10
+ value: 0
+ }
+ negated: False
+ start: 0
+ }
+ from_asterisk: False
+ hidden: False
+ start: 0
+ }
+ '''
+# ---
+# name: test_parenthesized_between_high_end_position_with_hoist[0_between_0_and_5_as_x-af6c11dc]
+ '''
+ {
+ alias: "x"
+ end: 22
+ expr: {
+ end: 17
+ expr: {
+ end: 1
+ start: 0
+ value: 0
+ }
+ high: {
+ end: 17
+ start: 16
+ value: 5
+ }
+ low: {
+ end: 11
+ start: 10
+ value: 0
+ }
+ negated: False
+ start: 0
+ }
+ from_asterisk: False
+ hidden: False
+ start: 0
+ }
+ '''
+# ---
+# name: test_parenthesized_between_high_end_position_with_hoist[0_not_between_0_and_0_as_x-af34ddad]
+ '''
+ {
+ alias: "x"
+ end: 28
+ expr: {
+ end: 23
+ expr: {
+ end: 1
+ start: 0
+ value: 0
+ }
+ high: {
+ end: 22
+ start: 21
+ value: 0
+ }
+ low: {
+ end: 15
+ start: 14
+ value: 0
+ }
+ negated: True
+ start: 0
+ }
+ from_asterisk: False
+ hidden: False
+ start: 0
+ }
+ '''
+# ---
+# name: test_parenthesized_between_high_end_position_with_hoist[1_between_2_and_3_4_5-d5932787]
'''
{
args: [
- "x",
- "y"
+ {
+ end: 19
+ expr: {
+ end: 1
+ start: 0
+ value: 1
+ }
+ high: {
+ end: 18
+ start: 17
+ value: 3
+ }
+ low: {
+ end: 11
+ start: 10
+ value: 2
+ }
+ negated: False
+ start: 0
+ },
+ {
+ end: 23
+ start: 22
+ value: 4
+ },
+ {
+ end: 27
+ start: 26
+ value: 5
+ }
]
- end: 15
+ distinct: False
+ end: 27
+ name: "if"
+ start: 0
+ }
+ '''
+# ---
+# name: test_parenthesized_between_high_end_position_with_hoist[1_between_2_and_3_4_as_x-9fc935a7]
+ '''
+ {
+ alias: "x"
+ end: 28
expr: {
- end: 15
- left: {
- chain: [
- "x"
- ]
+ end: 23
+ expr: {
+ end: 1
+ start: 0
+ value: 1
+ }
+ high: {
+ end: 22
+ left: {
+ end: 18
+ start: 17
+ value: 3
+ }
+ op: "+"
+ right: {
+ end: 22
+ start: 21
+ value: 4
+ }
+ start: 17
+ }
+ low: {
end: 11
- from_asterisk: False
start: 10
+ value: 2
}
- op: "+"
- right: {
- chain: [
- "y"
- ]
- end: 15
- from_asterisk: False
- start: 14
- }
- start: 10
+ negated: False
+ start: 0
}
+ from_asterisk: False
+ hidden: False
start: 0
}
'''
@@ -12800,6 +13941,38 @@
}
'''
# ---
+# name: test_placeholder_discarded_interpolate_must_be_terminated[x_order_by_1_interpolate_6-90b7bb71]
+ '''
+ {
+ end: 3
+ expr: {
+ chain: [
+ "x"
+ ]
+ end: 2
+ from_asterisk: False
+ start: 1
+ }
+ start: 0
+ }
+ '''
+# ---
+# name: test_placeholder_discarded_interpolate_must_be_terminated[x_order_by_1_interpolate_a-8d94abdf]
+ '''
+ {
+ end: 3
+ expr: {
+ chain: [
+ "x"
+ ]
+ end: 2
+ from_asterisk: False
+ start: 1
+ }
+ start: 0
+ }
+ '''
+# ---
# name: test_placeholder_statement_then_postfix_call_or_property[1-26a9fdff]
'''
{
@@ -15004,6 +16177,163 @@
}
'''
# ---
+# name: test_table_function_arg_rejects_bare_select_subquery[SELECT_FROM_a_1_2-3d1f9a13]
+ '''
+ {
+ end: 21
+ select: [
+ {
+ chain: [
+ "*"
+ ]
+ end: 8
+ from_asterisk: False
+ start: 7
+ }
+ ]
+ select_from: {
+ end: 21
+ start: 14
+ table: {
+ chain: [
+ "a"
+ ]
+ from_asterisk: False
+ }
+ table_args: [
+ {
+ end: 17
+ start: 16
+ value: 1
+ },
+ {
+ end: 20
+ start: 19
+ value: 2
+ }
+ ]
+ }
+ start: 0
+ }
+ '''
+# ---
+# name: test_table_function_arg_rejects_bare_select_subquery[SELECT_FROM_a_SELECT_1-24fdd15d]
+ '''
+ {
+ end: 27
+ select: [
+ {
+ chain: [
+ "*"
+ ]
+ end: 8
+ from_asterisk: False
+ start: 7
+ }
+ ]
+ select_from: {
+ end: 27
+ start: 14
+ table: {
+ chain: [
+ "a"
+ ]
+ from_asterisk: False
+ }
+ table_args: [
+ {
+ end: 25
+ select: [
+ {
+ end: 25
+ start: 24
+ value: 1
+ }
+ ]
+ start: 17
+ }
+ ]
+ }
+ start: 0
+ }
+ '''
+# ---
+# name: test_table_function_arg_rejects_bare_select_subquery[SELECT_FROM_a_b-135bc7d5]
+ '''
+ {
+ end: 18
+ select: [
+ {
+ chain: [
+ "*"
+ ]
+ end: 8
+ from_asterisk: False
+ start: 7
+ }
+ ]
+ select_from: {
+ end: 18
+ start: 14
+ table: {
+ chain: [
+ "a"
+ ]
+ from_asterisk: False
+ }
+ table_args: [
+ {
+ chain: [
+ "b"
+ ]
+ end: 17
+ from_asterisk: False
+ start: 16
+ }
+ ]
+ }
+ start: 0
+ }
+ '''
+# ---
+# name: test_table_function_arg_rejects_bare_select_subquery[SELECT_FROM_a_x_1-1c06ea1f]
+ '''
+ {
+ end: 23
+ select: [
+ {
+ chain: [
+ "*"
+ ]
+ end: 8
+ from_asterisk: False
+ start: 7
+ }
+ ]
+ select_from: {
+ end: 23
+ start: 14
+ table: {
+ chain: [
+ "a"
+ ]
+ from_asterisk: False
+ }
+ table_args: [
+ {
+ name: "x"
+ value: {
+ end: 22
+ start: 21
+ value: 1
+ }
+ }
+ ]
+ }
+ start: 0
+ }
+ '''
+# ---
# name: test_template_string_top_level_carries_outer_span[Hello_TypeScript_arrayMap_a_a_1_2_3-46be7f64]
'''
{
diff --git a/posthog/hogql/test/_test_parser.py b/posthog/hogql/test/_test_parser.py
index d02aa1ca7cda..41283bddfe3b 100644
--- a/posthog/hogql/test/_test_parser.py
+++ b/posthog/hogql/test/_test_parser.py
@@ -1839,6 +1839,31 @@ def parser_test_factory(backend: HogQLParserBackend):
),
)
+ def test_table_function_arg_rejects_bare_select_subquery(self):
+ # A table-function arg is a `columnExpr` (cpp's `tableArgList`), so a
+ # bare `SELECT …` is not valid — cpp rejects `FROM a(SELECT 1)`; only
+ # `(SELECT …)` paren-wrapped is. (A general call admits a bare subquery
+ # via `ColumnExprCallSelect`; a table-function arg does not.)
+ for src in (
+ "SELECT * FROM a(SELECT 1)",
+ "SELECT * FROM events(SELECT 1)",
+ "SELECT * FROM numbers(SELECT 1)",
+ "SELECT * FROM a(b, SELECT 1)",
+ ):
+ with self.assertRaises((ExposedHogQLError, SyntaxError), msg=f"{backend}: {src!r}"):
+ parse_select(src, backend="cpp-json")
+ with self.assertRaises((ExposedHogQLError, SyntaxError), msg=f"{backend}: {src!r}"):
+ parse_select(src, backend=backend)
+ # Guards: a paren-wrapped subquery, plain exprs, and named args are
+ # all valid table-function args.
+ for src in (
+ "SELECT * FROM a((SELECT 1))",
+ "SELECT * FROM a(1, 2)",
+ "SELECT * FROM a(b)",
+ "SELECT * FROM a(x := 1)",
+ ):
+ self._assert_ast(src, "select")
+
def test_select_from_join_multiple(self):
node = self._select(
"""
@@ -5346,6 +5371,24 @@ def parser_test_factory(backend: HogQLParserBackend):
self.assertEqual(inner.end, 24, msg=f"{backend}: inner.end={inner.end}, expected 24")
self.assertEqual(outer.end, 40, msg=f"{backend}: outer.end={outer.end}, expected 40")
+ def test_parenthesized_between_high_end_position_with_hoist(self):
+ # A BETWEEN whose high operand is parenthesized spans through the
+ # trailing `)`, but the high AST node's `end` is paren-stripped. In
+ # the hoist case (an alias / ternary / etc. parsed past the parens),
+ # the BetweenExpr span must be recovered from the source — else rust's
+ # BetweenExpr.end dropped the closing paren and diverged from cpp.
+ for src in (
+ "0 between 0 and (0) as x",
+ "0 not between 0 and (0) as x",
+ "0 between 0 and ((0)) as x",
+ "1 between 2 and (3) ? 4 : 5",
+ "1 between 2 and (3 + 4) as x",
+ ):
+ self._assert_ast(src, "expr")
+ # Guards: simple (no hoist) and a non-parenthesized high are unaffected.
+ for src in ("0 between 0 and (0)", "0 between 0 and 5 as x"):
+ self._assert_ast(src, "expr")
+
def test_bare_asterisk_clause_body_after_comma(self):
# `select a, where *` opens the WHERE clause with a bare `*` body; later LIMIT / GROUP BY / etc. is a normal subsequent clause.
cases = (
@@ -5835,6 +5878,71 @@ def parser_test_factory(backend: HogQLParserBackend):
for src in cases:
self._assert_ast(src, "expr")
+ def test_hogqlx_tight_vs_loose_tags(self):
+ # cpp lexes `<ident…` ("tight") through dedicated tag/text lexer modes
+ # and `< ident…` ("loose") through the default mode, and the two
+ # diverge: tight captures child text (incl. whitespace); loose admits
+ # only nested tags / `{expr}` children (stray text rejected, whitespace
+ # dropped); loose attribute values may be `f'…'` templates (tight
+ # rejects them); a loose opening name may be quoted (`< "x" />`) but a
+ # closing name never is (so `< "x" ></ "x" >` rejects).
+ accept = (
+ "<a></a>",
+ "< a ></ a >",
+ "<a>x</a>",
+ "<a> </a>",
+ "< a > </ a >",
+ "< a b=f'x' />",
+ "<a b={1}/>",
+ "< a b={1} />",
+ "< a >< b /></ a >",
+ '< "x" />',
+ )
+ for src in accept:
+ self._assert_ast(src, "expr")
+ reject = (
+ "< a >x</ a >",
+ "<a b=f'x'/>",
+ '< "x" ></ "x" >',
+ )
+ for src in reject:
+ with self.assertRaises((BaseHogQLError, SyntaxError), msg=f"{backend}: {src!r}"):
+ parse_expr(src, backend=backend)
+
+ def test_cast_type_param_admits_date_literal_as_raw_text(self):
+ # A `date ''` / `timestamp ''` literal inside a `ColumnTypeExprParam`
+ # is `getText()`'d, never visited, so cpp accepts it as raw param
+ # text; the visitor-level "not supported" rejection must not fire.
+ for src in (
+ "cast(0 as a(date ''))",
+ "cast(0 as a(date '', date '', ))",
+ "cast(0 as a(a(date '', date '', ), ))",
+ "cast(0 as a(timestamp ''))",
+ ):
+ self._assert_ast(src, "expr")
+ # Guards: a genuine ColumnTypeExprEnum and a bare `date ''` cast type
+ # still reject on every backend.
+ for src in ("cast(0 as a(f''=0))", "cast(0 as a('x'=1))", "cast(0 as date '')"):
+ with self.assertRaises((BaseHogQLError, SyntaxError), msg=f"{backend}: {src!r}"):
+ parse_expr(src, backend=backend)
+
+ def test_placeholder_discarded_interpolate_must_be_terminated(self):
+ # A `{placeholder}` select's trailing ORDER BY is grammar-parsed but
+ # never visited, so its INTERPOLATE is consume-dropped. An
+ # unterminated clause — e.g. a `#`-comment swallowing the `)` to
+ # end-of-line — must still reject, matching cpp's "mismatched input
+ # '<EOF>'", not be silently accepted.
+ for src in (
+ "{x} order by 1 interpolate ( # 6 )",
+ "{x} order by 1 interpolate ( a # 6 )",
+ "{x} order by 1 interpolate ( a",
+ ):
+ with self.assertRaises((BaseHogQLError, SyntaxError), msg=f"{backend}: {src!r}"):
+ parse_select(src, backend=backend)
+ # Guards: a well-formed interpolate (and a `#6` positional ref) parse.
+ for src in ("{x} order by 1 interpolate ( a )", "{x} order by 1 interpolate ( #6 )"):
+ self._assert_ast(src, "select")
+
def test_join_expr_parens_does_not_take_outer_alias(self):
# `JoinExprParens` isn't a `tableExpr`, so alias / FINAL / SAMPLE can't bind to a `(joinExpr)` from outside.
@@ -5963,6 +6071,15 @@ def parser_test_factory(backend: HogQLParserBackend):
for src in ("f'hello'", "f'{1+2}'"):
self._assert_ast(src, "expr")
+ def test_full_template_string_empty_body_span(self):
+ # The standalone `parse_string_template` entry has no trailing quote,
+ # so an empty body spans the whole synthetic `F'` token `[0, len]`,
+ # not one byte past it like an inline `f''` would. Position-sensitive.
+ self._assert_ast("", "template")
+ # Guards: a non-empty literal body and a `{ … }` substitution.
+ self._assert_ast("x", "template")
+ self._assert_ast("{1}", "template")
+
def test_empty_paren_only_clauses_rejected(self):
# `columnAliases`, `interpolateClause`'s paren body, and `columnsReplaceList` each require ≥ 1 element when parens are present.
@@ -6429,6 +6546,37 @@ def parser_test_factory(backend: HogQLParserBackend):
):
self._assert_ast(src, "select")
+ def test_cross_join_after_join_on_constraint(self):
+ # A comma after `JOIN … ON expr` is a CROSS JOIN (single-expr ON) when
+ # the post-comma table carries an alias or `FINAL`: cpp reads
+ # `ON expr, t alias` / `…, t FINAL` that way, not as a multi-expr ON.
+ for src in (
+ "SELECT 0 FROM a JOIN a ON '', a a",
+ "SELECT 1 FROM a JOIN b ON 1, c c",
+ "SELECT 0 FROM a JOIN a ON x = y, b b",
+ "SELECT * FROM a JOIN b ON x, y FINAL",
+ "SELECT * FROM a JOIN b ON x, y z, w",
+ "SELECT * FROM a JOIN b ON x, (select 1) s",
+ ):
+ self._assert_ast(src, "select")
+ # The comma stays a multi-expression ON (rejected on all backends)
+ # when the post-comma element fully consumes as a columnExpr: a bare
+ # column / `AS` alias / field chain, or a trailing `SAMPLE` (taken at
+ # the statement level). `y team_id` is a reserved alias (rejected on
+ # both); `c JOIN d ON y` has no alias/FINAL so it stays multi-expr ON.
+ for src in (
+ "SELECT * FROM a JOIN b ON x, y AS z",
+ "SELECT * FROM a JOIN b ON x, y.z",
+ "SELECT * FROM a JOIN b ON x, y SAMPLE 0.1",
+ "SELECT * FROM a JOIN b ON x, y, z",
+ "SELECT * FROM a JOIN b ON x, y team_id",
+ "SELECT * FROM a JOIN b ON x, c JOIN d ON y",
+ ):
+ with self.assertRaises((ExposedHogQLError, SyntaxError), msg=f"{backend}: {src!r}"):
+ parse_select(src, backend="cpp-json")
+ with self.assertRaises((ExposedHogQLError, SyntaxError), msg=f"{backend}: {src!r}"):
+ parse_select(src, backend=backend)
+
def test_cast_type_compound_loop_stops_at_non_identifier_keyword(self):
# `columnTypeExpr`'s compound alt is `identifier identifier+`; NULL / INF / NAN aren't in `identifier`, so `cast(x as Int NULL)` rejects.
# `Array(Int NULL)` is intentionally omitted — that routes through ColumnTypeExprParam's raw-text fallback (separate problem).
@@ -7510,6 +7658,23 @@ def parser_test_factory(backend: HogQLParserBackend):
with self.assertRaises(BaseHogQLError):
parse_select("SELECT DISTINCT FROM x", backend=backend)
+ def test_distinct_with_empty_parens_is_a_function_call(self):
+ # `distinct()` with EMPTY parens is the zero-arg call `Call(distinct,
+ # [])`, not the DISTINCT modifier: cpp can't read DISTINCT as the
+ # modifier with only `()` (no column) after, so it backs off to a call.
+ for src in ("SELECT distinct()", "SELECT distinct() FROM a"):
+ self._assert_ast(src, "select")
+ # Guard: non-empty parens keep DISTINCT the modifier on the column.
+ for src in ("SELECT distinct(x)", "SELECT distinct(x), y"):
+ self._assert_ast(src, "select")
+ # Same rule one level down: `count(distinct())` is `count` over a
+ # nested `distinct()` call, not the args DISTINCT-marker (empty `()` only).
+ for src in ("count(distinct())", "f(distinct())", "count(distinct() + 1)"):
+ self._assert_ast(src, "expr")
+ # Guards: non-empty parens / non-leading position keep the args-marker.
+ for src in ("count(distinct(x))", "count(distinct x)", "f(x, distinct())"):
+ self._assert_ast(src, "expr")
+
def test_hogqlx_attribute_and_text_child_positions_match(self):
# cpp positions each HogQLXAttribute (name start -> value end, or name end
# for a bare attribute), the string value Constant over the string token,
@@ -7766,6 +7931,78 @@ def parser_test_factory(backend: HogQLParserBackend):
msg=query,
)
+ def test_window_filter_body_suppresses_visitor_rejections(self):
+ # A window function's FILTER body is grammar-parsed but never visited
+ # (the AST discards it), so visitor-level rejections inside it must be
+ # tolerated to match cpp: a no-column `select … from …` subquery (cpp's
+ # `ColumnExprInvalidFromImplicitAlias`) and a unit-less `interval
+ # '<str>'` (cpp's `ColumnExprIntervalString`). rust used to fatally
+ # reject both before the body could be discarded.
+ for query in (
+ "a() filter(where (select from x)) over a",
+ "\"\"() filter(where interval 'bm ') over ()",
+ ):
+ self.assertEqual(
+ parse_expr(query, backend="cpp-json"),
+ parse_expr(query, backend=backend),
+ msg=query,
+ )
+ # Guards: the same forms reject when VISITED (at expr level), and a
+ # genuine grammar error in the body still rejects even when discarded.
+ strict = (
+ "(select from x)",
+ "interval 'bm '",
+ "a() filter(where (select where 1)) over a",
+ )
+ for query in strict:
+ with self.assertRaises((BaseHogQLError, SyntaxError), msg=query):
+ parse_expr(query, backend=backend)
+
+ def test_nested_interval_value_skips_postfix_run_for_unit(self):
+ # `INTERVAL <value> <unit>` whose value is itself a nested INTERVAL
+ # carrying a postfix run (a `()` call, `[…]` index, `.id` access):
+ # cpp resolves the trailing unit keyword by looking PAST the postfix
+ # operators. rust used to stop at the postfix and miss the unit, so it
+ # mis-parsed the nesting (`interval interval 0 hour () hour`).
+ for query in (
+ "interval interval 0 week week",
+ "interval interval 0 hour () hour",
+ ):
+ self.assertEqual(
+ parse_expr(query, backend="cpp-json"),
+ parse_expr(query, backend=backend),
+ msg=query,
+ )
+
+ def test_nested_string_interval_dispatches_on_trailing_unit_count(self):
+ # A nested string-valued INTERVAL: cpp keeps the inner string
+ # self-contained (`'5 day'`) when ONE unit trails (it's the OUTER's),
+ # but reads it as the value-expr of an expr+unit inner when TWO trail —
+ # the value-expr reading sidesteps the string's count/unit validation,
+ # so `''` / `'bm '` parse there (`interval interval '' day month` →
+ # `INTERVAL (INTERVAL '' DAY) MONTH`). A window FILTER body, being
+ # grammar-parsed but never visited, also tolerates a bad inner string.
+ # rust used to always use the string-only reading and wrong-reject these.
+ for query in (
+ "interval interval '' day month",
+ "interval interval '5 day' hour month",
+ "a() filter(where interval interval 'bm ' day) over a",
+ "a() filter(where interval interval '' day month) over a",
+ # one trailing unit keeps the inner string-only — still parity
+ "interval interval '5 day' month",
+ ):
+ self.assertEqual(
+ parse_expr(query, backend="cpp-json"),
+ parse_expr(query, backend=backend),
+ msg=query,
+ )
+ # Guard: a bad inner string with a SINGLE trailing unit has no
+ # value-expr escape hatch, so it rejects when VISITED. (The empty
+ # `''` single-unit form is left out — the legacy python backend
+ # surfaces it as a bare ValueError, an unrelated pre-existing quirk.)
+ with self.assertRaises((BaseHogQLError, SyntaxError), msg="interval interval 'bm ' day"):
+ parse_expr("interval interval 'bm ' day", backend=backend)
+
def test_stacked_table_alias_span_ends_at_first_alias(self):
# `TableExprAlias` is left-recursive (`x a b c`): cpp's nested ctxs end
# the JoinExpr span at the INNERMOST (first) alias, while each outer
@@ -8007,4 +8244,28 @@ def parser_test_factory(backend: HogQLParserBackend):
msg=query,
)
+ def test_cast_type_enum_template_string_key_rejected(self):
+ # `enumValue: string '=' numberLiteral`, and `string` is
+ # STRING_LITERAL | templateString — so an `f'…'` key makes
+ # `cast(0 as a(f''=0))` a `ColumnTypeExprEnum` that cpp rejects as
+ # unsupported. rust used to check only STRING for the key and
+ # over-accept the template-keyed enum as a raw Param type name.
+ for query in (
+ "cast(0 as a(f''=0))",
+ "cast(0 as a(f'x'=1))",
+ "cast(0 as a(f'{1}'=2))",
+ "cast(0 as a('k'=1, f''=2))",
+ "try_cast(0 as a(f''=0))",
+ ):
+ with self.assertRaises(BaseHogQLError, msg=f"{backend}: {query}"):
+ parse_expr(query, backend=backend)
+ # Guard: a template not followed by `= numberLiteral` is a Param type
+ # (not an enum), still accepted on both.
+ for query in ("cast(0 as a(b))", "cast(0 as a(f''))"):
+ self.assertEqual(
+ parse_expr(query, backend="cpp-json"),
+ parse_expr(query, backend=backend),
+ msg=query,
+ )
+
return TestParser
diff --git a/pyproject.toml b/pyproject.toml
index 104d3c979825..7cf4110fc239 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.92", # 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.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
"humanize~=4.12.3",
"infi-clickhouse-orm",
"jsonref==1.1.0",
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index a1b90fa88011..3a866af75493 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -4358,7 +4358,7 @@ dependencies = [
[[package]]
name = "hogql_parser_rs"
-version = "1.3.92"
+version = "1.3.96"
dependencies = [
"pyo3",
"serde_json",
diff --git a/rust/hogql/parser/Cargo.toml b/rust/hogql/parser/Cargo.toml
index e5fd7ea4a805..edc39286979b 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.92); each ships as its own PyPI wheel.
-version = "1.3.92"
+# 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"
edition = "2021"
publish = false
diff --git a/rust/hogql/parser/pyproject.toml b/rust/hogql/parser/pyproject.toml
index 78613c261e8b..97e460e3062c 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.92).
-version = "1.3.92"
+# 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"
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/parse/expr.rs b/rust/hogql/parser/src/parse/expr.rs
index 2371b95329e1..e96df1171d7a 100644
--- a/rust/hogql/parser/src/parse/expr.rs
+++ b/rust/hogql/parser/src/parse/expr.rs
@@ -806,23 +806,63 @@ impl<'a, E: Emitter + Clone> Parser<'a, E> {
// back; operator continuations like `interval + 1` reach try_alt too.
//
// A nested INTERVAL in the value position of an enclosing INTERVAL
- // (`interval interval '5 day' month`) is special: cpp's ALL(*)
- // reserves the trailing unit (`month`) for the OUTER interval, so
- // the inner one never takes the unit-consuming form. Parse it
- // string-only when a string follows (`interval '5 day'` →
- // `toIntervalDay(5)`, with a bad string a hard error like cpp's
- // `ColumnExprIntervalString`), else as a Field / call via the ident
- // path (`interval - x` → `interval` Field minus `x`; `interval(1)`
- // → call). The trailing unit then binds to the outer interval.
+ // is two-faced. The STRING form (`interval interval '5 day' month`)
+ // is self-contained — count and unit live inside the string — so
+ // cpp's ALL(*) parses the inner string-only and reserves the
+ // trailing `month` for the OUTER interval (a bad string is a hard
+ // error like cpp's `ColumnExprIntervalString`). The EXPR form is
+ // resolved by which reading lets the WHOLE thing parse: the inner is
+ // a nested `INTERVAL <value> <unit>` only when it leaves a unit for
+ // the outer (`interval interval 0 week week` → inner `INTERVAL 0
+ // WEEK`, outer `WEEK`). Otherwise the inner `interval` is an
+ // identifier and its trailing unit binds to the outer
+ // (`interval interval - x week` → `INTERVAL (interval - x) WEEK`;
+ // `interval interval(1) week` → the call as the value). So probe the
+ // nested form and keep it only when a unit keyword still follows.
TokenKind::Keyword(Kw::Interval) if interval_value => {
if self.peek_next() == TokenKind::String {
- self.parse_interval_string_only()
- .map_err(ParseError::into_fatal)
+ // Nested string-valued INTERVAL. cpp keeps the inner string a
+ // self-contained `ColumnExprIntervalString` (count+unit inside
+ // the quotes, `'5 day'`) when a SINGLE unit trails — that unit
+ // is the OUTER interval's. When TWO units trail, the inner is
+ // instead an expr+unit INTERVAL whose VALUE is the (plain
+ // constant) string and whose unit is the first keyword, leaving
+ // the second for the outer (`interval interval '' day month` →
+ // `INTERVAL (INTERVAL '' DAY) MONTH`). The value-expr reading
+ // sidesteps the string's count/unit validation, which is why
+ // `''` parses there but not as a bare string interval.
+ if self.interval_string_trailing_unit_count() >= 2 {
+ self.parse_interval_expr().map_err(ParseError::into_fatal)
+ } else {
+ self.parse_interval_string_only()
+ .map_err(ParseError::into_fatal)
+ }
} else {
- self.parse_ident_lead()
+ let cp = self.checkpoint();
+ match self.parse_interval_expr() {
+ // Keep the nested reading only when a unit is still left
+ // for the OUTER interval — directly, or after a run of
+ // postfix operators on the inner (`interval interval 0
+ // hour () hour` → `INTERVAL ((INTERVAL 0 HOUR)()) HOUR`).
+ Ok(inner) if self.interval_unit_follows_postfix_run() => Ok(inner),
+ Err(e) if e.fatal => Err(e),
+ _ => {
+ self.restore(cp)?;
+ self.parse_ident_lead()
+ }
+ }
}
}
- TokenKind::Keyword(Kw::Interval) if can_start_interval_value(self.peek_next()) => {
+ // A HogQLX tag is a valid interval value (`interval <t/> second` →
+ // `INTERVAL (<t/>) SECOND`), but `<` is a pure-infix operator so
+ // `can_start_interval_value` rejects it — admit it explicitly when
+ // the `<` actually begins a tag (not a `<` comparison). The try_alt
+ // below still falls back to the `interval < x` comparison reading
+ // when the tag parse doesn't pan out.
+ TokenKind::Keyword(Kw::Interval)
+ if can_start_interval_value(self.peek_next())
+ || self.peek_next_starts_hogqlx_tag() =>
+ {
if self.peek_next() == TokenKind::String {
self.parse_interval_expr().map_err(ParseError::into_fatal)
} else {
@@ -1227,6 +1267,19 @@ impl<'a, E: Emitter + Clone> Parser<'a, E> {
if matches!(self.peek(), TokenKind::String) && !self.peek_next_is_interval_unit() {
let str_tok = self.peek0;
let raw = unquote_single_string(self.text(str_tok));
+ // Unvisited clause (window FILTER body / discarded ORDER BY): cpp
+ // grammar-parses the string-form INTERVAL but never visits it, so
+ // none of its count / unit "not supported" rejections (`interval
+ // 'bm '`) fire here. Consume the string into a throwaway and return;
+ // the value is moot. (The no-space `interval 'p'` case is covered
+ // too, so its own suppress branch below is unreachable now.)
+ if self.suppress_unvisited_clause_checks {
+ self.bump()?;
+ return Ok(self.emit.call(
+ "toIntervalSecond",
+ vec![self.emit.constant(self.emit.string(&raw))],
+ ));
+ }
if let Some((count_str, unit)) = raw.split_once(' ') {
// cpp's `visitColumnExprIntervalString` requires the
// count to be a non-negative decimal integer (`isdigit`
@@ -1280,19 +1333,10 @@ impl<'a, E: Emitter + Clone> Parser<'a, E> {
// Reaching here means the string has no internal space (the split
// failed) and — per the branch guard — no trailing unit keyword:
// cpp's `ColumnExprIntervalString`, which `visitColumnExprIntervalString`
- // rejects (it isn't `<count> <unit>`). In a clause cpp grammar-parses
- // but never visits (`suppress_unvisited_clause_checks`), tolerate it
- // with a throwaway so the discarded parse completes — matching cpp's
- // accept (`{x} order by interval 'p'`). The node value is moot.
- if self.suppress_unvisited_clause_checks {
- let s = unquote_single_string(self.text(str_tok));
- self.bump()?;
- return Ok(self.emit.call(
- "toIntervalSecond",
- vec![self.emit.constant(self.emit.string(&s))],
- ));
- }
- // Fall through to the expr+unit form: parse the string as
+ // rejects (it isn't `<count> <unit>`). The unvisited-clause case
+ // (`{x} order by interval 'p'`) was already handled by the
+ // suppress short-circuit above, so a strict reject is all that's
+ // left — fall through to the expr+unit form: parse the string as
// the value expression and let the trailing unit keyword
// close the INTERVAL.
}
@@ -1366,6 +1410,18 @@ impl<'a, E: Emitter + Clone> Parser<'a, E> {
self.expect_kw(Kw::Interval, "INTERVAL")?;
let str_tok = self.peek0;
let raw = unquote_single_string(self.text(str_tok));
+ // Unvisited clause (window FILTER body / discarded ORDER BY): cpp
+ // grammar-parses the inner `ColumnExprIntervalString` but never visits it,
+ // so its count/unit "not supported" rejections never fire — tolerate any
+ // string with a throwaway, matching the suppress short-circuit in
+ // `parse_interval_expr` (`a() filter(where interval interval 'bm ' day) over a`).
+ if self.suppress_unvisited_clause_checks {
+ self.bump()?;
+ return Ok(self.emit.call(
+ "toIntervalSecond",
+ vec![self.emit.constant(self.emit.string(&raw))],
+ ));
+ }
let Some((count_str, unit)) = raw.split_once(' ') else {
self.bump()?;
return Err(ParseError::not_implemented_fatal(
@@ -1408,6 +1464,40 @@ impl<'a, E: Emitter + Clone> Parser<'a, E> {
.call(unit_name, vec![self.emit.constant(self.emit.int(count))]))
}
+ /// For a nested string-valued INTERVAL (`peek0 == interval`, `peek1 ==
+ /// String`), count the INTERVAL unit keywords (`SECOND … YEAR`) that
+ /// immediately trail the string, capped at 2. Drives the string-only vs
+ /// expr+unit choice for the inner interval: one trailing unit is the OUTER
+ /// interval's (inner stays self-contained), two means the inner takes the
+ /// first as its own unit and reserves the second for the outer.
+ fn interval_string_trailing_unit_count(&self) -> usize {
+ let mut probe = Lexer::with_pos(self.src, self.peek1.end);
+ let mut count = 0usize;
+ while count < 2 {
+ match probe.next_token() {
+ Ok(t)
+ if matches!(
+ t.kind,
+ TokenKind::Keyword(
+ Kw::Second
+ | Kw::Minute
+ | Kw::Hour
+ | Kw::Day
+ | Kw::Week
+ | Kw::Month
+ | Kw::Quarter
+ | Kw::Year
+ )
+ ) =>
+ {
+ count += 1
+ }
+ _ => break,
+ }
+ }
+ count
+ }
+
/// Is `peek_next` a recognised INTERVAL unit keyword? Used by
/// parse_interval_expr to decide between the combined-string form
/// (`INTERVAL '5 day'`) and the expr-plus-unit form (`INTERVAL '1'
@@ -1422,6 +1512,66 @@ impl<'a, E: Emitter + Clone> Parser<'a, E> {
}
}
+ /// After a nested-interval value at `peek0`, would one of the eight singular
+ /// INTERVAL unit keywords (`SECOND … YEAR`, what `parse_interval_expr`'s unit
+ /// slot accepts) follow once a run of postfix operators on that value — a
+ /// `(…)` call, `[…]` subscript, or `.id` / `?.id` member — is skipped? The
+ /// enclosing INTERVAL takes that unit, so the inner `interval` is a nested
+ /// value-plus-postfixes (`interval interval 0 hour () hour`) rather than a
+ /// bare identifier. Postfix runs only — an arithmetic / infix continuation
+ /// is left to the bare-identifier reading.
+ fn interval_unit_follows_postfix_run(&self) -> bool {
+ let is_unit = |k: TokenKind| {
+ matches!(
+ k,
+ TokenKind::Keyword(
+ Kw::Second
+ | Kw::Minute
+ | Kw::Hour
+ | Kw::Day
+ | Kw::Week
+ | Kw::Month
+ | Kw::Quarter
+ | Kw::Year
+ )
+ )
+ };
+ let mut probe = Lexer::with_pos(self.src, self.peek0.start);
+ loop {
+ let Ok(t) = probe.next_token() else {
+ return false;
+ };
+ match t.kind {
+ k if is_unit(k) => return true,
+ TokenKind::LParen | TokenKind::LBracket => {
+ let mut depth: i32 = 1;
+ while depth > 0 {
+ let Ok(inner) = probe.next_token() else {
+ return false;
+ };
+ match inner.kind {
+ TokenKind::LParen | TokenKind::LBracket | TokenKind::LBrace => {
+ depth += 1
+ }
+ TokenKind::RParen | TokenKind::RBracket | TokenKind::RBrace => {
+ depth -= 1
+ }
+ TokenKind::Eof => return false,
+ _ => {}
+ }
+ }
+ }
+ // `.id` / `?.id` member — skip the member token too.
+ TokenKind::Dot | TokenKind::NullProperty => {
+ if probe.next_token().is_err() {
+ return false;
+ }
+ }
+ _ => return false,
+ }
+ }
+ }
+
/// Is the current token a `WITH` that begins a `WITH (LOCAL)? TIME
/// ZONE` type-cast suffix? Used by the `::` cast handler so a bare
/// `WITH` (e.g. a trailing `WITH FILL` order-by modifier) is left
@@ -3253,9 +3403,16 @@ impl<'a, E: Emitter + Clone> Parser<'a, E> {
// all keep DISTINCT as a Field. The follow-set heuristic here
// mirrors that: bail out when peek_next is Comma or any pure
// infix/postfix op that can't start a fresh expression.
+ // `distinct()` with EMPTY parens is the zero-arg call `Call(distinct,
+ // [])`, not the args DISTINCT-marker: cpp reads `count(distinct())` as
+ // `count` over a nested `distinct()` call (cf. `SELECT distinct()`).
+ // `distinct(x)` keeps the marker, so only empty `()` triggers this.
+ let distinct_heads_empty_call =
+ self.peek_next() == TokenKind::LParen && self.peek_lparen_is_empty();
let distinct = if self.peek() == TokenKind::Keyword(Kw::Distinct)
&& !matches!(self.peek_next(), TokenKind::Comma)
&& !is_pure_infix_op(self.peek_next())
+ && !distinct_heads_empty_call
{
self.bump()?;
true
@@ -3420,8 +3577,13 @@ impl<'a, E: Emitter + Clone> Parser<'a, E> {
let mut pos = self.peek0.start;
loop {
let mut probe = Lexer::with_pos(self.src, pos);
- // enumValue: STRING `=` numberLiteral
- if !matches!(probe.next_token().map(|t| t.kind), Ok(TokenKind::String)) {
+ // enumValue: string `=` numberLiteral, where `string` is
+ // STRING_LITERAL | templateString — so an `f'…'` key (`a(f''=0)`) is
+ // an enum value too, which cpp rejects as `ColumnTypeExprEnum`.
+ if !matches!(
+ probe.next_token().map(|t| t.kind),
+ Ok(TokenKind::String | TokenKind::TemplateString)
+ ) {
return false;
}
if !matches!(probe.next_token().map(|t| t.kind), Ok(TokenKind::EqDouble)) {
@@ -4275,8 +4437,19 @@ impl<'a, E: Emitter + Clone> Parser<'a, E> {
// `a() b` (juxtaposition), `Int NULL` — is swallowed as raw text and
// accepted, where cpp rejects. Both callers (param-mode loop and the
// `parse_type_param_item` fall-back) route through here.
+ //
+ // `getText()` matches the item but never VISITS it, so the visitor-level
+ // "not supported" rejections (a `date '' ` / `timestamp ''` literal —
+ // `a(date '')` — and friends) must not fire during this grammar-only
+ // validation: cpp accepts them as raw param text. Suppress those checks
+ // for the validation parse only. (A genuine `ColumnTypeExprEnum` is
+ // already caught by `paren_body_is_enum_value_list` before we get here.)
let validate_cp = self.checkpoint();
- self.parse_expr_bp(0)?;
+ let prev_suppress = self.suppress_unvisited_clause_checks;
+ self.suppress_unvisited_clause_checks = true;
+ let validated = self.parse_expr_bp(0);
+ self.suppress_unvisited_clause_checks = prev_suppress;
+ validated?;
if !matches!(self.peek(), TokenKind::Comma | TokenKind::RParen) {
return Err(self.err("type parameter is not a valid expression"));
}
@@ -4351,6 +4524,50 @@ impl<'a, E: Emitter + Clone> Parser<'a, E> {
Ok(args)
}
+ /// Table-function argument list (cpp's `tableArgList`): each arg is a plain
+ /// `columnExpr` or a named `ident := expr`. Unlike a general function call
+ /// (cpp's `ColumnExprCallSelect`), a *bare* `SELECT …` is not a valid table
+ /// arg — cpp rejects `FROM a(SELECT 1)` but accepts `FROM a((SELECT 1))` —
+ /// so this skips the bare-`selectSetStmt` alt that `parse_arg_list` allows.
+ pub(crate) fn parse_table_arg_list(
+ &mut self,
+ terminator: TokenKind,
+ ) -> Result<Vec<E::Value>, ParseError> {
+ let mut args = Vec::new();
+ if self.peek() == terminator {
+ return Ok(args);
+ }
+ loop {
+ args.push(self.parse_table_argument()?);
+ if !self.eat(TokenKind::Comma)? {
+ break;
+ }
+ if self.peek() == terminator {
+ break;
+ }
+ }
+ Ok(args)
+ }
+
+ /// One table-function argument: a named `ident := expr`, else a plain
+ /// `columnExpr` (no bare-`SELECT` alt — see `parse_table_arg_list`). The
+ /// named-arg gate mirrors `parse_call_argument_with` (cpp's
+ /// `ColumnExprNamedArg` admits the full `identifier` rule).
+ fn parse_table_argument(&mut self) -> Result<E::Value, ParseError> {
+ let name_kw_ok =
+ matches!(self.peek(), TokenKind::Keyword(kw) if kw_valid_as_identifier(kw));
+ if (matches!(self.peek(), TokenKind::Ident | TokenKind::QuotedIdent) || name_kw_ok)
+ && self.peek_next() == TokenKind::ColonEquals
+ {
+ let name_tok = self.bump()?;
+ let name = identifier_text(self.text(name_tok), name_tok.kind);
+ self.bump()?; // consume `:=`
+ let value = self.parse_expr_bp(0)?;
+ return Ok(self.emit.named_argument(&name, value));
+ }
+ self.parse_expr_bp(0)
+ }
+
/// One argument in a function call's argument list. Supports the named
/// argument shape `ident := expr` which is grammar-bound to call sites,
/// and a `SELECT …` subquery (`f(select 1)`) which the grammar's
@@ -4877,9 +5094,12 @@ impl<'a, E: Emitter + Clone> Parser<'a, E> {
// is now buried inside (e.g. as `Call(if, [BetweenExpr, …])` for the ternary hoist)
// and would not otherwise receive a span. cpp emits position info on BetweenExpr
// unconditionally — match that. Simple BETWEEN spans through the high operand's
- // last consumed token (incl. a parenthesized high's trailing `)`); only the
- // WIDE/hoist case needs `high.end` (last_consumed_end overshoots there).
- let high_end = self.emit.get_field(&high, "end");
+ // last consumed token (incl. a parenthesized high's trailing `)`) via wrap_pos;
+ // the WIDE/hoist case can't (last_consumed_end overshoots past the hoist), so it
+ // stamps the high operand's end directly. The high node `end` is paren-stripped,
+ // so recover a parenthesized high's trailing `)` via `high_operand_paren_end`.
+ let high_end = high_operand_paren_end(self, &high)
+ .or_else(|| self.emit.get_field(&high, "end"));
let between_inner = self.emit.between(prev, low, high, true);
let mut between = if hoisted.is_empty() {
self.wrap_pos(between_inner, lhs_start)
@@ -4945,11 +5165,13 @@ impl<'a, E: Emitter + Clone> Parser<'a, E> {
let prev = std::mem::replace(lhs, self.emit.null());
// The simple BETWEEN spans through the high operand's *last consumed*
// token — including a trailing `)` that a parenthesized high
- // (`… and (3)`) strips from `high.end`. Only the WIDE/hoist case
- // (`parse_between_body` absorbed a nested BETWEEN that is now hoisted
- // back out) needs `high.end`, because there `last_consumed_end` is
- // past the high we actually keep.
- let high_end = self.emit.get_field(&high, "end");
+ // (`… and (3)`) strips from `high.end`. The WIDE/hoist case can't
+ // use `last_consumed_end` (it's past the hoist), so it stamps the
+ // high operand's end directly, recovering a parenthesized high's
+ // trailing `)` via `high_operand_paren_end` (the node `end` is
+ // paren-stripped).
+ let high_end = high_operand_paren_end(self, &high)
+ .or_else(|| self.emit.get_field(&high, "end"));
let between_inner = self.emit.between(prev, low, high, false);
let mut between = if hoisted.is_empty() {
self.wrap_pos(between_inner, lhs_start)
@@ -5886,23 +6108,33 @@ fn is_wholly_parenthesized<'a, E: Emitter + Clone>(
parser: &Parser<'a, E>,
node: &E::Value,
) -> bool {
- let start = match pos_offset(&parser.emit, parser.emit.get_field(node, "start").as_ref()) {
- Some(s) => s,
- None => return false,
- };
- let end = match pos_offset(&parser.emit, parser.emit.get_field(node, "end").as_ref()) {
- Some(e) => e,
- None => return false,
- };
+ let start = pos_offset(&parser.emit, parser.emit.get_field(node, "start").as_ref());
+ let end = pos_offset(&parser.emit, parser.emit.get_field(node, "end").as_ref());
+ match (start, end) {
+ (Some(s), Some(e)) => wholly_parenthesized_close(parser, s, e).is_some(),
+ _ => false,
+ }
+}
+
+/// If the byte range `[start, end)` is wholly wrapped in one balanced `( … )`
+/// (ignoring surrounding whitespace, and skipping string / quoted-identifier
+/// bodies and block comments so parens inside literals don't miscount),
+/// return that pair's `(` / `)` byte offsets `(lp, rp)`. ASCII byte-scan;
+/// callers gate on `parser.is_ascii_src`.
+fn wholly_parenthesized_close<'a, E: Emitter + Clone>(
+ parser: &Parser<'a, E>,
+ start: usize,
+ end: usize,
+) -> Option<(usize, usize)> {
let bytes = parser.src.as_bytes();
if start >= end || end > bytes.len() {
- return false;
+ return None;
}
// Nearest non-whitespace byte before `start` must be an opening paren.
let mut lp = start;
loop {
if lp == 0 {
- return false;
+ return None;
}
lp -= 1;
if !bytes[lp].is_ascii_whitespace() {
@@ -5910,7 +6142,7 @@ fn is_wholly_parenthesized<'a, E: Emitter + Clone>(
}
}
if bytes[lp] != b'(' {
- return false;
+ return None;
}
// Nearest non-whitespace byte at/after `end` must be a closing paren.
let mut rp = end;
@@ -5918,7 +6150,7 @@ fn is_wholly_parenthesized<'a, E: Emitter + Clone>(
rp += 1;
}
if rp >= bytes.len() || bytes[rp] != b')' {
- return false;
+ return None;
}
// The `(` at `lp` must balance-match the `)` at `rp` exactly.
let mut depth = 0i32;
@@ -5954,14 +6186,39 @@ fn is_wholly_parenthesized<'a, E: Emitter + Clone>(
b')' => {
depth -= 1;
if depth == 0 {
- return i == rp;
+ return (i == rp).then_some((lp, rp));
}
}
_ => {}
}
i += 1;
}
- false
+ None
+}
+
+/// The source offset just past a BETWEEN high operand, following any balanced
+/// wrapping parens. cpp's BetweenExpr span runs through a parenthesized high's
+/// trailing `)`, but the high AST node's `end` is the paren-stripped inner
+/// expr — so in the hoist case (where `last_consumed_end` has already moved
+/// past the hoist and can't be used) the node `end` undershoots by the closing
+/// paren(s). Returns a position object for the walked end, or `None` when the
+/// operand isn't parenthesized (caller keeps the node `end`) or src isn't ASCII.
+fn high_operand_paren_end<'a, E: Emitter + Clone>(
+ parser: &Parser<'a, E>,
+ high: &E::Value,
+) -> Option<E::Value> {
+ if !parser.is_ascii_src {
+ return None;
+ }
+ let mut s = pos_offset(&parser.emit, parser.emit.get_field(high, "start").as_ref())?;
+ let mut e = pos_offset(&parser.emit, parser.emit.get_field(high, "end").as_ref())?;
+ let mut extended = false;
+ while let Some((lp, rp)) = wholly_parenthesized_close(parser, s, e) {
+ s = lp;
+ e = rp + 1;
+ extended = true;
+ }
+ extended.then(|| parser.pos_obj(e))
}
/// `a and (b and c)` flattens to `And([a,b,c])` (cpp does the same for a
diff --git a/rust/hogql/parser/src/parse/hogqlx.rs b/rust/hogql/parser/src/parse/hogqlx.rs
index 1fb8a07d1304..a5258aa22557 100644
--- a/rust/hogql/parser/src/parse/hogqlx.rs
+++ b/rust/hogql/parser/src/parse/hogqlx.rs
@@ -24,6 +24,7 @@
//! Parser API is identical across the two backends so no rewrites are
//! needed here.
+use super::template::parse_template_body;
use super::{identifier_text, kw_valid_as_identifier, unquote_single_string, Parser};
use crate::emit::Emitter;
use crate::error::ParseError;
@@ -60,6 +61,68 @@ impl<'a, E: Emitter + Clone> Parser<'a, E> {
)
}
+ /// cpp's `isOpeningTag()` lexer predicate (`HogQLLexer.cpp.g4`). It decides
+ /// whether a `<` enters cpp's dedicated HogQLX tag lexer mode ("tight": tag
+ /// tokens, whitespace hidden, `>` opens a TEXT mode that captures child
+ /// text) or stays a plain `LT` that the grammar still matches as a tag in
+ /// the default lexer mode ("loose": default-mode tokens, whitespace skipped,
+ /// child *text* is not lexable so only nested tags / `{expr}` are valid
+ /// children, but attribute values may be `f'…'` templates).
+ ///
+ /// `lt_end` is the byte offset just past the `<`. Tight requires `<`
+ /// immediately followed by an identifier-start char, then — after the
+ /// `[A-Za-z0-9_-]*` tag name — either an immediate `>` / `/`, or whitespace
+ /// then `[A-Za-z0-9_]` / `>` / `/`.
+ fn hogqlx_tag_is_tight(&self, lt_end: usize) -> bool {
+ let bytes = self.src.as_bytes();
+ let is_name_start = |c: u8| c.is_ascii_alphabetic() || c == b'_';
+ let is_name_part = |c: u8| c.is_ascii_alphanumeric() || c == b'_' || c == b'-';
+ match bytes.get(lt_end) {
+ Some(&c) if is_name_start(c) => {}
+ _ => return false,
+ }
+ let mut i = lt_end + 1;
+ while bytes.get(i).is_some_and(|&c| is_name_part(c)) {
+ i += 1;
+ }
+ match bytes.get(i) {
+ Some(b'>') | Some(b'/') => true,
+ Some(&c) if c.is_ascii_whitespace() => {
+ let j = self.hogqlx_skip_ws_and_comments(i);
+ matches!(bytes.get(j), Some(&c) if c.is_ascii_alphanumeric() || c == b'_' || c == b'>' || c == b'/')
+ }
+ _ => false,
+ }
+ }
+
+ /// Byte-level skip of whitespace and `/* … */` / `--` / `//` comments,
+ /// mirroring cpp's `skipWsAndComments` used inside `isOpeningTag`.
+ fn hogqlx_skip_ws_and_comments(&self, mut i: usize) -> usize {
+ let bytes = self.src.as_bytes();
+ loop {
+ while bytes.get(i).is_some_and(|&c| c.is_ascii_whitespace()) {
+ i += 1;
+ }
+ if bytes.get(i) == Some(&b'/') && bytes.get(i + 1) == Some(&b'*') {
+ i += 2;
+ while i + 1 < bytes.len() && !(bytes[i] == b'*' && bytes[i + 1] == b'/') {
+ i += 1;
+ }
+ i += 2;
+ continue;
+ }
+ if (bytes.get(i) == Some(&b'-') && bytes.get(i + 1) == Some(&b'-'))
+ || (bytes.get(i) == Some(&b'/') && bytes.get(i + 1) == Some(&b'/'))
+ {
+ while bytes.get(i).is_some_and(|&c| c != b'\n' && c != b'\r') {
+ i += 1;
+ }
+ continue;
+ }
+ return i;
+ }
+ }
+
/// Parse a HogQLX tag element starting at `<`.
///
/// Handles both `<Tag attr* />` (self-closing) and
@@ -122,7 +185,17 @@ impl<'a, E: Emitter + Clone> Parser<'a, E> {
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")?;
+ // cpp lexes `<ident…` tags ("tight") through dedicated tag/text modes,
+ // and `< ident…` ("loose") through the default mode — they differ on
+ // child text (tight captures it, loose admits only nested tags / `{…}`)
+ // and on attribute values (loose also admits an `f'…'` template).
+ let tight = self.hogqlx_tag_is_tight(self.last_consumed_end);
+ // A loose opening name lexes in the default mode and may be a
+ // QUOTED_IDENTIFIER (`< "x" />` accepts); a tight name is a bare
+ // TAG_IDENT. The CLOSING name, by contrast, always lexes in
+ // HOGQLX_TAG_CLOSE mode (bare only — see the `false` below), so a quoted
+ // opening can only ever pair with a self-closing `/>`, never `</"x">`.
+ let kind = self.parse_hogqlx_identifier("tag name", !tight)?;
let mut attributes: Vec<E::Value> = Vec::new();
loop {
match self.peek() {
@@ -132,9 +205,9 @@ impl<'a, E: Emitter + Clone> Parser<'a, E> {
}
TokenKind::Gt => {
self.bump()?;
- let children = self.parse_hogqlx_children()?;
+ let children = self.parse_hogqlx_children(tight)?;
self.expect(TokenKind::LtSlash, "</")?;
- let close = self.parse_hogqlx_identifier("closing tag name")?;
+ let close = self.parse_hogqlx_identifier("closing tag name", false)?;
if close != kind {
return Err(self.err(format!(
"Opening and closing HogQLX tags must match. Got {} and {}",
@@ -160,7 +233,7 @@ impl<'a, E: Emitter + Clone> Parser<'a, E> {
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()?);
+ attributes.push(self.parse_hogqlx_attribute(tight)?);
}
TokenKind::Eof => {
return Err(self.err("unexpected end of input inside HogQLX tag"));
@@ -179,13 +252,13 @@ impl<'a, E: Emitter + Clone> Parser<'a, E> {
/// - `name = 'string'` → HogQLXAttribute(name, Constant(string))
/// - `name = { expr }` → HogQLXAttribute(name, expr)
/// - `name` → HogQLXAttribute(name, Constant(true))
- fn parse_hogqlx_attribute(&mut self) -> Result<E::Value, ParseError> {
+ fn parse_hogqlx_attribute(&mut self, tight: bool) -> Result<E::Value, ParseError> {
// cpp positions the HogQLXAttribute from the name start to the value end
// (or the name end for a bare attribute), and the string value Constant
// over the string token. The bare-attribute `Constant(true)` stays
// position-less (cpp leaves it null too).
let name_start = self.peek0.start;
- let name = self.parse_hogqlx_identifier("attribute name")?;
+ let name = self.parse_hogqlx_identifier("attribute name", true)?;
let name_end = self.last_consumed_end;
// No `=` → bare attribute, value is Constant(true).
if self.peek() != TokenKind::EqDouble {
@@ -217,9 +290,22 @@ impl<'a, E: Emitter + Clone> Parser<'a, E> {
self.reseek_peek_window(self.last_consumed_end);
expr
}
+ // A loose tag lexes attribute values in the default mode, where the
+ // grammar's `string` is STRING_LITERAL | templateString — so
+ // `< a b=f'x' />` admits an `f'…'` template. A tight tag lexes in
+ // TAG mode (TAG_STRING is STRING_LITERAL only), so `<a b=f'x'/>` has
+ // no template token and cpp rejects it: fall through to the error.
+ TokenKind::TemplateString if !tight => {
+ let t = self.bump()?;
+ if self.text(t).starts_with("F'") {
+ return Err(self.err("mismatched input 'F''"));
+ }
+ parse_template_body(&self.emit, self.src, t.start + 2, t.end - 1)?
+ }
_ => {
return Err(self.err(format!(
- "expected string literal or `{{expr}}` for attribute value, got {:?}",
+ "expected string literal{} or `{{expr}}` for attribute value, got {:?}",
+ if tight { "" } else { ", `f'…'` template," },
self.peek()
)));
}
@@ -238,26 +324,34 @@ impl<'a, E: Emitter + Clone> Parser<'a, E> {
/// 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<E::Value>, ParseError> {
+ fn parse_hogqlx_children(&mut self, tight: bool) -> Result<Vec<E::Value>, ParseError> {
let mut children: Vec<E::Value> = Vec::new();
loop {
- // `consume_hogqlx_text` scans from `last_consumed_end`, so that is
- // the text run's start; its byte length gives the end. cpp positions
- // each kept text Constant over its raw byte span.
- let text_start = self.last_consumed_end;
- let text = self.consume_hogqlx_text()?;
- // cpp's `VISIT(HogqlxTagElementNested)` drops child text
- // runs that contain a newline AND are entirely whitespace —
- // any pretty-printed multi-line HOGQLX literal lands here.
- // Pure-space / pure-tab runs (no newline) are kept. Mixed
- // whitespace-with-content runs are also kept verbatim.
- let drop_for_newline_ws = !text.is_empty()
- && 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 {
- let text_end = text_start + text.len();
- let c = self.emit.constant(self.emit.string(&text));
- children.push(self.wrap_pos_to(c, text_start, text_end));
+ // A tight tag's `>` opens cpp's HOGQLX_TEXT lexer mode, which captures
+ // child text (incl. whitespace). A loose tag's `>` is a plain GT in the
+ // default mode — there is no HOGQLX_TEXT token, so child text isn't
+ // lexable and only nested tags / `{…}` are valid children (the `_` arm
+ // below rejects stray text, matching cpp's `< a >x</a>` reject), and
+ // whitespace between children is skipped by the lexer, not kept.
+ if tight {
+ // `consume_hogqlx_text` scans from `last_consumed_end`, so that is
+ // the text run's start; its byte length gives the end. cpp positions
+ // each kept text Constant over its raw byte span.
+ let text_start = self.last_consumed_end;
+ let text = self.consume_hogqlx_text()?;
+ // cpp's `VISIT(HogqlxTagElementNested)` drops child text
+ // runs that contain a newline AND are entirely whitespace —
+ // any pretty-printed multi-line HOGQLX literal lands here.
+ // Pure-space / pure-tab runs (no newline) are kept. Mixed
+ // whitespace-with-content runs are also kept verbatim.
+ let drop_for_newline_ws = !text.is_empty()
+ && 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 {
+ let text_end = text_start + text.len();
+ let c = self.emit.constant(self.emit.string(&text));
+ children.push(self.wrap_pos_to(c, text_start, text_end));
+ }
}
match self.peek() {
TokenKind::LtSlash => return Ok(children),
@@ -292,8 +386,10 @@ impl<'a, E: Emitter + Clone> Parser<'a, E> {
return Err(self.err("unexpected end of input inside HogQLX tag children"));
}
_ => {
- // Should be unreachable — text consumption advances
- // past anything except `<` / `{` / Eof.
+ // Tight: unreachable — `consume_hogqlx_text` advances past
+ // anything except `<` / `{` / Eof. Loose: a stray default-mode
+ // token (bare text like `x`) — not a valid loose child, so
+ // reject, matching cpp's `< a >x</a>`.
return Err(self.err(format!(
"unexpected token in HogQLX tag children: {:?}",
self.peek()
@@ -345,7 +441,11 @@ impl<'a, E: Emitter + Clone> Parser<'a, E> {
/// modes, so `a-b` lexes as `Ident a`, `Dash`, `Ident b`; stitch
/// them back together here when the dash is followed immediately
/// by an ident-like token with no intervening whitespace.
- fn parse_hogqlx_identifier(&mut self, what: &str) -> Result<String, ParseError> {
+ fn parse_hogqlx_identifier(
+ &mut self,
+ what: &str,
+ allow_quoted: bool,
+ ) -> Result<String, ParseError> {
let head = self.bump()?;
// A tag/attr name is an `identifier` (grammar `hogqlxTagElement` /
// `hogqlxTagAttribute`), so a keyword head is only valid when it is a
@@ -353,10 +453,14 @@ impl<'a, E: Emitter + Clone> Parser<'a, E> {
// set-op keywords (intersect/except) and literal keywords (null/inf/nan)
// are omitted from that rule, so cpp rejects `<fn/>` / `<a let/>` with
// "no viable alternative"; gate them out here to match.
+ //
+ // A quoted head (`` `x` `` / `"x"`) is rejected for TAG names — cpp's tag
+ // lexer modes never yield QUOTED_IDENTIFIER there, and the loose default
+ // mode rejects `< "x" >` / `` < `x` > `` too. Attribute names DO admit a
+ // quoted form (`< c "h" >`), so `allow_quoted` gates only the name kind.
let mut name = match head.kind {
- TokenKind::Ident | TokenKind::QuotedIdent => {
- identifier_text(self.text(head), head.kind)
- }
+ TokenKind::Ident => identifier_text(self.text(head), head.kind),
+ TokenKind::QuotedIdent if allow_quoted => identifier_text(self.text(head), head.kind),
TokenKind::Keyword(kw) if kw_valid_as_identifier(kw) => {
identifier_text(self.text(head), head.kind)
}
diff --git a/rust/hogql/parser/src/parse/join.rs b/rust/hogql/parser/src/parse/join.rs
index df8f0e9cd4c6..7f267de31085 100644
--- a/rust/hogql/parser/src/parse/join.rs
+++ b/rust/hogql/parser/src/parse/join.rs
@@ -463,28 +463,19 @@ impl<'a, E: Emitter + Clone> Parser<'a, E> {
let cons_start = self.peek0.start;
if self.eat_kw(Kw::On)? {
let expr = self.parse_expr_bp(0)?;
- // cpp's `joinConstraintClause: ON columnExprList` greedily
- // consumes the comma-separated list, then the cpp visitor
- // raises `NotImplementedError` for any list with more than
- // one expression. Mirror that here: a comma followed by
- // anything that could continue the list belongs to the ON
- // list, not the outer JOIN's CROSS-JOIN comma. Rust used
- // to fall out and let the outer chain consume it as
- // cross-join, silently emitting a divergent JoinExpr.
- //
- // A *trailing* comma (`FROM a JOIN b ON 1,` with nothing parseable
- // after) is the `columnExprList`'s optional `COMMA?` — valid, and
- // cpp's JoinConstraint span covers it. Consume it here so the span
- // matches (and so the outer JOIN loop doesn't have to special-case
- // it). A comma with a real expression after is the unsupported
- // multi-expression list.
+ // cpp's `ON columnExprList` overlaps with the `joinExpr COMMA
+ // joinExpr` CROSS JOIN. A trailing comma (`ON 1,` with nothing
+ // after) is the list's optional `COMMA?` — consume it so the
+ // JoinConstraint span matches cpp's. A comma with content is either a
+ // CROSS JOIN or the unsupported multi-expression ON;
+ // `comma_after_on_begins_cross_join` splits them as cpp's ALL(*) does.
if self.peek() == TokenKind::Comma {
if matches!(
self.peek_next(),
TokenKind::Eof | TokenKind::Semicolon | TokenKind::RParen
) {
self.bump()?;
- } else {
+ } else if !self.comma_after_on_begins_cross_join()? {
let start = self.peek0.start;
let end = self.peek0.end;
return Err(ParseError::not_implemented(
@@ -493,6 +484,7 @@ impl<'a, E: Emitter + Clone> Parser<'a, E> {
end,
));
}
+ // else: a CROSS JOIN begins here — leave the comma for the outer loop.
}
return Ok(Some(
self.wrap_pos(self.emit.join_constraint(expr, "ON"), cons_start),
@@ -537,6 +529,40 @@ impl<'a, E: Emitter + Clone> Parser<'a, E> {
Ok(None)
}
+ /// After `ON expr` and a comma with content after it (comma not yet
+ /// consumed), decide whether the comma begins a CROSS JOIN rather than
+ /// extending `ON columnExprList` into the unsupported multi-expression form.
+ ///
+ /// cpp's `ON columnExprList` overlaps with the `joinExpr COMMA joinExpr`
+ /// CROSS JOIN. ANTLR's ALL(*) takes the columnExprList (declared first)
+ /// whenever it yields a complete parse, falling back to the CROSS JOIN only
+ /// when the post-comma `columnExpr` leaves a trailing token neither the list
+ /// nor the statement can consume — i.e. a table `alias` or `FINAL`. (A
+ /// trailing `SAMPLE` is consumed at the statement level, and `AS alias` is
+ /// absorbed into the columnExpr, so both stay a multi-expression ON.)
+ ///
+ /// So probe-parse the post-comma `columnExpr`, check for a following alias /
+ /// `FINAL`, then roll back for the outer loop to re-parse the target cleanly.
+ fn comma_after_on_begins_cross_join(&mut self) -> Result<bool, ParseError> {
+ let cp = self.checkpoint();
+ self.bump()?; // consume the comma for the probe only
+ let begins_cross_join = match self.parse_expr_bp(0) {
+ // Reuse `try_consume_table_alias` (cpp's exact bare/`AS` alias set,
+ // minus SAMPLE / FINAL / clause keywords) so the probe matches how
+ // the outer loop parses the alias. Swallow its error — a reserved
+ // name like `team_id` — instead of letting `?` skip the `restore`:
+ // cpp rejects a reserved cross-join alias too, so "no cross-join"
+ // keeps both backends rejecting.
+ Ok(_) => {
+ matches!(self.try_consume_table_alias(), Ok(Some(_)))
+ || self.peek() == TokenKind::Keyword(Kw::Final)
+ }
+ Err(_) => false,
+ };
+ self.restore(cp)?;
+ Ok(begins_cross_join)
+ }
+
/// Probe: does `peek_next` look like the start of a `tableExpr`?
/// Used by the JOIN loop to decide whether a top-level `,` is the
/// start of a CROSS JOIN (table atom follows) or a stray trailing
@@ -848,7 +874,7 @@ impl<'a, E: Emitter + Clone> Parser<'a, E> {
// picks up the args list off the returned Field.
if self.peek() == TokenKind::LParen {
self.bump()?;
- let args = self.parse_arg_list(TokenKind::RParen)?;
+ let args = self.parse_table_arg_list(TokenKind::RParen)?;
self.expect(TokenKind::RParen, ")")?;
// Encode as a Field with a sibling "table_args" object so the
// wrapping JoinExpr in parse_table_atom can pull it out.
diff --git a/rust/hogql/parser/src/parse/select.rs b/rust/hogql/parser/src/parse/select.rs
index dbcd13f9b372..52cddf82ffcd 100644
--- a/rust/hogql/parser/src/parse/select.rs
+++ b/rust/hogql/parser/src/parse/select.rs
@@ -266,7 +266,12 @@ impl<'a, E: Emitter + Clone> Parser<'a, E> {
match self.peek() {
TokenKind::LParen => depth += 1,
TokenKind::RParen => depth -= 1,
- TokenKind::Eof => break,
+ // EOF with the `(` still open is an unterminated clause —
+ // cpp rejects ("mismatched input '<EOF>'"). This fires when
+ // a `#`-comment inside the parens (`interpolate ( # 6 )`)
+ // swallows the closing `)` to end-of-line; break-ing here
+ // would silently accept it.
+ TokenKind::Eof => return Err(self.err("unterminated INTERPOLATE clause")),
_ => {}
}
self.bump()?;
@@ -492,11 +497,16 @@ impl<'a, E: Emitter + Clone> Parser<'a, E> {
// 1` -> `[Field(distinct)]` + ORDER BY). FROM is the exception:
// `SELECT DISTINCT FROM x` keeps DISTINCT a modifier and rejects via
// the FROM-implicit-alias footgun, matching cpp.
+ // `distinct()` (empty parens) is the zero-arg call `Call(distinct,
+ // [])`, not the modifier — cpp can't read DISTINCT as the modifier
+ // with only `()` (no column) after, so it backs off to a function
+ // call. `distinct(x)` stays the modifier on `(x)`; only empty `()`.
let distinct_is_column = matches!(
self.peek(),
TokenKind::Comma | TokenKind::Eof | TokenKind::RParen | TokenKind::Semicolon
) || (self.peek_is_clause_terminator()
- && self.peek() != TokenKind::Keyword(Kw::From));
+ && self.peek() != TokenKind::Keyword(Kw::From))
+ || (self.peek() == TokenKind::LParen && self.peek_next() == TokenKind::RParen);
if distinct_is_column {
self.restore(cp_after_select)?;
} else {
@@ -1696,7 +1706,9 @@ impl<'a, E: Emitter + Clone> Parser<'a, E> {
// 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(&self.emit, &expr) {
+ if is_bare_from_field(&self.emit, &expr)
+ && !self.suppress_unvisited_clause_checks
+ {
return Err(self.err("Cannot use \"from\" before an implicit alias"));
}
// cpp's `ColumnExprAlias` ctx for the implicit-alias
diff --git a/rust/hogql/parser/src/parse/template.rs b/rust/hogql/parser/src/parse/template.rs
index fff6bb915fb4..febc1648385d 100644
--- a/rust/hogql/parser/src/parse/template.rs
+++ b/rust/hogql/parser/src/parse/template.rs
@@ -252,16 +252,22 @@ pub(super) fn parse_template_body<E: Emitter + Clone>(
));
}
if chunks.is_empty() {
- // Empty body — cpp spans the empty-string Constant over the WHOLE
- // `f'…'` token (there is no interior text to span), not the zero-width
- // gap between the quotes. The token runs from `body_offset - 2` (`f'`)
- // through `body_end + 1` (past the closing `'`).
+ // Empty body — cpp spans the empty-string Constant over the WHOLE `f'…'`
+ // token (no interior text), from `body_offset - 2` (`f'`) through the
+ // closing `'`. Inline `f'…'` has that quote at `body_end` (span ends
+ // `body_end + 1`); the standalone `parse_full_template_string` entry has
+ // no trailing quote (`body_end == full_src.len()`), so it ends at `body_end`.
+ let token_end = if body_end < full_src.len() {
+ body_end + 1
+ } else {
+ body_end
+ };
return Ok(wrap_literal_chunk(
emit,
full_src,
String::new(),
- body_offset - 2,
- body_end + 1,
+ body_offset.saturating_sub(2),
+ token_end,
));
}
// A single-chunk template IS that chunk — whether a literal
diff --git a/uv.lock b/uv.lock
index e1745405b9cd..9b6a96822d0b 100644
--- a/uv.lock
+++ b/uv.lock
@@ -11,7 +11,7 @@ resolution-markers = [
]
[options]
-exclude-newer = "2026-06-11T08:15:12.733489Z"
+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.92"
+version = "1.3.96"
source = { registry = "https://pypi.org/simple" }
-sdist = { url = "https://files.pythonhosted.org/packages/fc/62/dd0b370956736088e231f8ac258e4fcfb07dae65618d3d9828ea6d0afe70/hogql_parser_rs-1.3.92.tar.gz", hash = "sha256:6181af7d101e0eade7287ae667f6b34336fcdede9a014ced738ac79e56983066", size = 291627, upload-time = "2026-06-17T15:57:33.661Z" }
+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" }
wheels = [
- { url = "https://files.pythonhosted.org/packages/e2/64/2ecb5f10116ad85afd37c8818747fd55ce98d3964136e04ebc767ba0f31a/hogql_parser_rs-1.3.92-cp312-abi3-macosx_10_12_x86_64.whl", hash = "sha256:fb9415be40765f55d2a5dde30e3a1b91419aaa02fe9818a66ba68105ab1adf7e", size = 730170, upload-time = "2026-06-17T15:57:21.853Z" },
- { url = "https://files.pythonhosted.org/packages/67/ca/aff3021bc372c3c52e9c00256d52b70063c2cc72dab0cd02493432e4fc27/hogql_parser_rs-1.3.92-cp312-abi3-macosx_11_0_arm64.whl", hash = "sha256:485b178ea90c4c69f625d197196bf16097ef4b30452c811fd9f51830e6502730", size = 687776, upload-time = "2026-06-17T15:57:24.189Z" },
- { url = "https://files.pythonhosted.org/packages/c1/0d/682560fbabb5e61df48ad15ba827479e2b81ba7a3cd8d96971a8817257f3/hogql_parser_rs-1.3.92-cp312-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:87902dae7ec18c029c5cc1360080dc3e7b651086e1dbcd95db44256f4bce4d74", size = 2476099, upload-time = "2026-06-17T15:57:26.091Z" },
- { url = "https://files.pythonhosted.org/packages/2a/5c/d7188f72ebea3375347cf3550fc6dd2ac732cf001674f90380ba865490dd/hogql_parser_rs-1.3.92-cp312-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:58d9db568e7597f250c1849ec0955dfbe9ad99aac5ec6b0ee7c78f55d3a94ab9", size = 2741059, upload-time = "2026-06-17T15:57:28.224Z" },
- { url = "https://files.pythonhosted.org/packages/2b/63/17bf2101a26d611de216e37c908b1c51a1444ea14eb5f44a841e99990b67/hogql_parser_rs-1.3.92-cp312-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:61e3f9d123971575ce72ca56564766a44f7e157ccb51729831d6a008e157d059", size = 2648503, upload-time = "2026-06-17T15:57:30.024Z" },
- { url = "https://files.pythonhosted.org/packages/fa/86/0a796462011329e9990fdb1a21159cc0b0b28b2590bbf89c1a9b0c361fc9/hogql_parser_rs-1.3.92-cp312-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:358b8a355bae555ecbbf6dae19071d881cee5d3dac4c1d4f6ec7ea5e6aca10db", size = 2703437, upload-time = "2026-06-17T15:57:31.726Z" },
+ { 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" },
]
[[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.92" },
+ { name = "hogql-parser-rs", specifier = "==1.3.96" },
{ 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" },