diff --git a/.editorconfig b/.editorconfig index 71498debe..9f04669ec 100644 --- a/.editorconfig +++ b/.editorconfig @@ -30,3 +30,6 @@ indent_size = 2 [*.{py,java,toml}] indent_style = space indent_size = 4 + +[*.g4] +indent_style = space \ No newline at end of file diff --git a/.github/labeler.yml b/.github/labeler.yml index 306623e97..a428b7058 100644 --- a/.github/labeler.yml +++ b/.github/labeler.yml @@ -28,6 +28,12 @@ docs: - changed-files: - any-glob-to-any-file: 'docs/**' +grammar: + - changed-files: + - any-glob-to-any-file: + - 'core-spec/grammar/**' + - 'compliance/expressions/**' + 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..234e10adc --- /dev/null +++ b/.github/workflows/grammar-ci.yml @@ -0,0 +1,68 @@ +# +# 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: + - "core-spec/grammar/**" + - "compliance/expressions/**" + - "core-spec/expression_language.md" + - "examples/**" + - ".github/workflows/grammar-ci.yml" + pull_request: + branches: ["main"] + paths: + - "core-spec/grammar/**" + - "compliance/expressions/**" + - "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 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/compliance/expressions/invalid.txt b/compliance/expressions/invalid.txt new file mode 100644 index 000000000..ae047f636 --- /dev/null +++ b/compliance/expressions/invalid.txt @@ -0,0 +1,40 @@ +# 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. + +# 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 +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) + +# DISTINCT needs an argument +SUM(DISTINCT) +COUNT(DISTINCT) diff --git a/compliance/expressions/valid.txt b/compliance/expressions/valid.txt new file mode 100644 index 000000000..598a8ec57 --- /dev/null +++ b/compliance/expressions/valid.txt @@ -0,0 +1,105 @@ +# 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. + +# 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. + +# 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/core-spec/expression_language.md b/core-spec/expression_language.md index cd0f38244..d343f5cd3 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/core-spec/grammar/OssieExpression.g4 b/core-spec/grammar/OssieExpression.g4 new file mode 100644 index 000000000..1084b7901 --- /dev/null +++ b/core-spec/grammar/OssieExpression.g4 @@ -0,0 +1,260 @@ +/* + * 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. +// +// 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 +; + +// 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)* | (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/core-spec/grammar/README.md b/core-spec/grammar/README.md new file mode 100644 index 000000000..2aee50114 --- /dev/null +++ b/core-spec/grammar/README.md @@ -0,0 +1,60 @@ + + +# Ossie expression grammar + +`OssieExpression.g4` is an [ANTLR 4](https://www.antlr.org/) grammar for the +`OSSIE_SQL_2026` expression language described in +[`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 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 + +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 core-spec/grammar/tests/ +``` + +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 core-spec/grammar/ && uv run --with ruff ruff format --check core-spec/grammar/` +(settings in `ruff.toml`). diff --git a/core-spec/grammar/ruff.toml b/core-spec/grammar/ruff.toml new file mode 100644 index 000000000..a04b3c710 --- /dev/null +++ b/core-spec/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/core-spec/grammar/tests/conftest.py b/core-spec/grammar/tests/conftest.py new file mode 100644 index 000000000..b74ef955e --- /dev/null +++ b/core-spec/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[3] +JAR = REPO / "dev" / "lib" / f"antlr4-{ANTLR_VERSION}-complete.jar" +GRAMMAR = Path(__file__).resolve().parents[1] / "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/core-spec/grammar/tests/test_expression_grammar.py b/core-spec/grammar/tests/test_expression_grammar.py new file mode 100644 index 000000000..8f04517f9 --- /dev/null +++ b/core-spec/grammar/tests/test_expression_grammar.py @@ -0,0 +1,141 @@ +# 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 + +REPO = Path(__file__).resolve().parents[3] +FIXTURES = REPO / "compliance" / "expressions" +EXAMPLES = REPO / "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]