From 40efe40fce4b1eb2019d76f761c7eeff88868221 Mon Sep 17 00:00:00 2001 From: Johannes Zemlin Date: Tue, 27 Oct 2026 21:56:08 +0100 Subject: [PATCH 1/4] feat(grammar): add ANTLR4 grammar for OSSIE_SQL_2026 expressions Add grammar/OssieExpression.g4, an ANTLR 4 grammar for the expression language in core-spec/expression_language.md, with Python tests that parse valid/invalid fixtures, the expressions in examples/, and check operator precedence. Add a grammar CI workflow, a README, a label rule, an .editorconfig rule for .g4 files, and a pointer from the spec. Co-Authored-By: Claude Sonnet 5.5 --- .editorconfig | 6 + .github/labeler.yml | 4 + .github/workflows/grammar-ci.yml | 66 ++++++ README.md | 1 + core-spec/expression_language.md | 5 + grammar/OssieExpression.g4 | 261 +++++++++++++++++++++++ grammar/README.md | 58 +++++ grammar/ruff.toml | 26 +++ grammar/tests/conftest.py | 89 ++++++++ grammar/tests/fixtures/invalid.txt | 32 +++ grammar/tests/fixtures/valid.txt | 103 +++++++++ grammar/tests/test_expression_grammar.py | 140 ++++++++++++ 12 files changed, 791 insertions(+) create mode 100644 .github/workflows/grammar-ci.yml create mode 100644 grammar/OssieExpression.g4 create mode 100644 grammar/README.md create mode 100644 grammar/ruff.toml create mode 100644 grammar/tests/conftest.py create mode 100644 grammar/tests/fixtures/invalid.txt create mode 100644 grammar/tests/fixtures/valid.txt create mode 100644 grammar/tests/test_expression_grammar.py diff --git a/.editorconfig b/.editorconfig index 71498debe..f2a0baf51 100644 --- a/.editorconfig +++ b/.editorconfig @@ -30,3 +30,9 @@ indent_size = 2 [*.{py,java,toml}] indent_style = space indent_size = 4 + +[*.g4] +indent_style = space + +[{Makefile,go.mod,*.go}] +indent_style = tab diff --git a/.github/labeler.yml b/.github/labeler.yml index 306623e97..7ff9e3c52 100644 --- a/.github/labeler.yml +++ b/.github/labeler.yml @@ -28,6 +28,10 @@ docs: - changed-files: - any-glob-to-any-file: 'docs/**' +grammar: + - changed-files: + - any-glob-to-any-file: 'grammar/**' + validation: - changed-files: - any-glob-to-any-file: 'validation/**' diff --git a/.github/workflows/grammar-ci.yml b/.github/workflows/grammar-ci.yml new file mode 100644 index 000000000..233d05ee9 --- /dev/null +++ b/.github/workflows/grammar-ci.yml @@ -0,0 +1,66 @@ +# +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +name: Grammar CI + +on: + push: + branches: ["main"] + paths: + - "grammar/**" + - "core-spec/expression_language.md" + - "examples/**" + - ".github/workflows/grammar-ci.yml" + pull_request: + branches: ["main"] + paths: + - "grammar/**" + - "core-spec/expression_language.md" + - "examples/**" + - ".github/workflows/grammar-ci.yml" + +permissions: + contents: read + +jobs: + test: + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + python-version: ["3.11", "3.14"] + + steps: + - name: Checkout project + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 + with: + python-version: ${{ matrix.python-version }} + + - name: Install uv + uses: astral-sh/setup-uv@07a047e608db84b3d8c06cd9a7c7dcc9c355c18e # v10.3.2 + with: + version: "0.12.19" + + # The tests download the ANTLR 4.13.2 jar from Maven Central into dev/lib/ and verify its SHA-256. + - name: Run grammar tests + run: > + uv run --with pytest --with pyyaml --with antlr4-python3-runtime==4.13.2 + -m pytest grammar/tests/ diff --git a/README.md b/README.md index d63bf3f14..d99c66ea4 100644 --- a/README.md +++ b/README.md @@ -33,6 +33,7 @@ Apache Ossie provides a single JSON- and YAML-based specification that any tool - [`dev/`](dev/) — Development utilities. - [`docs/`](docs/) — Project documentation and overview. - [`examples/`](examples/) — Example semantic models, including a complete TPC-DS model. +- [`grammar/`](grammar/) — non-authoritative ANTLR 4 grammar for the `OSSIE_SQL_2026` expression language, with tests. - [`extensions/`](extensions/) — Community registry of dialect and vendor tokens used in extension metadata. - [`ontology/`](ontology/) — The ontology specification (`ontology.md`), its machine-readable schemas (`ontology.json`, `mapping.json`), and supporting documentation. - [`python/`](python/) — Python SDK with Pydantic v2 models for parsing, validating, and serializing Ossie documents. diff --git a/core-spec/expression_language.md b/core-spec/expression_language.md index cd0f38244..e168be250 100644 --- a/core-spec/expression_language.md +++ b/core-spec/expression_language.md @@ -844,6 +844,11 @@ Implementations MAY support additional functions through dialect extensions. The --- +## ANTLR4 Grammar + +A machine-readable ANTLR 4 grammar for this language is available in [`grammar/`](../grammar/). It is a +tooling aid; where it and this document differ, this document is authoritative. + ## Version History | Version | Date | Changes | diff --git a/grammar/OssieExpression.g4 b/grammar/OssieExpression.g4 new file mode 100644 index 000000000..37c0f13af --- /dev/null +++ b/grammar/OssieExpression.g4 @@ -0,0 +1,261 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +grammar OssieExpression; + +options { caseInsensitive = true; } + +// Ossie expression language (OSSIE_SQL_2026), see core-spec/expression_language.md. +// +// Only expressions are covered -- no SELECT/FROM/WHERE/GROUP BY, no subqueries. The grammar is +// deliberately lenient about function names and arities: every function is parsed as +// `name(args)`, and which functions exist (SUM, DATE_TRUNC, COALESCE, ...) is a matter for +// semantic checks, not syntax. Only constructs with their own syntax get their own rule: CASE, +// CAST, EXTRACT, POSITION, COUNT(*), DISTINCT, FILTER, WITHIN GROUP, OVER, typed literals. +// +// Operands of comparisons and predicates are arithmetic expressions: `a = b = c` needs parentheses. +// +// Deviations from the precedence list in the spec, which puts NOT above * and /: NOT sits between +// the predicates and AND, as in ANSI SQL -- otherwise `NOT a = b` would mean `(NOT a) = b`. +// `||` is parsed at the level of + and -. + +expression + : expr EOF +; + +// Boolean level: predicates over value expressions, combined with NOT, AND and OR. The operands of +// a predicate are value expressions, so the AND of BETWEEN cannot be taken for the logical one. +expr + : valueExpr op=(EQ | NEQ | LT | LTE | GT | GTE) valueExpr # comparisonExpr + | valueExpr NOT? BETWEEN valueExpr AND valueExpr # betweenExpr + | valueExpr NOT? IN LPAREN valueExpr (COMMA valueExpr)* RPAREN # inListExpr + | valueExpr NOT? op=(LIKE | ILIKE) valueExpr # likeExpr + | valueExpr IS NOT? NULL # isNullExpr + | valueExpr IS NOT? DISTINCT FROM valueExpr # isDistinctFromExpr + | valueExpr # valueOnlyExpr + | NOT expr # notExpr + | expr AND expr # andExpr + | expr OR expr # orExpr +; + +// Arithmetic and concatenation, tightest binding first. +valueExpr + : primary # primaryValue + | op=(PLUS | MINUS) valueExpr # unaryValue + | valueExpr op=(STAR | SLASH | PERCENT) valueExpr # multiplicativeValue + | valueExpr op=(PLUS | MINUS | CONCAT) valueExpr # additiveValue +; + +primary + : LPAREN expr RPAREN # parenthesized + | literal # literalPrimary + | caseExpr # casePrimary + | castExpr # castPrimary + | extractExpr # extractPrimary + | positionExpr # positionPrimary + | currentDatetime # currentDatetimePrimary + | functionCall # functionPrimary + | qualifiedName # referencePrimary +; + +// Field | Field '.' Field, and deeper: dataset.field, schema.dataset.field. +qualifiedName + : identifier (DOT identifier)* +; + +// A regular identifier is case-insensitive, a quoted one is exact ("" is a quote inside). +identifier + : IDENTIFIER + | QUOTED_IDENTIFIER + | nonReservedWord +; + +// Words with a meaning only in one place, so they stay usable as names elsewhere: a column called +// `date`, `first`, `range`. Reserved are only the words that would make an expression ambiguous. +nonReservedWord + : DATE | TIME | TIMESTAMP | TIMESTAMP_NTZ + | FIRST | LAST | NULLS | ROW | ROWS | RANGE | UNBOUNDED | PRECEDING | FOLLOWING | CURRENT + | FILTER | OVER | WITHIN | GROUP | PARTITION | ASC | DESC | POSITION +; + +literal + : NUMBER # numberLiteral + | STRING # stringLiteral + | (TRUE | FALSE) # booleanLiteral + | NULL # nullLiteral + | typeName=(DATE | TIME | TIMESTAMP | TIMESTAMP_NTZ) STRING # typedLiteral +; + +// CURRENT_DATE and CURRENT_DATE() are both valid. +currentDatetime + : (CURRENT_DATE | CURRENT_TIME | CURRENT_TIMESTAMP) (LPAREN RPAREN)? +; + +functionCall + : name=identifier LPAREN (STAR | DISTINCT? (expr (COMMA expr)*)?) RPAREN + withinGroup? filterClause? overClause? +; + +// PERCENTILE_CONT(p) WITHIN GROUP (ORDER BY expr) +withinGroup + : WITHIN GROUP LPAREN ORDER BY sortItem (COMMA sortItem)* RPAREN +; + +// (...) FILTER (WHERE ) +filterClause + : FILTER LPAREN WHERE expr RPAREN +; + +overClause + : OVER LPAREN + (PARTITION BY expr (COMMA expr)*)? + (ORDER BY sortItem (COMMA sortItem)*)? + frameClause? + RPAREN +; + +sortItem + : expr direction=(ASC | DESC)? (NULLS nulls=(FIRST | LAST))? +; + +frameClause + : unit=(ROWS | RANGE) (BETWEEN frameBound AND frameBound | frameBound) +; + +frameBound + : UNBOUNDED (PRECEDING | FOLLOWING) + | CURRENT ROW + | expr (PRECEDING | FOLLOWING) +; + +// Searched and simple CASE. +caseExpr + : CASE operand=expr? whenClause+ (ELSE elseResult=expr)? END +; + +whenClause + : WHEN condition=expr THEN result=expr +; + +castExpr + : (CAST | TRY_CAST) LPAREN expr AS dataType RPAREN +; + +// VARCHAR, INT, DECIMAL(10, 2), TIMESTAMP_NTZ, ...: the target types are plain words, which one is +// supported is not a syntax question. +dataType + : identifier (LPAREN NUMBER (COMMA NUMBER)? RPAREN)? +; + +// EXTRACT(YEAR FROM date_expr) +extractExpr + : EXTRACT LPAREN field=identifier FROM expr RPAREN +; + +// POSITION(substr IN str) +positionExpr + : POSITION LPAREN expr IN expr RPAREN +; + +// Keywords. Matching is case-insensitive (options above). +AND : 'AND' ; +AS : 'AS' ; +ASC : 'ASC' ; +BETWEEN : 'BETWEEN' ; +BY : 'BY' ; +CASE : 'CASE' ; +CAST : 'CAST' ; +CURRENT : 'CURRENT' ; +CURRENT_DATE : 'CURRENT_DATE' ; +CURRENT_TIME : 'CURRENT_TIME' ; +CURRENT_TIMESTAMP : 'CURRENT_TIMESTAMP' ; +DATE : 'DATE' ; +DESC : 'DESC' ; +DISTINCT : 'DISTINCT' ; +ELSE : 'ELSE' ; +END : 'END' ; +EXTRACT : 'EXTRACT' ; +FALSE : 'FALSE' ; +FILTER : 'FILTER' ; +FIRST : 'FIRST' ; +FOLLOWING : 'FOLLOWING' ; +FROM : 'FROM' ; +GROUP : 'GROUP' ; +ILIKE : 'ILIKE' ; +IN : 'IN' ; +IS : 'IS' ; +LAST : 'LAST' ; +LIKE : 'LIKE' ; +NOT : 'NOT' ; +NULL : 'NULL' ; +NULLS : 'NULLS' ; +OR : 'OR' ; +ORDER : 'ORDER' ; +OVER : 'OVER' ; +PARTITION : 'PARTITION' ; +POSITION : 'POSITION' ; +PRECEDING : 'PRECEDING' ; +RANGE : 'RANGE' ; +ROW : 'ROW' ; +ROWS : 'ROWS' ; +THEN : 'THEN' ; +TIME : 'TIME' ; +TIMESTAMP : 'TIMESTAMP' ; +TIMESTAMP_NTZ : 'TIMESTAMP_NTZ' ; +TRUE : 'TRUE' ; +TRY_CAST : 'TRY_CAST' ; +UNBOUNDED : 'UNBOUNDED' ; +WHEN : 'WHEN' ; +WHERE : 'WHERE' ; +WITHIN : 'WITHIN' ; + +EQ : '=' ; +NEQ : '<>' | '!=' ; +LTE : '<=' ; +GTE : '>=' ; +LT : '<' ; +GT : '>' ; +PLUS : '+' ; +MINUS : '-' ; +STAR : '*' ; +SLASH : '/' ; +PERCENT : '%' ; +CONCAT : '||' ; +LPAREN : '(' ; +RPAREN : ')' ; +COMMA : ',' ; +DOT : '.' ; + +// 42, 3.14, .5, 1e10, 1.5E-3. The sign is an operator. +NUMBER : DIGIT+ ('.' DIGIT*)? EXPONENT? + | '.' DIGIT+ EXPONENT? + ; + +// 'it''s' +STRING : '\'' ( ~'\'' | '\'\'' )* '\'' ; + +IDENTIFIER : [A-Z_] [A-Z_0-9$]* ; +QUOTED_IDENTIFIER : '"' ( ~'"' | '""' )* '"' ; + +LINE_COMMENT : '--' ~[\r\n]* -> channel(HIDDEN) ; +BLOCK_COMMENT : '/*' .*? '*/' -> channel(HIDDEN) ; +WS : [ \t\r\n]+ -> channel(HIDDEN) ; + +fragment DIGIT : [0-9] ; +fragment EXPONENT : 'E' [+-]? DIGIT+ ; diff --git a/grammar/README.md b/grammar/README.md new file mode 100644 index 000000000..0b0e43b58 --- /dev/null +++ b/grammar/README.md @@ -0,0 +1,58 @@ + + +# Ossie expression grammar + +`OssieExpression.g4` is an [ANTLR 4](https://www.antlr.org/) grammar for the +`OSSIE_SQL_2026` expression language described in +[`core-spec/expression_language.md`](../core-spec/expression_language.md). It covers +expressions only (no `SELECT`, `FROM`, `WHERE`, subqueries). Function names and arities +are not checked: every function parses as `name(args)`, which functions exist is a +semantic question. Constructs with their own syntax (`CASE`, `CAST`, `EXTRACT`, +`POSITION`, `FILTER`, `WITHIN GROUP`, `OVER`, typed literals) have their own rules. + +The entry rule is `expression`. The generated parser is not committed. + +## Where the grammar goes beyond the spec text + +The precedence levels follow the list in the spec's "Operator Precedence" section. Two points +are not decided there: + +- `||` is accepted, at the level of `+` and `-`. The spec's portable form is `CONCAT(a, b)`; + `a || b` only appears as a dialect form. +- Comparisons do not chain: `a = b = c` needs parentheses. + +## Tests + +The tests generate the Python parser with ANTLR 4.13.2 and need Java 11+. The first run downloads +the ANTLR jar from Maven Central into `dev/lib/` (git-ignored, like Apache RAT) and checks it +against a pinned SHA-256; ANTLR is BSD-3-Clause licensed. + +```bash +uv run --with pytest --with pyyaml --with antlr4-python3-runtime==4.13.2 \ + -m pytest grammar/tests/ +``` + +`tests/fixtures/*.txt` hold one expression per line (`#` starts a comment): +`valid.txt` must parse, `invalid.txt` must be rejected. `test_example_models_parse` also +parses every `ANSI_SQL` / `OSSIE_SQL_2026` expression and top-level `sql` in `examples/*.yaml`. + +Python style is checked with `uv run --with ruff ruff check grammar/ && uv run --with ruff ruff format --check grammar/` +(settings in `ruff.toml`). diff --git a/grammar/ruff.toml b/grammar/ruff.toml new file mode 100644 index 000000000..a04b3c710 --- /dev/null +++ b/grammar/ruff.toml @@ -0,0 +1,26 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +# Ruff settings for grammar/ only; the repository has no shared ruff configuration yet. +line-length = 100 +target-version = "py311" + +# Parser files generated by ANTLR (if someone generates them into this folder) are not linted. +extend-exclude = ["OssieExpression*.py", "gen", "generated"] + +[lint] +select = ["E", "F", "I", "B", "UP"] diff --git a/grammar/tests/conftest.py b/grammar/tests/conftest.py new file mode 100644 index 000000000..061b07817 --- /dev/null +++ b/grammar/tests/conftest.py @@ -0,0 +1,89 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +"""Build the Python parser from OssieExpression.g4 once per test session. + +The ANTLR tool jar is downloaded from Maven Central into dev/lib/ (git-ignored, the same place +dev/check-license keeps Apache RAT) and checked against a pinned SHA-256 before it is run. +""" + +import hashlib +import shutil +import subprocess +import sys +import urllib.request +from pathlib import Path + +import pytest + +ANTLR_VERSION = "4.13.2" +# SHA-256 of antlr4-4.13.2-complete.jar; its SHA-1 matches the .sha1 published on Maven Central. +ANTLR_SHA256 = "eae2dfa119a64327444672aff63e9ec35a20180dc5b8090b7a6ab85125df4d76" +ANTLR_URL = ( + "https://repo1.maven.org/maven2/org/antlr/antlr4/" + f"{ANTLR_VERSION}/antlr4-{ANTLR_VERSION}-complete.jar" +) + +REPO = Path(__file__).resolve().parents[2] +JAR = REPO / "dev" / "lib" / f"antlr4-{ANTLR_VERSION}-complete.jar" +GRAMMAR = Path(__file__).resolve().parent.parent / "OssieExpression.g4" + + +def sha256(path): + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def antlr_jar(): + """Return the verified ANTLR jar, downloading it first if it is not cached.""" + if not JAR.exists(): + JAR.parent.mkdir(parents=True, exist_ok=True) + tmp = JAR.with_suffix(".part") + with urllib.request.urlopen(ANTLR_URL, timeout=60) as response: + tmp.write_bytes(response.read()) + tmp.replace(JAR) + if sha256(JAR) != ANTLR_SHA256: + JAR.unlink() + pytest.fail(f"{JAR.name} does not match the pinned SHA-256; removed, rerun to download") + return JAR + + +@pytest.fixture(scope="session") +def ossie(tmp_path_factory): + """Generate the Python3 target with the ANTLR tool (needs Java 11+) and import it.""" + java = shutil.which("java") + if java is None: + pytest.fail("`java` not found: ANTLR needs Java 11+ on PATH") + out = tmp_path_factory.mktemp("gen") + subprocess.run( + [ + java, + "-jar", + str(antlr_jar()), + "-Dlanguage=Python3", + "-visitor", + "-Werror", + "-o", + str(out), + str(GRAMMAR), + ], + check=True, + ) + sys.path.insert(0, str(out)) + import OssieExpressionLexer + import OssieExpressionParser + + return OssieExpressionLexer.OssieExpressionLexer, OssieExpressionParser.OssieExpressionParser diff --git a/grammar/tests/fixtures/invalid.txt b/grammar/tests/fixtures/invalid.txt new file mode 100644 index 000000000..b9406aeab --- /dev/null +++ b/grammar/tests/fixtures/invalid.txt @@ -0,0 +1,32 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +1 + +SUM( +(a +a b +CASE WHEN a THEN b +x BETWEEN 1 +x IN () +SELECT a FROM t +a IS +'unterminated +CAST(x AS) + +# INTERVAL is not part of OSSIE_SQL_2026, date arithmetic uses DATEADD(part, amount, date_expr) +order_date + INTERVAL '7 days' +DATE_ADD(d, INTERVAL 7 DAY) diff --git a/grammar/tests/fixtures/valid.txt b/grammar/tests/fixtures/valid.txt new file mode 100644 index 000000000..c75b9edf7 --- /dev/null +++ b/grammar/tests/fixtures/valid.txt @@ -0,0 +1,103 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +# One expression per line; blank lines and lines starting with '#' are skipped. +# Each line exercises a different part of the grammar. Function names are not checked by the +# grammar, so one generic call stands for all of them. Expressions of examples/*.yaml are parsed +# by test_example_models_parse and are not repeated here. + +# Aggregates: COUNT(*), DISTINCT, WITHIN GROUP, FILTER +SUM(amount) +COUNT(*) +COUNT(DISTINCT customer_id) +SUM(DISTINCT amount) +PERCENTILE_CONT(0.75) WITHIN GROUP (ORDER BY x) +PERCENTILE_DISC(0.5) WITHIN GROUP (ORDER BY x DESC NULLS LAST) +SUM(amount) FILTER (WHERE status = 'completed') +COUNT(*) FILTER (WHERE status = 'completed') +COUNT(DISTINCT customer_id) FILTER (WHERE status = 'completed') + +# CASE, CAST, EXTRACT, POSITION +SUM(CASE WHEN status = 'completed' THEN amount END) +CASE WHEN a > 1 THEN 'x' WHEN a > 0 THEN 'y' ELSE 'z' END +CASE expression WHEN 1 THEN 'one' WHEN 2 THEN 'two' ELSE 'many' END +CAST('2024-01-15' AS DATE) +CAST(x AS DECIMAL(10, 2)) +TRY_CAST(x AS INTEGER) +EXTRACT(YEAR FROM date_expr) +POSITION('a' IN str) + +# Date and time: current datetime, typed literals, date arithmetic +CURRENT_DATE +CURRENT_DATE() +CURRENT_TIMESTAMP +CURRENT_TIME() +DATE '2024-01-15' +TIMESTAMP_NTZ '2024-01-15 10:30:00' +TIME '10:30:00' +DATEADD(day, 7, order_date) +DATEADD(month, -1, order_date) + +# Generic function calls +PI() +COALESCE(a, b, c) +ROUND(x, 2) + +# Operators and predicates +first_name || ' ' || last_name +x % 2 +-x + +y * (z - 1) / 2 +a <> b AND a != b AND a <= b AND a >= b +str LIKE 'a%' +str NOT LIKE 'a%' +str ILIKE '%b_' +x BETWEEN 1 AND 10 AND y NOT BETWEEN a AND b +x IN (1, 2, 3) +x NOT IN ('a', 'b') +x IS NULL +x IS NOT NULL +a IS DISTINCT FROM b +a IS NOT DISTINCT FROM b +NOT expr +NOT a = b +a AND b OR NOT c +TRUE AND NOT FALSE + +# Literals, identifiers, comments +1.5e-3 + .5 + 10. +NULL +"Order Date" +"say ""hi""" +dataset.field +schema.dataset."Field" +date +first +a -- trailing comment +a + 1 /* inline */ + 2 + +# Keywords are case-insensitive +sum(amount) filter (where status = 'completed') +case when a then b else c end + +# Window functions: PARTITION BY, ORDER BY, NULLS, frames +ROW_NUMBER() OVER (ORDER BY id) +RANK() OVER (ORDER BY revenue DESC NULLS LAST) +NTILE(4) OVER (PARTITION BY region ORDER BY revenue) +SUM(amount) OVER (PARTITION BY region) +AVG(amount) OVER (ORDER BY order_date ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) +SUM(amount) OVER (ORDER BY d RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) +amount / SUM(amount) OVER () * 100 diff --git a/grammar/tests/test_expression_grammar.py b/grammar/tests/test_expression_grammar.py new file mode 100644 index 000000000..a20315907 --- /dev/null +++ b/grammar/tests/test_expression_grammar.py @@ -0,0 +1,140 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +"""Parse the fixture expressions and check operator precedence.""" + +from pathlib import Path + +import yaml +from antlr4 import CommonTokenStream, InputStream +from antlr4.error.ErrorListener import ErrorListener + +FIXTURES = Path(__file__).parent / "fixtures" +EXAMPLES = Path(__file__).resolve().parents[2] / "examples" +PORTABLE_DIALECTS = {"ANSI_SQL", "OSSIE_SQL_2026"} + + +class Collect(ErrorListener): + def __init__(self): + self.errors = [] + + def syntaxError(self, recognizer, symbol, line, column, msg, e): + self.errors.append(f"{line}:{column} {msg}") + + +def parse(ossie, text): + """Return (tree, syntax errors) for the whole input.""" + lexer_cls, parser_cls = ossie + errors = Collect() + lexer = lexer_cls(InputStream(text)) + lexer.removeErrorListeners() + lexer.addErrorListener(errors) + parser = parser_cls(CommonTokenStream(lexer)) + parser.removeErrorListeners() + parser.addErrorListener(errors) + return parser.expression(), errors.errors + + +def lines(name): + """One expression per line; blank lines and lines starting with '#' are skipped.""" + text = (FIXTURES / name).read_text(encoding="utf-8") + return [line for line in text.splitlines() if line.strip() and not line.startswith("#")] + + +def top(ossie, text): + tree, errors = parse(ossie, text) + assert not errors, f"{text} -> {errors}" + return tree.expr() + + +def test_valid_expressions_parse(ossie): + failures = {line: e for line in lines("valid.txt") if (e := parse(ossie, line)[1])} + assert not failures + + +def test_invalid_expressions_are_rejected(ossie): + accepted = [line for line in lines("invalid.txt") if not parse(ossie, line)[1]] + assert not accepted + + +def portable_expressions(node): + """Yield every OSSIE_SQL_2026 / ANSI_SQL expression string in a loaded YAML document.""" + if isinstance(node, dict): + if isinstance(node.get("sql"), str): + yield node["sql"] + if node.get("dialect") in PORTABLE_DIALECTS and isinstance(node.get("expression"), str): + yield node["expression"] + for value in node.values(): + yield from portable_expressions(value) + elif isinstance(node, list): + for item in node: + yield from portable_expressions(item) + + +def example_expressions(): + for path in sorted(EXAMPLES.glob("*.yaml")): + for text in portable_expressions(yaml.safe_load(path.read_text(encoding="utf-8"))): + yield f"{path.name}: {text}", text + + +def test_example_models_parse(ossie): + """Every portable expression in examples/ must parse, so grammar and examples stay in sync.""" + found = list(example_expressions()) + assert found, "no expressions found in examples/" + failures = {label: e for label, text in found if (e := parse(ossie, text)[1])} + assert not failures + + +def kind(ctx): + return type(ctx).__name__.removesuffix("Context") + + +def test_multiplication_binds_tighter_than_addition(ossie): + value = top(ossie, "1 + 2 * 3") + assert kind(value) == "ValueOnlyExpr" + add = value.valueExpr() + assert kind(add) == "AdditiveValue" + assert kind(add.valueExpr(1)) == "MultiplicativeValue" + + +def test_not_binds_looser_than_comparison(ossie): + not_expr = top(ossie, "NOT a = b") + assert kind(not_expr) == "NotExpr" + assert kind(not_expr.expr()) == "ComparisonExpr" + + +def test_not_binds_tighter_than_and(ossie): + and_expr = top(ossie, "NOT a AND b") + assert kind(and_expr) == "AndExpr" + assert kind(and_expr.expr(0)) == "NotExpr" + + +def test_and_binds_tighter_than_or(ossie): + or_expr = top(ossie, "a OR b AND c") + assert kind(or_expr) == "OrExpr" + assert kind(or_expr.expr(1)) == "AndExpr" + + +def test_between_keeps_its_and_out_of_the_logical_and(ossie): + and_expr = top(ossie, "x BETWEEN 1 AND 2 AND y") + assert kind(and_expr) == "AndExpr" + assert kind(and_expr.expr(0)) == "BetweenExpr" + + +def test_chained_comparison_needs_parentheses(ossie): + assert parse(ossie, "a = b = c")[1] + assert not parse(ossie, "(a = b) = c")[1] From 13984276dc7fa9edc542009ba9106618e39041f9 Mon Sep 17 00:00:00 2001 From: Johannes Zemlin Date: Tue, 27 Oct 2026 22:06:32 +0100 Subject: [PATCH 2/4] refactor(grammar): move to core-spec/grammar and compliance/expressions Move the ANTLR grammar next to the spec (core-spec/grammar/) and the valid/invalid expression fixtures to compliance/expressions/ so any parser can run them. Require at least one argument after DISTINCT in function calls, and add SUM(DISTINCT) and COUNT(DISTINCT) to the invalid fixtures. Drop the stale NOT precedence note from the grammar header, update CI paths, labels and links, and ignore generated ANTLR output. Co-Authored-By: Claude Sonnet 5.5 --- .github/labeler.yml | 4 +++- .github/workflows/grammar-ci.yml | 8 +++++--- .gitignore | 7 +++++++ README.md | 2 +- .../fixtures => compliance/expressions}/invalid.txt | 8 ++++++++ .../fixtures => compliance/expressions}/valid.txt | 4 +++- core-spec/expression_language.md | 2 +- {grammar => core-spec/grammar}/OssieExpression.g4 | 7 +++---- {grammar => core-spec/grammar}/README.md | 12 +++++++----- {grammar => core-spec/grammar}/ruff.toml | 0 {grammar => core-spec/grammar}/tests/conftest.py | 4 ++-- .../grammar}/tests/test_expression_grammar.py | 5 +++-- 12 files changed, 43 insertions(+), 20 deletions(-) rename {grammar/tests/fixtures => compliance/expressions}/invalid.txt (77%) rename {grammar/tests/fixtures => compliance/expressions}/valid.txt (91%) rename {grammar => core-spec/grammar}/OssieExpression.g4 (96%) rename {grammar => core-spec/grammar}/README.md (79%) rename {grammar => core-spec/grammar}/ruff.toml (100%) rename {grammar => core-spec/grammar}/tests/conftest.py (96%) rename {grammar => core-spec/grammar}/tests/test_expression_grammar.py (97%) diff --git a/.github/labeler.yml b/.github/labeler.yml index 7ff9e3c52..a428b7058 100644 --- a/.github/labeler.yml +++ b/.github/labeler.yml @@ -30,7 +30,9 @@ docs: grammar: - changed-files: - - any-glob-to-any-file: 'grammar/**' + - any-glob-to-any-file: + - 'core-spec/grammar/**' + - 'compliance/expressions/**' validation: - changed-files: diff --git a/.github/workflows/grammar-ci.yml b/.github/workflows/grammar-ci.yml index 233d05ee9..234e10adc 100644 --- a/.github/workflows/grammar-ci.yml +++ b/.github/workflows/grammar-ci.yml @@ -22,14 +22,16 @@ on: push: branches: ["main"] paths: - - "grammar/**" + - "core-spec/grammar/**" + - "compliance/expressions/**" - "core-spec/expression_language.md" - "examples/**" - ".github/workflows/grammar-ci.yml" pull_request: branches: ["main"] paths: - - "grammar/**" + - "core-spec/grammar/**" + - "compliance/expressions/**" - "core-spec/expression_language.md" - "examples/**" - ".github/workflows/grammar-ci.yml" @@ -63,4 +65,4 @@ jobs: - name: Run grammar tests run: > uv run --with pytest --with pyyaml --with antlr4-python3-runtime==4.13.2 - -m pytest grammar/tests/ + -m pytest core-spec/grammar/tests/ diff --git a/.gitignore b/.gitignore index 0ec52cf14..cf7c7a063 100644 --- a/.gitignore +++ b/.gitignore @@ -30,3 +30,10 @@ # Apache RAT (downloaded by dev/check-license) dev/lib/ + +# ANTLR generated output (core-spec/grammar/) +core-spec/grammar/**/gen/ +core-spec/grammar/**/OssieExpression*.py +core-spec/grammar/**/*.java +core-spec/grammar/**/*.interp +core-spec/grammar/**/*.tokens diff --git a/README.md b/README.md index d99c66ea4..387946426 100644 --- a/README.md +++ b/README.md @@ -33,7 +33,7 @@ Apache Ossie provides a single JSON- and YAML-based specification that any tool - [`dev/`](dev/) — Development utilities. - [`docs/`](docs/) — Project documentation and overview. - [`examples/`](examples/) — Example semantic models, including a complete TPC-DS model. -- [`grammar/`](grammar/) — non-authoritative ANTLR 4 grammar for the `OSSIE_SQL_2026` expression language, with tests. +- [`core-spec/grammar/`](core-spec/grammar/) — non-authoritative ANTLR 4 grammar for the `OSSIE_SQL_2026` expression language, with tests. - [`extensions/`](extensions/) — Community registry of dialect and vendor tokens used in extension metadata. - [`ontology/`](ontology/) — The ontology specification (`ontology.md`), its machine-readable schemas (`ontology.json`, `mapping.json`), and supporting documentation. - [`python/`](python/) — Python SDK with Pydantic v2 models for parsing, validating, and serializing Ossie documents. diff --git a/grammar/tests/fixtures/invalid.txt b/compliance/expressions/invalid.txt similarity index 77% rename from grammar/tests/fixtures/invalid.txt rename to compliance/expressions/invalid.txt index b9406aeab..ae047f636 100644 --- a/grammar/tests/fixtures/invalid.txt +++ b/compliance/expressions/invalid.txt @@ -15,6 +15,10 @@ # specific language governing permissions and limitations # under the License. +# Conformance fixture for the OSSIE_SQL_2026 expression language: every line must be rejected by a +# parser for it (valid.txt: every line must be accepted). One expression per line; blank lines +# and lines starting with '#' are skipped. + 1 + SUM( (a @@ -30,3 +34,7 @@ CAST(x AS) # INTERVAL is not part of OSSIE_SQL_2026, date arithmetic uses DATEADD(part, amount, date_expr) order_date + INTERVAL '7 days' DATE_ADD(d, INTERVAL 7 DAY) + +# DISTINCT needs an argument +SUM(DISTINCT) +COUNT(DISTINCT) diff --git a/grammar/tests/fixtures/valid.txt b/compliance/expressions/valid.txt similarity index 91% rename from grammar/tests/fixtures/valid.txt rename to compliance/expressions/valid.txt index c75b9edf7..598a8ec57 100644 --- a/grammar/tests/fixtures/valid.txt +++ b/compliance/expressions/valid.txt @@ -15,7 +15,9 @@ # specific language governing permissions and limitations # under the License. -# One expression per line; blank lines and lines starting with '#' are skipped. +# Conformance fixture for the OSSIE_SQL_2026 expression language: every line must be accepted by a +# parser for it (invalid.txt: every line must be rejected). One expression per line; blank lines +# and lines starting with '#' are skipped. The reference parser is core-spec/grammar/. # Each line exercises a different part of the grammar. Function names are not checked by the # grammar, so one generic call stands for all of them. Expressions of examples/*.yaml are parsed # by test_example_models_parse and are not repeated here. diff --git a/core-spec/expression_language.md b/core-spec/expression_language.md index e168be250..d343f5cd3 100644 --- a/core-spec/expression_language.md +++ b/core-spec/expression_language.md @@ -846,7 +846,7 @@ Implementations MAY support additional functions through dialect extensions. The ## ANTLR4 Grammar -A machine-readable ANTLR 4 grammar for this language is available in [`grammar/`](../grammar/). It is a +A machine-readable ANTLR 4 grammar for this language is available in [`grammar/`](grammar/). It is a tooling aid; where it and this document differ, this document is authoritative. ## Version History diff --git a/grammar/OssieExpression.g4 b/core-spec/grammar/OssieExpression.g4 similarity index 96% rename from grammar/OssieExpression.g4 rename to core-spec/grammar/OssieExpression.g4 index 37c0f13af..1084b7901 100644 --- a/grammar/OssieExpression.g4 +++ b/core-spec/grammar/OssieExpression.g4 @@ -31,9 +31,8 @@ options { caseInsensitive = true; } // // Operands of comparisons and predicates are arithmetic expressions: `a = b = c` needs parentheses. // -// Deviations from the precedence list in the spec, which puts NOT above * and /: NOT sits between -// the predicates and AND, as in ANSI SQL -- otherwise `NOT a = b` would mean `(NOT a) = b`. -// `||` is parsed at the level of + and -. +// Precedence follows the list in the spec. The spec does not say where `||` sits: it is parsed at +// the level of + and -. expression : expr EOF @@ -108,7 +107,7 @@ currentDatetime ; functionCall - : name=identifier LPAREN (STAR | DISTINCT? (expr (COMMA expr)*)?) RPAREN + : name=identifier LPAREN (STAR | DISTINCT expr (COMMA expr)* | (expr (COMMA expr)*)?) RPAREN withinGroup? filterClause? overClause? ; diff --git a/grammar/README.md b/core-spec/grammar/README.md similarity index 79% rename from grammar/README.md rename to core-spec/grammar/README.md index 0b0e43b58..2aee50114 100644 --- a/grammar/README.md +++ b/core-spec/grammar/README.md @@ -22,13 +22,14 @@ under the License. `OssieExpression.g4` is an [ANTLR 4](https://www.antlr.org/) grammar for the `OSSIE_SQL_2026` expression language described in -[`core-spec/expression_language.md`](../core-spec/expression_language.md). It covers +[`expression_language.md`](../expression_language.md). It covers expressions only (no `SELECT`, `FROM`, `WHERE`, subqueries). Function names and arities are not checked: every function parses as `name(args)`, which functions exist is a semantic question. Constructs with their own syntax (`CASE`, `CAST`, `EXTRACT`, `POSITION`, `FILTER`, `WITHIN GROUP`, `OVER`, typed literals) have their own rules. -The entry rule is `expression`. The generated parser is not committed. +The spec is normative, the grammar is a reference artifact. The entry rule is `expression`. The +generated parser is not committed. ## Where the grammar goes beyond the spec text @@ -47,12 +48,13 @@ against a pinned SHA-256; ANTLR is BSD-3-Clause licensed. ```bash uv run --with pytest --with pyyaml --with antlr4-python3-runtime==4.13.2 \ - -m pytest grammar/tests/ + -m pytest core-spec/grammar/tests/ ``` -`tests/fixtures/*.txt` hold one expression per line (`#` starts a comment): +The conformance fixtures are in [`compliance/expressions/`](../../compliance/expressions/), so any +parser can run them. They hold one expression per line (`#` starts a comment): `valid.txt` must parse, `invalid.txt` must be rejected. `test_example_models_parse` also parses every `ANSI_SQL` / `OSSIE_SQL_2026` expression and top-level `sql` in `examples/*.yaml`. -Python style is checked with `uv run --with ruff ruff check grammar/ && uv run --with ruff ruff format --check grammar/` +Python style is checked with `uv run --with ruff ruff check core-spec/grammar/ && uv run --with ruff ruff format --check core-spec/grammar/` (settings in `ruff.toml`). diff --git a/grammar/ruff.toml b/core-spec/grammar/ruff.toml similarity index 100% rename from grammar/ruff.toml rename to core-spec/grammar/ruff.toml diff --git a/grammar/tests/conftest.py b/core-spec/grammar/tests/conftest.py similarity index 96% rename from grammar/tests/conftest.py rename to core-spec/grammar/tests/conftest.py index 061b07817..b74ef955e 100644 --- a/grammar/tests/conftest.py +++ b/core-spec/grammar/tests/conftest.py @@ -38,9 +38,9 @@ f"{ANTLR_VERSION}/antlr4-{ANTLR_VERSION}-complete.jar" ) -REPO = Path(__file__).resolve().parents[2] +REPO = Path(__file__).resolve().parents[3] JAR = REPO / "dev" / "lib" / f"antlr4-{ANTLR_VERSION}-complete.jar" -GRAMMAR = Path(__file__).resolve().parent.parent / "OssieExpression.g4" +GRAMMAR = Path(__file__).resolve().parents[1] / "OssieExpression.g4" def sha256(path): diff --git a/grammar/tests/test_expression_grammar.py b/core-spec/grammar/tests/test_expression_grammar.py similarity index 97% rename from grammar/tests/test_expression_grammar.py rename to core-spec/grammar/tests/test_expression_grammar.py index a20315907..8f04517f9 100644 --- a/grammar/tests/test_expression_grammar.py +++ b/core-spec/grammar/tests/test_expression_grammar.py @@ -23,8 +23,9 @@ from antlr4 import CommonTokenStream, InputStream from antlr4.error.ErrorListener import ErrorListener -FIXTURES = Path(__file__).parent / "fixtures" -EXAMPLES = Path(__file__).resolve().parents[2] / "examples" +REPO = Path(__file__).resolve().parents[3] +FIXTURES = REPO / "compliance" / "expressions" +EXAMPLES = REPO / "examples" PORTABLE_DIALECTS = {"ANSI_SQL", "OSSIE_SQL_2026"} From 6698f976d1310e7ac2445d05d79319ff1bb359e7 Mon Sep 17 00:00:00 2001 From: Johannes Zemlin Date: Tue, 27 Oct 2026 23:28:59 +0100 Subject: [PATCH 3/4] docs(readme): restore README.md, grammar is already linked from core-spec/expression_language.md --- README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/README.md b/README.md index 387946426..d63bf3f14 100644 --- a/README.md +++ b/README.md @@ -33,7 +33,6 @@ Apache Ossie provides a single JSON- and YAML-based specification that any tool - [`dev/`](dev/) — Development utilities. - [`docs/`](docs/) — Project documentation and overview. - [`examples/`](examples/) — Example semantic models, including a complete TPC-DS model. -- [`core-spec/grammar/`](core-spec/grammar/) — non-authoritative ANTLR 4 grammar for the `OSSIE_SQL_2026` expression language, with tests. - [`extensions/`](extensions/) — Community registry of dialect and vendor tokens used in extension metadata. - [`ontology/`](ontology/) — The ontology specification (`ontology.md`), its machine-readable schemas (`ontology.json`, `mapping.json`), and supporting documentation. - [`python/`](python/) — Python SDK with Pydantic v2 models for parsing, validating, and serializing Ossie documents. From 432993fae0f1ec1e5d1caa089e00a80ce62dbbbf Mon Sep 17 00:00:00 2001 From: Johannes Zemlin Date: Mon, 2 Nov 2026 18:45:45 +0100 Subject: [PATCH 4/4] chore(editorconfig): remove unintended tab-indent block The [{Makefile,go.mod,*.go}] section was added by mistake and is unrelated to the grammar. Keep only the [*.g4] block. --- .editorconfig | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/.editorconfig b/.editorconfig index f2a0baf51..9f04669ec 100644 --- a/.editorconfig +++ b/.editorconfig @@ -32,7 +32,4 @@ indent_style = space indent_size = 4 [*.g4] -indent_style = space - -[{Makefile,go.mod,*.go}] -indent_style = tab +indent_style = space \ No newline at end of file