From 3969b843867b3b1856b454e770db554f88dfec73 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Tue, 24 Nov 2026 21:48:01 +0000 Subject: [PATCH 01/15] fix[next]: take CollapseTuple's remapped-argument names from uids FLATTEN_AS_FIELDOP_ARGS named the let variable binding a flattened tuple argument __ct_flat_remapped_{i}, with a counter restarting at 0 on every application. Flattening a nested tuple argument inside a let that survived the previous flattening rebound the same name and captured the outer references. --- .../iterator/transforms/collapse_tuple.py | 5 +- .../transforms_tests/test_collapse_tuple.py | 59 +++++++++++++++++++ 2 files changed, 60 insertions(+), 4 deletions(-) diff --git a/src/gt4py/next/iterator/transforms/collapse_tuple.py b/src/gt4py/next/iterator/transforms/collapse_tuple.py index 08ad5c9ede..f399749565 100644 --- a/src/gt4py/next/iterator/transforms/collapse_tuple.py +++ b/src/gt4py/next/iterator/transforms/collapse_tuple.py @@ -587,10 +587,7 @@ def transform_flatten_as_fieldop_args( for param, arg in zip(stencil.params, node.args, strict=True): if isinstance(arg.type, ts.TupleType): assert isinstance(param.type, it_ts.IteratorType) - ref_to_remapped_arg = im.ref( - f"__ct_flat_remapped_{len(remapped_args)}", - arg.type, - ) + ref_to_remapped_arg = im.ref(next(self.uids["__ct_flat_remapped"]), arg.type) self._preserve_annex(arg, ref_to_remapped_arg) remapped_args[im.sym(ref_to_remapped_arg.id, arg.type)] = arg new_params_inner, lift_params = [], [] diff --git a/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_collapse_tuple.py b/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_collapse_tuple.py index 18d1bdc08c..995b6d841f 100644 --- a/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_collapse_tuple.py +++ b/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_collapse_tuple.py @@ -472,3 +472,62 @@ def test_flatten_as_fieldop_args_scan(uids: utils.IDGeneratorPool): uids=uids, ) assert actual == expected + + +def test_flatten_as_fieldop_args_no_capture_of_remapped_args(uids: utils.IDGeneratorPool): + # `{a + 1}` is not trivial, so the let binding it survives the first flattening and the + # second flattening (of `d[0]` and `d[1]`) happens inside it. + d_type = ts.TupleType( + types=[ + ts.TupleType(types=[int_type, int_type, int_type]), + ts.TupleType(types=[int_type, int_type]), + int_type, + ] + ) + x_type = ts.TupleType(types=[int_type]) + testee = im.as_fieldop( + im.lambda_( + im.sym("x", it_ts.IteratorType(position_dims=[], defined_dims=[], element_type=x_type)), + im.sym("d", it_ts.IteratorType(position_dims=[], defined_dims=[], element_type=d_type)), + )( + im.plus( + im.tuple_get(0, im.deref("x")), + im.plus( + im.tuple_get(2, im.tuple_get(0, im.deref("d"))), + im.tuple_get(2, im.deref("d")), + ), + ) + ) + )(im.make_tuple(im.plus(im.ref("a", int_type), 1)), im.ref("d", d_type)) + expected = im.as_fieldop( + im.lambda_( + "__ct_flat_el_0_x", + "__ct_flat_el_0_0_d", + "__ct_flat_el_0_1_d", + "__ct_flat_el_0_2_d", + "__ct_flat_el_1_0_d", + "__ct_flat_el_1_1_d", + "__ct_flat_el_2_d", + )( + im.plus( + im.deref("__ct_flat_el_0_x"), + im.plus(im.deref("__ct_flat_el_0_2_d"), im.deref("__ct_flat_el_2_d")), + ) + ) + )( + im.plus("a", 1), + im.tuple_get(0, im.tuple_get(0, "d")), + im.tuple_get(1, im.tuple_get(0, "d")), + im.tuple_get(2, im.tuple_get(0, "d")), + im.tuple_get(0, im.tuple_get(1, "d")), + im.tuple_get(1, im.tuple_get(1, "d")), + im.tuple_get(2, "d"), + ) + actual = CollapseTuple.apply( + testee, + enabled_transformations=~CollapseTuple.Transformation.PROPAGATE_TO_IF_ON_TUPLES, + allow_undeclared_symbols=True, + within_stencil=False, + uids=uids, + ) + assert actual == expected From 764f97fbae758cc115c413d0a1b33893c1733ba1 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Tue, 24 Nov 2026 21:48:01 +0000 Subject: [PATCH 02/15] fix[next]: lower attribute access on named collections in programs A program body like domain={E: (d.edges.lb, d.edges.ub)} failed on every compiled backend because ProgramLowering had no visit_Attribute. --- src/gt4py/next/ffront/past_to_itir.py | 5 + .../ffront_tests/test_named_collections.py | 93 +++++++++++++++++++ .../ffront_tests/test_past_to_gtir.py | 39 +++++++- 3 files changed, 136 insertions(+), 1 deletion(-) diff --git a/src/gt4py/next/ffront/past_to_itir.py b/src/gt4py/next/ffront/past_to_itir.py index cd908fca14..c6d5bac023 100644 --- a/src/gt4py/next/ffront/past_to_itir.py +++ b/src/gt4py/next/ffront/past_to_itir.py @@ -510,6 +510,11 @@ def visit_Symbol(self, node: past.Symbol, **kwargs: Any) -> itir.Sym: new_symbol_type = node.type return itir.Sym(id=node.id, type=new_symbol_type) + def visit_Attribute(self, node: past.Attribute, **kwargs: Any) -> itir.FunCall: + named_tup_type = node.value.type + assert isinstance(named_tup_type, ts.NamedCollectionType) + return im.tuple_get(named_tup_type.keys.index(node.attr), self.visit(node.value, **kwargs)) + def visit_BinOp(self, node: past.BinOp, **kwargs: Any) -> itir.FunCall: return itir.FunCall( fun=itir.SymRef(id=node.op.value), diff --git a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_named_collections.py b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_named_collections.py index 77b793f93b..d796872be4 100644 --- a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_named_collections.py +++ b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_named_collections.py @@ -657,3 +657,96 @@ def testee( np.where(vertex_mask, c, d), ), ) + + +class IBounds(NamedTuple): + lower: gtx.int32 + split: gtx.int32 + upper: gtx.int32 + + +class JBounds(NamedTuple): + lower: gtx.int32 + upper: gtx.int32 + + +class NestedBounds(NamedTuple): + i: IBounds + j: JBounds + scale: gtx.int32 + + +@gtx.field_operator +def split_at_bound(a: cases.IJField, bounds: NestedBounds) -> cases.IJField: + return concat_where(IDim < bounds.i.split, a, bounds.scale * a) + + +@gtx.program +def nested_bounds_as_field_operator_arg_program( + a: cases.IJField, bounds: NestedBounds, out: cases.IJField +): + split_at_bound(a, bounds, out=out) + + +@gtx.field_operator +def scale_by_bound(a: cases.IJField, bounds: NestedBounds) -> cases.IJField: + return bounds.scale * a + + +@gtx.program +def nested_bounds_as_domain_program(a: cases.IJField, bounds: NestedBounds, out: cases.IJField): + scale_by_bound( + a, + bounds, + out=out, + domain={ + IDim: (bounds.i.lower, bounds.i.upper), + JDim: (bounds.j.lower, bounds.j.upper), + }, + ) + + +def _nested_bounds(case: cases.Case) -> NestedBounds: + size_i, size_j = case.default_sizes[IDim], case.default_sizes[JDim] + return NestedBounds( + i=IBounds(lower=gtx.int32(1), split=gtx.int32(size_i // 2), upper=gtx.int32(size_i - 1)), + j=JBounds(lower=gtx.int32(1), upper=gtx.int32(size_j - 1)), + scale=gtx.int32(2), + ) + + +def _split_at_bound_ref(a: np.ndarray, bounds: NestedBounds) -> np.ndarray: + i = np.arange(a.shape[0])[:, np.newaxis] + return np.where(i < bounds.i.split, a, bounds.scale * a) + + +@pytest.mark.uses_tuple_args +@pytest.mark.uses_concat_where +def test_nested_named_tuple_as_field_operator_arg(cartesian_case): + bounds = _nested_bounds(cartesian_case) + a = cases.allocate(cartesian_case, nested_bounds_as_field_operator_arg_program, "a")() + out = cases.allocate(cartesian_case, nested_bounds_as_field_operator_arg_program, "out")() + + cases.verify( + cartesian_case, + nested_bounds_as_field_operator_arg_program, + a, + bounds, + out=out, + ref=_split_at_bound_ref(a.asnumpy(), bounds), + ) + + +@pytest.mark.uses_tuple_args +@pytest.mark.uses_scalar_in_domain +@pytest.mark.uses_scalar_in_domain_and_fo +def test_nested_named_tuple_as_domain(cartesian_case): + bounds = _nested_bounds(cartesian_case) + a = cases.allocate(cartesian_case, nested_bounds_as_domain_program, "a")() + out = cases.allocate(cartesian_case, nested_bounds_as_domain_program, "out").zeros()() + + ref = np.zeros_like(out.asnumpy()) + region = (slice(bounds.i.lower, bounds.i.upper), slice(bounds.j.lower, bounds.j.upper)) + ref[region] = bounds.scale * a.asnumpy()[region] + + cases.verify(cartesian_case, nested_bounds_as_domain_program, a, bounds, out=out, ref=ref) diff --git a/tests/next_tests/unit_tests/ffront_tests/test_past_to_gtir.py b/tests/next_tests/unit_tests/ffront_tests/test_past_to_gtir.py index 9db3567a2f..1794b86b5a 100644 --- a/tests/next_tests/unit_tests/ffront_tests/test_past_to_gtir.py +++ b/tests/next_tests/unit_tests/ffront_tests/test_past_to_gtir.py @@ -8,7 +8,7 @@ import re -from typing import Literal +from typing import Literal, NamedTuple import pytest @@ -174,6 +174,43 @@ def test_copy_restrict_lowering(copy_restrict_program_def, gtir_identity_fundef) program_pattern.match(itir_node, raise_exception=True) +class Bounds(NamedTuple): + lower: gtx.int32 + upper: gtx.int32 + + +class NestedBounds(NamedTuple): + scale: gtx.int32 + i: Bounds + + +def test_named_collection_attribute_in_domain(identity_def, gtir_identity_fundef): + identity = gtx.field_operator(identity_def) + + def program( + in_field: gtx.Field[[IDim], float64], + out: gtx.Field[[IDim], float64], + bounds: NestedBounds, + ): + identity(in_field, out=out, domain={IDim: (bounds.i.lower, bounds.i.upper)}) + + itir_node = ProgramLowering.apply( + ProgramParser.apply_to_function(program), + function_definitions=[gtir_identity_fundef], + grid_type=gtx.GridType.CARTESIAN, + ) + + assert itir_node.body[0].domain == im.domain( + gtx.GridType.CARTESIAN, + { + IDim: ( + im.tuple_get(0, im.tuple_get(1, "bounds")), + im.tuple_get(1, im.tuple_get(1, "bounds")), + ) + }, + ) + + make_tuple_op_definition = itir.FunctionDefinition( id="make_tuple_op", params=[itir.Sym(id="inp")], expr=im.make_tuple("inp", "inp") ) From 0ba19fed89c91be53dc1bd3d1e4a002713ab6968 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Wed, 25 Nov 2026 08:45:05 +0000 Subject: [PATCH 03/15] fix[next]: support indexing tuples and named collections in programs A subscript on a tuple program argument, e.g. d[1] as a field operator argument or d[0][1] as a domain bound, was typed as the whole tuple and nested subscripts were rejected, as program_ast.Subscript only modelled slicing an output field. --- src/gt4py/next/ffront/func_to_past.py | 2 +- .../next/ffront/past_passes/type_deduction.py | 16 ++++++---- src/gt4py/next/ffront/past_to_itir.py | 8 ++++- src/gt4py/next/ffront/program_ast.py | 2 +- .../ffront_tests/test_named_collections.py | 31 ++++++++++++++++++ .../ffront_tests/test_func_to_past.py | 32 +++++++++++++++++++ .../ffront_tests/test_past_to_gtir.py | 22 +++++++++++++ 7 files changed, 104 insertions(+), 9 deletions(-) diff --git a/src/gt4py/next/ffront/func_to_past.py b/src/gt4py/next/ffront/func_to_past.py index 8cf01eb691..9915456bfe 100644 --- a/src/gt4py/next/ffront/func_to_past.py +++ b/src/gt4py/next/ffront/func_to_past.py @@ -194,7 +194,7 @@ def visit_Attribute(self, node: ast.Attribute) -> past.Attribute: raise errors.DSLError( self.get_location(node), "`node.ctx` can only be of type ast.Load" ) - assert isinstance(node.value, (ast.Name, ast.Attribute)) + assert isinstance(node.value, (ast.Name, ast.Attribute, ast.Subscript)) return past.Attribute( attr=node.attr, diff --git a/src/gt4py/next/ffront/past_passes/type_deduction.py b/src/gt4py/next/ffront/past_passes/type_deduction.py index 9d021ceb51..36c17e9125 100644 --- a/src/gt4py/next/ffront/past_passes/type_deduction.py +++ b/src/gt4py/next/ffront/past_passes/type_deduction.py @@ -142,12 +142,16 @@ def visit_Slice(self, node: past.Slice, **kwargs: Any) -> past.Slice: def visit_Subscript(self, node: past.Subscript, **kwargs: Any) -> past.Subscript: value = self.visit(node.value, **kwargs) - return past.Subscript( - value=value, - slice_=self.visit(node.slice_, **kwargs), - type=value.type, - location=node.location, - ) + slice_ = self.visit(node.slice_, **kwargs) + new_type = value.type + if isinstance(value.type, (ts.TupleType, ts.NamedCollectionType)): + if not (isinstance(slice_, past.Constant) and isinstance(slice_.value, int)): + raise errors.DSLError( + node.location, + f"Tuples need to be indexed with literal integers, got '{node.slice_}'.", + ) + new_type = value.type.types[slice_.value] + return past.Subscript(value=value, slice_=slice_, type=new_type, location=node.location) def visit_Attribute(self, node: past.Attribute, **kwargs: Any) -> past.Attribute: new_value = self.visit(node.value, **kwargs) diff --git a/src/gt4py/next/ffront/past_to_itir.py b/src/gt4py/next/ffront/past_to_itir.py index c6d5bac023..b740057e9b 100644 --- a/src/gt4py/next/ffront/past_to_itir.py +++ b/src/gt4py/next/ffront/past_to_itir.py @@ -186,7 +186,7 @@ def _column_axis(all_closure_vars: dict[str, Any]) -> Optional[common.Dimension] def _compute_field_slice(node: past.Subscript) -> list[past.Slice]: - out_field_name: past.Name = node.value + out_field_name = node.value out_field_slice_: list[past.Slice] if isinstance(node.slice_, past.TupleExpr) and all( isinstance(el, past.Slice) for el in node.slice_.elts @@ -445,6 +445,7 @@ def _split_field_and_slice( self, field: past.Name | past.Subscript ) -> tuple[past.Name, list[past.Slice] | None]: if isinstance(field, past.Subscript): + assert isinstance(field.value, past.Name) return field.value, _compute_field_slice(field) else: assert isinstance(field, past.Name) @@ -515,6 +516,11 @@ def visit_Attribute(self, node: past.Attribute, **kwargs: Any) -> itir.FunCall: assert isinstance(named_tup_type, ts.NamedCollectionType) return im.tuple_get(named_tup_type.keys.index(node.attr), self.visit(node.value, **kwargs)) + def visit_Subscript(self, node: past.Subscript, **kwargs: Any) -> itir.FunCall: + assert isinstance(node.value.type, (ts.TupleType, ts.NamedCollectionType)) + assert isinstance(node.slice_, past.Constant) + return im.tuple_get(node.slice_.value, self.visit(node.value, **kwargs)) + def visit_BinOp(self, node: past.BinOp, **kwargs: Any) -> itir.FunCall: return itir.FunCall( fun=itir.SymRef(id=node.op.value), diff --git a/src/gt4py/next/ffront/program_ast.py b/src/gt4py/next/ffront/program_ast.py index 9e0eb30939..46384c77fd 100644 --- a/src/gt4py/next/ffront/program_ast.py +++ b/src/gt4py/next/ffront/program_ast.py @@ -64,7 +64,7 @@ class Call(Expr): class Subscript(Expr): - value: Name + value: Expr slice_: Expr diff --git a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_named_collections.py b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_named_collections.py index d796872be4..0f741282e2 100644 --- a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_named_collections.py +++ b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_named_collections.py @@ -750,3 +750,34 @@ def test_nested_named_tuple_as_domain(cartesian_case): ref[region] = bounds.scale * a.asnumpy()[region] cases.verify(cartesian_case, nested_bounds_as_domain_program, a, bounds, out=out, ref=ref) + + +@pytest.mark.uses_tuple_args +@pytest.mark.uses_scalar_in_domain +@pytest.mark.uses_scalar_in_domain_and_fo +def test_nested_named_tuple_subscript(cartesian_case): + @gtx.field_operator + def scale_by(a: cases.IJField, scale: gtx.int32) -> cases.IJField: + return scale * a + + @gtx.program + def testee(a: cases.IJField, bounds: NestedBounds, out: cases.IJField): + scale_by( + a, + bounds[2], + out=out, + domain={ + IDim: (bounds[0][0], bounds[0][2]), + JDim: (bounds[1].lower, bounds.j[1]), + }, + ) + + bounds = _nested_bounds(cartesian_case) + a = cases.allocate(cartesian_case, testee, "a")() + out = cases.allocate(cartesian_case, testee, "out").zeros()() + + ref = np.zeros_like(out.asnumpy()) + region = (slice(bounds.i.lower, bounds.i.upper), slice(bounds.j.lower, bounds.j.upper)) + ref[region] = bounds.scale * a.asnumpy()[region] + + cases.verify(cartesian_case, testee, a, bounds, out=out, ref=ref) diff --git a/tests/next_tests/unit_tests/ffront_tests/test_func_to_past.py b/tests/next_tests/unit_tests/ffront_tests/test_func_to_past.py index 8486885076..74cdb57bca 100644 --- a/tests/next_tests/unit_tests/ffront_tests/test_func_to_past.py +++ b/tests/next_tests/unit_tests/ffront_tests/test_func_to_past.py @@ -251,3 +251,35 @@ def domain_format_6_program(in_field: gtx.Field[[IDim], float64]): assert exc_info.match("Invalid call to 'domain_format_6'") assert re.search("Empty domain not allowed.", exc_info.value.__cause__.args[0]) is not None + + +def test_tuple_subscript_type(identity_def): + identity = gtx.field_operator(identity_def) + + def program( + in_field: gtx.Field[[IDim], float64], + out: gtx.Field[[IDim], float64], + t: tuple[tuple[gtx.int32, gtx.int64], gtx.int32], + ): + identity(in_field, out=out, domain={IDim: (t[1], t[0][1])}) + + past_node = ProgramParser.apply_to_function(program) + + lower, upper = past_node.body[0].kwargs["domain"].values_[0].elts + assert lower.type == ts.ScalarType(kind=ts.ScalarKind.INT32) + assert upper.type == ts.ScalarType(kind=ts.ScalarKind.INT64) + + +def test_tuple_subscript_with_non_literal_index(identity_def): + identity = gtx.field_operator(identity_def) + + def program( + in_field: gtx.Field[[IDim], float64], + out: gtx.Field[[IDim], float64], + t: tuple[gtx.int32, gtx.int32], + i: gtx.int32, + ): + identity(in_field, out=out, domain={IDim: (t[i], t[1])}) + + with pytest.raises(errors.DSLError, match="Tuples need to be indexed with literal integers"): + ProgramParser.apply_to_function(program) diff --git a/tests/next_tests/unit_tests/ffront_tests/test_past_to_gtir.py b/tests/next_tests/unit_tests/ffront_tests/test_past_to_gtir.py index 1794b86b5a..c72e40d631 100644 --- a/tests/next_tests/unit_tests/ffront_tests/test_past_to_gtir.py +++ b/tests/next_tests/unit_tests/ffront_tests/test_past_to_gtir.py @@ -211,6 +211,28 @@ def program( ) +def test_tuple_subscript_in_domain(identity_def, gtir_identity_fundef): + identity = gtx.field_operator(identity_def) + + def program( + in_field: gtx.Field[[IDim], float64], + out: gtx.Field[[IDim], float64], + t: tuple[gtx.int32, tuple[gtx.int32, gtx.int32]], + ): + identity(in_field, out=out, domain={IDim: (t[0], t[1][1])}) + + itir_node = ProgramLowering.apply( + ProgramParser.apply_to_function(program), + function_definitions=[gtir_identity_fundef], + grid_type=gtx.GridType.CARTESIAN, + ) + + assert itir_node.body[0].domain == im.domain( + gtx.GridType.CARTESIAN, + {IDim: (im.tuple_get(0, "t"), im.tuple_get(1, im.tuple_get(1, "t")))}, + ) + + make_tuple_op_definition = itir.FunctionDefinition( id="make_tuple_op", params=[itir.Sym(id="inp")], expr=im.make_tuple("inp", "inp") ) From 08eb826297a56bab4a036dea248cc0c8b094eefe Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Wed, 25 Nov 2026 09:47:11 +0000 Subject: [PATCH 04/15] test[next]: mark nested named-tuple concat_where test as using a scalar in a domain --- .../feature_tests/ffront_tests/test_named_collections.py | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_named_collections.py b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_named_collections.py index 0f741282e2..32fe08baed 100644 --- a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_named_collections.py +++ b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_named_collections.py @@ -722,6 +722,7 @@ def _split_at_bound_ref(a: np.ndarray, bounds: NestedBounds) -> np.ndarray: @pytest.mark.uses_tuple_args @pytest.mark.uses_concat_where +@pytest.mark.uses_scalar_in_domain def test_nested_named_tuple_as_field_operator_arg(cartesian_case): bounds = _nested_bounds(cartesian_case) a = cases.allocate(cartesian_case, nested_bounds_as_field_operator_arg_program, "a")() From 6d2fe14f6576e1c0338684c54141b499dfa2288e Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Wed, 25 Nov 2026 10:24:54 +0000 Subject: [PATCH 05/15] fix[next]: validate element access on collections in programs Reject non-literal, out-of-range, negative and bool tuple indices, integer indexing of dataclass collections and element access on closure variables with a DSLError, and look up named-collection attributes by key, so that fields named like attributes of the type spec (e.g. 'keys') resolve. --- .../next/ffront/past_passes/type_deduction.py | 46 ++++++++-- .../ffront_tests/test_func_to_past.py | 88 ++++++++++++++++--- 2 files changed, 119 insertions(+), 15 deletions(-) diff --git a/src/gt4py/next/ffront/past_passes/type_deduction.py b/src/gt4py/next/ffront/past_passes/type_deduction.py index 36c17e9125..d87907a4d8 100644 --- a/src/gt4py/next/ffront/past_passes/type_deduction.py +++ b/src/gt4py/next/ffront/past_passes/type_deduction.py @@ -5,9 +5,10 @@ # # Please, refer to the LICENSE file in the root directory. # SPDX-License-Identifier: BSD-3-Clause +import pkgutil from typing import Any, Optional, cast -from gt4py.eve import NodeTranslator, traits +from gt4py.eve import NodeTranslator, SourceLocation, traits from gt4py.next import errors from gt4py.next.ffront import ( dialect_ast_enums, @@ -32,6 +33,20 @@ def _ensure_no_sliced_field(entry: past.Expr) -> None: _ensure_no_sliced_field(param) +def _ensure_no_closure_var_access( + value: past.Expr, location: SourceLocation, closure_var_ids: set[str] +) -> None: + root = value + while isinstance(root, (past.Subscript, past.Attribute)): + root = root.value + if isinstance(root, past.Name) and root.id in closure_var_ids: + raise errors.DSLError( + location, + f"Elements of closure variable '{root.id}' can not be accessed in a program, " + "pass it as a program argument instead.", + ) + + def _is_integral_scalar(expr: past.Expr) -> bool: """Check that expression is an integral scalar.""" return isinstance(expr.type, ts.ScalarType) and type_info.is_integral(expr.type) @@ -115,6 +130,7 @@ def apply(cls, node: past.Program) -> past.Program: def visit_Program(self, node: past.Program, **kwargs: Any) -> past.Program: params = self.visit(node.params, **kwargs) + kwargs["closure_var_ids"] = {str(sym.id) for sym in node.closure_vars} definition_type = ts.FunctionType( pos_only_args=[], @@ -145,21 +161,41 @@ def visit_Subscript(self, node: past.Subscript, **kwargs: Any) -> past.Subscript slice_ = self.visit(node.slice_, **kwargs) new_type = value.type if isinstance(value.type, (ts.TupleType, ts.NamedCollectionType)): - if not (isinstance(slice_, past.Constant) and isinstance(slice_.value, int)): + _ensure_no_closure_var_access(value, node.location, kwargs["closure_var_ids"]) + if isinstance(value.type, ts.NamedCollectionType) and not issubclass( + pkgutil.resolve_name(value.type.original_python_type), tuple + ): + raise errors.DSLError( + node.location, + f"Elements of '{value.type}' can only be accessed by attribute, not by index.", + ) + index = slice_.value if isinstance(slice_, past.Constant) else None + # `type(...) is int` rejects `bool` + if type(index) is not int or not 0 <= index < len(value.type.types): raise errors.DSLError( node.location, - f"Tuples need to be indexed with literal integers, got '{node.slice_}'.", + f"Tuples need to be indexed with literal integers in " + f"[0, {len(value.type.types)}), got '{node.slice_}'.", ) - new_type = value.type.types[slice_.value] + new_type = value.type.types[index] return past.Subscript(value=value, slice_=slice_, type=new_type, location=node.location) def visit_Attribute(self, node: past.Attribute, **kwargs: Any) -> past.Attribute: new_value = self.visit(node.value, **kwargs) + # look up via `keys`: `getattr` on the type would resolve e.g. `keys` or `types` + # to the attributes of the type itself + if not ( + isinstance(new_value.type, ts.NamedCollectionType) and node.attr in new_value.type.keys + ): + raise errors.DSLError( + node.location, f"'{new_value.type}' has no attribute '{node.attr}'." + ) + _ensure_no_closure_var_access(new_value, node.location, kwargs["closure_var_ids"]) return past.Attribute( value=new_value, attr=node.attr, location=node.location, - type=getattr(new_value.type, node.attr), + type=new_value.type.types[new_value.type.keys.index(node.attr)], ) def visit_Dict(self, node: past.Dict, **kwargs: Any) -> past.Dict: diff --git a/tests/next_tests/unit_tests/ffront_tests/test_func_to_past.py b/tests/next_tests/unit_tests/ffront_tests/test_func_to_past.py index 74cdb57bca..ea9ec1f72a 100644 --- a/tests/next_tests/unit_tests/ffront_tests/test_func_to_past.py +++ b/tests/next_tests/unit_tests/ffront_tests/test_func_to_past.py @@ -6,7 +6,9 @@ # Please, refer to the LICENSE file in the root directory. # SPDX-License-Identifier: BSD-3-Clause +import dataclasses import re +from typing import NamedTuple import pytest @@ -270,16 +272,82 @@ def program( assert upper.type == ts.ScalarType(kind=ts.ScalarKind.INT64) -def test_tuple_subscript_with_non_literal_index(identity_def): - identity = gtx.field_operator(identity_def) +class SpecialKeysNamedTuple(NamedTuple): + types: gtx.int32 + keys: gtx.int64 - def program( - in_field: gtx.Field[[IDim], float64], - out: gtx.Field[[IDim], float64], - t: tuple[gtx.int32, gtx.int32], - i: gtx.int32, - ): - identity(in_field, out=out, domain={IDim: (t[i], t[1])}) - with pytest.raises(errors.DSLError, match="Tuples need to be indexed with literal integers"): +@dataclasses.dataclass +class BoundsDataclass: + lower: gtx.int32 + upper: gtx.int32 + + +CLOSURE_TUPLE = (gtx.int32(0), gtx.int32(1)) + +_InField = gtx.Field[[IDim], float64] + + +@gtx.field_operator +def _identity(x: _InField) -> _InField: + return x + + +def _non_literal_index( + in_field: _InField, out: _InField, t: tuple[gtx.int32, gtx.int32], i: gtx.int32 +): + _identity(in_field, out=out, domain={IDim: (t[i], t[1])}) + + +def _out_of_range_index(in_field: _InField, out: _InField, t: tuple[gtx.int32, gtx.int32]): + _identity(in_field, out=out, domain={IDim: (t[0], t[2])}) + + +def _negative_index(in_field: _InField, out: _InField, t: tuple[gtx.int32, gtx.int32]): + _identity(in_field, out=out, domain={IDim: (t[0], t[-1])}) + + +def _bool_index(in_field: _InField, out: _InField, t: tuple[gtx.int32, gtx.int32]): + _identity(in_field, out=out, domain={IDim: (t[False], t[True])}) + + +def _dataclass_index(in_field: _InField, out: _InField, d: BoundsDataclass): + _identity(in_field, out=out, domain={IDim: (d[0], d[1])}) + + +def _unknown_attribute(in_field: _InField, out: _InField, d: SpecialKeysNamedTuple): + _identity(in_field, out=out, domain={IDim: (d.types, d.upper)}) + + +def _closure_tuple_index(in_field: _InField, out: _InField): + _identity(in_field, out=out, domain={IDim: (CLOSURE_TUPLE[0], CLOSURE_TUPLE[1])}) + + +@pytest.mark.parametrize( + "program, message", + [ + (_non_literal_index, "Tuples need to be indexed with literal integers"), + (_out_of_range_index, "Tuples need to be indexed with literal integers"), + (_negative_index, "Tuples need to be indexed with literal integers"), + (_bool_index, "Tuples need to be indexed with literal integers"), + (_dataclass_index, "can only be accessed by attribute"), + (_unknown_attribute, "has no attribute 'upper'"), + (_closure_tuple_index, "closure variable 'CLOSURE_TUPLE'"), + ], +) +def test_invalid_collection_element_access(program, message): + with pytest.raises(errors.DSLError, match=message): ProgramParser.apply_to_function(program) + + +def test_named_tuple_attributes_named_like_type_spec_fields(identity_def): + identity = gtx.field_operator(identity_def) + + def program(in_field: _InField, out: _InField, d: SpecialKeysNamedTuple): + identity(in_field, out=out, domain={IDim: (d.types, d.keys)}) + + past_node = ProgramParser.apply_to_function(program) + + lower, upper = past_node.body[0].kwargs["domain"].values_[0].elts + assert lower.type == ts.ScalarType(kind=ts.ScalarKind.INT32) + assert upper.type == ts.ScalarType(kind=ts.ScalarKind.INT64) From beaeedd7ab587684b639997391395968b82ca700 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Wed, 25 Nov 2026 11:41:17 +0000 Subject: [PATCH 06/15] fix[next]: reject subscripts of non-collections and sliced inputs in programs Subscripting a scalar or slicing a field passed as a field operator input got through type deduction and failed on an assert in lowering. Also resolve the NamedTuple/dataclass distinction for classes defined in a function, which pkgutil can not resolve by name. --- .../next/ffront/past_passes/type_deduction.py | 29 +++++++++++++++++-- .../ffront_tests/test_func_to_past.py | 25 ++++++++++++++++ 2 files changed, 51 insertions(+), 3 deletions(-) diff --git a/src/gt4py/next/ffront/past_passes/type_deduction.py b/src/gt4py/next/ffront/past_passes/type_deduction.py index d87907a4d8..191531e752 100644 --- a/src/gt4py/next/ffront/past_passes/type_deduction.py +++ b/src/gt4py/next/ffront/past_passes/type_deduction.py @@ -47,6 +47,21 @@ def _ensure_no_closure_var_access( ) +def _contains_sliced_field(expr: past.Expr) -> bool: + if isinstance(expr, past.TupleExpr): + return any(_contains_sliced_field(elt) for elt in expr.elts) + return isinstance(expr, past.Subscript) and isinstance(expr.value.type, ts.FieldType) + + +def _is_tuple_like(type_: ts.NamedCollectionType) -> bool: + try: + python_type = pkgutil.resolve_name(type_.original_python_type) + except (ValueError, ImportError, AttributeError): + # e.g. a class defined in a function (`mod:f..C`) can not be resolved by name + return True + return isinstance(python_type, type) and issubclass(python_type, tuple) + + def _is_integral_scalar(expr: past.Expr) -> bool: """Check that expression is an integral scalar.""" return isinstance(expr.type, ts.ScalarType) and type_info.is_integral(expr.type) @@ -162,9 +177,7 @@ def visit_Subscript(self, node: past.Subscript, **kwargs: Any) -> past.Subscript new_type = value.type if isinstance(value.type, (ts.TupleType, ts.NamedCollectionType)): _ensure_no_closure_var_access(value, node.location, kwargs["closure_var_ids"]) - if isinstance(value.type, ts.NamedCollectionType) and not issubclass( - pkgutil.resolve_name(value.type.original_python_type), tuple - ): + if isinstance(value.type, ts.NamedCollectionType) and not _is_tuple_like(value.type): raise errors.DSLError( node.location, f"Elements of '{value.type}' can only be accessed by attribute, not by index.", @@ -178,6 +191,10 @@ def visit_Subscript(self, node: past.Subscript, **kwargs: Any) -> past.Subscript f"[0, {len(value.type.types)}), got '{node.slice_}'.", ) new_type = value.type.types[index] + elif not isinstance(value.type, ts.FieldType): + raise errors.DSLError( + node.location, f"Values of type '{value.type}' can not be subscripted." + ) return past.Subscript(value=value, slice_=slice_, type=new_type, location=node.location) def visit_Attribute(self, node: past.Attribute, **kwargs: Any) -> past.Attribute: @@ -273,6 +290,12 @@ def visit_Call(self, node: past.Call, **kwargs: Any) -> past.Call: ) if is_operator: _validate_operator_call(new_func, new_kwargs) + inputs = [ + *new_args, + *(v for k, v in new_kwargs.items() if k not in ["out", "domain"]), + ] + if any(_contains_sliced_field(arg) for arg in inputs): + raise ValueError("Only the 'out' argument can be sliced.") arg_types = [arg.type for arg in new_args] kwarg_types = { name: expr.type diff --git a/tests/next_tests/unit_tests/ffront_tests/test_func_to_past.py b/tests/next_tests/unit_tests/ffront_tests/test_func_to_past.py index ea9ec1f72a..5f7bff1404 100644 --- a/tests/next_tests/unit_tests/ffront_tests/test_func_to_past.py +++ b/tests/next_tests/unit_tests/ffront_tests/test_func_to_past.py @@ -323,9 +323,19 @@ def _closure_tuple_index(in_field: _InField, out: _InField): _identity(in_field, out=out, domain={IDim: (CLOSURE_TUPLE[0], CLOSURE_TUPLE[1])}) +def _scalar_index(in_field: _InField, out: _InField, s: gtx.int32): + _identity(in_field, out=out, domain={IDim: (0, s[0])}) + + +def _sliced_input(in_field: _InField, out: _InField): + _identity(in_field[1:3], out=out) + + @pytest.mark.parametrize( "program, message", [ + (_scalar_index, "can not be subscripted"), + (_sliced_input, "Only the 'out' argument can be sliced"), (_non_literal_index, "Tuples need to be indexed with literal integers"), (_out_of_range_index, "Tuples need to be indexed with literal integers"), (_negative_index, "Tuples need to be indexed with literal integers"), @@ -351,3 +361,18 @@ def program(in_field: _InField, out: _InField, d: SpecialKeysNamedTuple): lower, upper = past_node.body[0].kwargs["domain"].values_[0].elts assert lower.type == ts.ScalarType(kind=ts.ScalarKind.INT32) assert upper.type == ts.ScalarType(kind=ts.ScalarKind.INT64) + + +def test_locally_defined_named_tuple_subscript(): + class LocalNamedTuple(NamedTuple): + lower: gtx.int32 + upper: gtx.int64 + + def program(in_field: _InField, out: _InField, d: LocalNamedTuple): + _identity(in_field, out=out, domain={IDim: (d[0], d[1])}) + + past_node = ProgramParser.apply_to_function(program) + + lower, upper = past_node.body[0].kwargs["domain"].values_[0].elts + assert lower.type == ts.ScalarType(kind=ts.ScalarKind.INT32) + assert upper.type == ts.ScalarType(kind=ts.ScalarKind.INT64) From 5340d7c7b8635925148861930025ec6646207d96 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Wed, 25 Nov 2026 12:08:14 +0000 Subject: [PATCH 07/15] fix[next]: fold enum and constant-namespace attributes in programs Attribute access on an enum or FrozenNamespace closure variable in a program body is folded to a constant, as in field operators. It previously worked only in embedded execution. --- .../next/ffront/past_passes/type_deduction.py | 26 ++++++++++++-- src/gt4py/next/ffront/past_to_itir.py | 7 +++- .../ffront_tests/test_closure_vars.py | 34 ++++++++++++++++++- .../ffront_tests/test_func_to_past.py | 12 +++++++ 4 files changed, 75 insertions(+), 4 deletions(-) diff --git a/src/gt4py/next/ffront/past_passes/type_deduction.py b/src/gt4py/next/ffront/past_passes/type_deduction.py index 191531e752..7c442ede1f 100644 --- a/src/gt4py/next/ffront/past_passes/type_deduction.py +++ b/src/gt4py/next/ffront/past_passes/type_deduction.py @@ -5,6 +5,7 @@ # # Please, refer to the LICENSE file in the root directory. # SPDX-License-Identifier: BSD-3-Clause +import enum import pkgutil from typing import Any, Optional, cast @@ -15,7 +16,7 @@ program_ast as past, type_specifications as ts_ffront, ) -from gt4py.next.type_system import type_info, type_specifications as ts +from gt4py.next.type_system import type_info, type_specifications as ts, type_translation def _ensure_no_sliced_field(entry: past.Expr) -> None: @@ -197,8 +198,29 @@ def visit_Subscript(self, node: past.Subscript, **kwargs: Any) -> past.Subscript ) return past.Subscript(value=value, slice_=slice_, type=new_type, location=node.location) - def visit_Attribute(self, node: past.Attribute, **kwargs: Any) -> past.Attribute: + def visit_Attribute( + self, node: past.Attribute, **kwargs: Any + ) -> past.Attribute | past.Constant: new_value = self.visit(node.value, **kwargs) + if isinstance(new_value.type, type_translation.NamespaceProxy): + namespace = new_value.type._object + if not hasattr(namespace, node.attr): + raise errors.MissingAttributeError(node.location, node.attr) + member = getattr(namespace, node.attr) + if isinstance(namespace, type_translation.ConstantPythonNamespaceObject) and not ( + isinstance(member, type_translation.PythonNamespaceObject) + ): + if isinstance(member, enum.Enum): + member = member.value + return past.Constant( + value=member, type=type_translation.from_value(member), location=node.location + ) + return past.Attribute( + value=new_value, + attr=node.attr, + location=node.location, + type=type_translation.from_value(member), + ) # look up via `keys`: `getattr` on the type would resolve e.g. `keys` or `types` # to the attributes of the type itself if not ( diff --git a/src/gt4py/next/ffront/past_to_itir.py b/src/gt4py/next/ffront/past_to_itir.py index b740057e9b..7b0cb7702a 100644 --- a/src/gt4py/next/ffront/past_to_itir.py +++ b/src/gt4py/next/ffront/past_to_itir.py @@ -513,7 +513,12 @@ def visit_Symbol(self, node: past.Symbol, **kwargs: Any) -> itir.Sym: def visit_Attribute(self, node: past.Attribute, **kwargs: Any) -> itir.FunCall: named_tup_type = node.value.type - assert isinstance(named_tup_type, ts.NamedCollectionType) + if not isinstance(named_tup_type, ts.NamedCollectionType): + raise errors.DSLError( + node.location, + "Only attributes of named collections, enums and constant namespaces are " + "supported in compiled programs.", + ) return im.tuple_get(named_tup_type.keys.index(node.attr), self.visit(node.value, **kwargs)) def visit_Subscript(self, node: past.Subscript, **kwargs: Any) -> itir.FunCall: diff --git a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_closure_vars.py b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_closure_vars.py index 086cc4a282..8d117718ab 100644 --- a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_closure_vars.py +++ b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_closure_vars.py @@ -11,7 +11,7 @@ import gt4py.next as gtx from next_tests.integration_tests import cases -from next_tests.integration_tests.cases import cartesian_case +from next_tests.integration_tests.cases import IDim, cartesian_case from next_tests.integration_tests.cases_utils import ( exec_alloc_descriptor, ) @@ -45,3 +45,35 @@ def consume_constants(input: cases.IFloatField) -> cases.IFloatField: cases.verify_with_default_data( cartesian_case, consume_constants, ref=lambda input: Constants.PI * Constants.E * input ) + + +def test_constant_closure_vars_in_program(cartesian_case): + import enum + + from gt4py.eve.utils import FrozenNamespace + + class Bounds(enum.IntEnum): + LOWER = 1 + UPPER = 3 + + constants = FrozenNamespace(factor=np.int32(2), inner=FrozenNamespace(offset=np.int32(1))) + + @gtx.field_operator + def scale(a: cases.IField, factor: gtx.int32) -> cases.IField: + return factor * a + + @gtx.program + def testee(a: cases.IField, out: cases.IField): + scale( + a, + constants.factor, + out=out, + domain={IDim: (Bounds.LOWER, Bounds.UPPER + constants.inner.offset)}, + ) + + a = cases.allocate(cartesian_case, testee, "a")() + out = cases.allocate(cartesian_case, testee, "out").zeros()() + ref = np.zeros_like(a.asnumpy()) + ref[1:4] = 2 * a.asnumpy()[1:4] + + cases.verify(cartesian_case, testee, a, out=out, ref=ref) diff --git a/tests/next_tests/unit_tests/ffront_tests/test_func_to_past.py b/tests/next_tests/unit_tests/ffront_tests/test_func_to_past.py index 5f7bff1404..e6bc20dafc 100644 --- a/tests/next_tests/unit_tests/ffront_tests/test_func_to_past.py +++ b/tests/next_tests/unit_tests/ffront_tests/test_func_to_past.py @@ -7,6 +7,7 @@ # SPDX-License-Identifier: BSD-3-Clause import dataclasses +import enum import re from typing import NamedTuple @@ -376,3 +377,14 @@ def program(in_field: _InField, out: _InField, d: LocalNamedTuple): lower, upper = past_node.body[0].kwargs["domain"].values_[0].elts assert lower.type == ts.ScalarType(kind=ts.ScalarKind.INT32) assert upper.type == ts.ScalarType(kind=ts.ScalarKind.INT64) + + +def test_missing_enum_member(): + class Bounds(enum.IntEnum): + LOWER = 0 + + def program(in_field: _InField, out: _InField): + _identity(in_field, out=out, domain={IDim: (Bounds.LOWER, Bounds.UPPER)}) + + with pytest.raises(errors.MissingAttributeError, match="'UPPER'"): + ProgramParser.apply_to_function(program) From 32fd317917916a7e45ee593f7ddbeb60492f25a0 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Thu, 26 Nov 2026 10:31:45 +0000 Subject: [PATCH 08/15] refactor[next]: move element-access validation beyond indices to a follow-up Keep only the index checks for tuple subscripts and the rejection of subscripted scalars here. Key-based attribute lookup, folding of enum attributes, rejecting dataclass indexing, closure-variable element access and sliced inputs move to a separate PR. --- .../next/ffront/past_passes/type_deduction.py | 82 +------------------ src/gt4py/next/ffront/past_to_itir.py | 3 +- .../ffront_tests/test_closure_vars.py | 34 +------- .../ffront_tests/test_func_to_past.py | 59 ------------- 4 files changed, 6 insertions(+), 172 deletions(-) diff --git a/src/gt4py/next/ffront/past_passes/type_deduction.py b/src/gt4py/next/ffront/past_passes/type_deduction.py index 7c442ede1f..1f156590b4 100644 --- a/src/gt4py/next/ffront/past_passes/type_deduction.py +++ b/src/gt4py/next/ffront/past_passes/type_deduction.py @@ -5,18 +5,16 @@ # # Please, refer to the LICENSE file in the root directory. # SPDX-License-Identifier: BSD-3-Clause -import enum -import pkgutil from typing import Any, Optional, cast -from gt4py.eve import NodeTranslator, SourceLocation, traits +from gt4py.eve import NodeTranslator, traits from gt4py.next import errors from gt4py.next.ffront import ( dialect_ast_enums, program_ast as past, type_specifications as ts_ffront, ) -from gt4py.next.type_system import type_info, type_specifications as ts, type_translation +from gt4py.next.type_system import type_info, type_specifications as ts def _ensure_no_sliced_field(entry: past.Expr) -> None: @@ -34,35 +32,6 @@ def _ensure_no_sliced_field(entry: past.Expr) -> None: _ensure_no_sliced_field(param) -def _ensure_no_closure_var_access( - value: past.Expr, location: SourceLocation, closure_var_ids: set[str] -) -> None: - root = value - while isinstance(root, (past.Subscript, past.Attribute)): - root = root.value - if isinstance(root, past.Name) and root.id in closure_var_ids: - raise errors.DSLError( - location, - f"Elements of closure variable '{root.id}' can not be accessed in a program, " - "pass it as a program argument instead.", - ) - - -def _contains_sliced_field(expr: past.Expr) -> bool: - if isinstance(expr, past.TupleExpr): - return any(_contains_sliced_field(elt) for elt in expr.elts) - return isinstance(expr, past.Subscript) and isinstance(expr.value.type, ts.FieldType) - - -def _is_tuple_like(type_: ts.NamedCollectionType) -> bool: - try: - python_type = pkgutil.resolve_name(type_.original_python_type) - except (ValueError, ImportError, AttributeError): - # e.g. a class defined in a function (`mod:f..C`) can not be resolved by name - return True - return isinstance(python_type, type) and issubclass(python_type, tuple) - - def _is_integral_scalar(expr: past.Expr) -> bool: """Check that expression is an integral scalar.""" return isinstance(expr.type, ts.ScalarType) and type_info.is_integral(expr.type) @@ -146,7 +115,6 @@ def apply(cls, node: past.Program) -> past.Program: def visit_Program(self, node: past.Program, **kwargs: Any) -> past.Program: params = self.visit(node.params, **kwargs) - kwargs["closure_var_ids"] = {str(sym.id) for sym in node.closure_vars} definition_type = ts.FunctionType( pos_only_args=[], @@ -177,12 +145,6 @@ def visit_Subscript(self, node: past.Subscript, **kwargs: Any) -> past.Subscript slice_ = self.visit(node.slice_, **kwargs) new_type = value.type if isinstance(value.type, (ts.TupleType, ts.NamedCollectionType)): - _ensure_no_closure_var_access(value, node.location, kwargs["closure_var_ids"]) - if isinstance(value.type, ts.NamedCollectionType) and not _is_tuple_like(value.type): - raise errors.DSLError( - node.location, - f"Elements of '{value.type}' can only be accessed by attribute, not by index.", - ) index = slice_.value if isinstance(slice_, past.Constant) else None # `type(...) is int` rejects `bool` if type(index) is not int or not 0 <= index < len(value.type.types): @@ -198,43 +160,13 @@ def visit_Subscript(self, node: past.Subscript, **kwargs: Any) -> past.Subscript ) return past.Subscript(value=value, slice_=slice_, type=new_type, location=node.location) - def visit_Attribute( - self, node: past.Attribute, **kwargs: Any - ) -> past.Attribute | past.Constant: + def visit_Attribute(self, node: past.Attribute, **kwargs: Any) -> past.Attribute: new_value = self.visit(node.value, **kwargs) - if isinstance(new_value.type, type_translation.NamespaceProxy): - namespace = new_value.type._object - if not hasattr(namespace, node.attr): - raise errors.MissingAttributeError(node.location, node.attr) - member = getattr(namespace, node.attr) - if isinstance(namespace, type_translation.ConstantPythonNamespaceObject) and not ( - isinstance(member, type_translation.PythonNamespaceObject) - ): - if isinstance(member, enum.Enum): - member = member.value - return past.Constant( - value=member, type=type_translation.from_value(member), location=node.location - ) - return past.Attribute( - value=new_value, - attr=node.attr, - location=node.location, - type=type_translation.from_value(member), - ) - # look up via `keys`: `getattr` on the type would resolve e.g. `keys` or `types` - # to the attributes of the type itself - if not ( - isinstance(new_value.type, ts.NamedCollectionType) and node.attr in new_value.type.keys - ): - raise errors.DSLError( - node.location, f"'{new_value.type}' has no attribute '{node.attr}'." - ) - _ensure_no_closure_var_access(new_value, node.location, kwargs["closure_var_ids"]) return past.Attribute( value=new_value, attr=node.attr, location=node.location, - type=new_value.type.types[new_value.type.keys.index(node.attr)], + type=getattr(new_value.type, node.attr), ) def visit_Dict(self, node: past.Dict, **kwargs: Any) -> past.Dict: @@ -312,12 +244,6 @@ def visit_Call(self, node: past.Call, **kwargs: Any) -> past.Call: ) if is_operator: _validate_operator_call(new_func, new_kwargs) - inputs = [ - *new_args, - *(v for k, v in new_kwargs.items() if k not in ["out", "domain"]), - ] - if any(_contains_sliced_field(arg) for arg in inputs): - raise ValueError("Only the 'out' argument can be sliced.") arg_types = [arg.type for arg in new_args] kwarg_types = { name: expr.type diff --git a/src/gt4py/next/ffront/past_to_itir.py b/src/gt4py/next/ffront/past_to_itir.py index 7b0cb7702a..21eb241e8f 100644 --- a/src/gt4py/next/ffront/past_to_itir.py +++ b/src/gt4py/next/ffront/past_to_itir.py @@ -516,8 +516,7 @@ def visit_Attribute(self, node: past.Attribute, **kwargs: Any) -> itir.FunCall: if not isinstance(named_tup_type, ts.NamedCollectionType): raise errors.DSLError( node.location, - "Only attributes of named collections, enums and constant namespaces are " - "supported in compiled programs.", + "Only attributes of named collections are supported in compiled programs.", ) return im.tuple_get(named_tup_type.keys.index(node.attr), self.visit(node.value, **kwargs)) diff --git a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_closure_vars.py b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_closure_vars.py index 8d117718ab..086cc4a282 100644 --- a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_closure_vars.py +++ b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_closure_vars.py @@ -11,7 +11,7 @@ import gt4py.next as gtx from next_tests.integration_tests import cases -from next_tests.integration_tests.cases import IDim, cartesian_case +from next_tests.integration_tests.cases import cartesian_case from next_tests.integration_tests.cases_utils import ( exec_alloc_descriptor, ) @@ -45,35 +45,3 @@ def consume_constants(input: cases.IFloatField) -> cases.IFloatField: cases.verify_with_default_data( cartesian_case, consume_constants, ref=lambda input: Constants.PI * Constants.E * input ) - - -def test_constant_closure_vars_in_program(cartesian_case): - import enum - - from gt4py.eve.utils import FrozenNamespace - - class Bounds(enum.IntEnum): - LOWER = 1 - UPPER = 3 - - constants = FrozenNamespace(factor=np.int32(2), inner=FrozenNamespace(offset=np.int32(1))) - - @gtx.field_operator - def scale(a: cases.IField, factor: gtx.int32) -> cases.IField: - return factor * a - - @gtx.program - def testee(a: cases.IField, out: cases.IField): - scale( - a, - constants.factor, - out=out, - domain={IDim: (Bounds.LOWER, Bounds.UPPER + constants.inner.offset)}, - ) - - a = cases.allocate(cartesian_case, testee, "a")() - out = cases.allocate(cartesian_case, testee, "out").zeros()() - ref = np.zeros_like(a.asnumpy()) - ref[1:4] = 2 * a.asnumpy()[1:4] - - cases.verify(cartesian_case, testee, a, out=out, ref=ref) diff --git a/tests/next_tests/unit_tests/ffront_tests/test_func_to_past.py b/tests/next_tests/unit_tests/ffront_tests/test_func_to_past.py index e6bc20dafc..4e7b5f25f7 100644 --- a/tests/next_tests/unit_tests/ffront_tests/test_func_to_past.py +++ b/tests/next_tests/unit_tests/ffront_tests/test_func_to_past.py @@ -6,8 +6,6 @@ # Please, refer to the LICENSE file in the root directory. # SPDX-License-Identifier: BSD-3-Clause -import dataclasses -import enum import re from typing import NamedTuple @@ -273,19 +271,6 @@ def program( assert upper.type == ts.ScalarType(kind=ts.ScalarKind.INT64) -class SpecialKeysNamedTuple(NamedTuple): - types: gtx.int32 - keys: gtx.int64 - - -@dataclasses.dataclass -class BoundsDataclass: - lower: gtx.int32 - upper: gtx.int32 - - -CLOSURE_TUPLE = (gtx.int32(0), gtx.int32(1)) - _InField = gtx.Field[[IDim], float64] @@ -312,38 +297,18 @@ def _bool_index(in_field: _InField, out: _InField, t: tuple[gtx.int32, gtx.int32 _identity(in_field, out=out, domain={IDim: (t[False], t[True])}) -def _dataclass_index(in_field: _InField, out: _InField, d: BoundsDataclass): - _identity(in_field, out=out, domain={IDim: (d[0], d[1])}) - - -def _unknown_attribute(in_field: _InField, out: _InField, d: SpecialKeysNamedTuple): - _identity(in_field, out=out, domain={IDim: (d.types, d.upper)}) - - -def _closure_tuple_index(in_field: _InField, out: _InField): - _identity(in_field, out=out, domain={IDim: (CLOSURE_TUPLE[0], CLOSURE_TUPLE[1])}) - - def _scalar_index(in_field: _InField, out: _InField, s: gtx.int32): _identity(in_field, out=out, domain={IDim: (0, s[0])}) -def _sliced_input(in_field: _InField, out: _InField): - _identity(in_field[1:3], out=out) - - @pytest.mark.parametrize( "program, message", [ (_scalar_index, "can not be subscripted"), - (_sliced_input, "Only the 'out' argument can be sliced"), (_non_literal_index, "Tuples need to be indexed with literal integers"), (_out_of_range_index, "Tuples need to be indexed with literal integers"), (_negative_index, "Tuples need to be indexed with literal integers"), (_bool_index, "Tuples need to be indexed with literal integers"), - (_dataclass_index, "can only be accessed by attribute"), - (_unknown_attribute, "has no attribute 'upper'"), - (_closure_tuple_index, "closure variable 'CLOSURE_TUPLE'"), ], ) def test_invalid_collection_element_access(program, message): @@ -351,19 +316,6 @@ def test_invalid_collection_element_access(program, message): ProgramParser.apply_to_function(program) -def test_named_tuple_attributes_named_like_type_spec_fields(identity_def): - identity = gtx.field_operator(identity_def) - - def program(in_field: _InField, out: _InField, d: SpecialKeysNamedTuple): - identity(in_field, out=out, domain={IDim: (d.types, d.keys)}) - - past_node = ProgramParser.apply_to_function(program) - - lower, upper = past_node.body[0].kwargs["domain"].values_[0].elts - assert lower.type == ts.ScalarType(kind=ts.ScalarKind.INT32) - assert upper.type == ts.ScalarType(kind=ts.ScalarKind.INT64) - - def test_locally_defined_named_tuple_subscript(): class LocalNamedTuple(NamedTuple): lower: gtx.int32 @@ -377,14 +329,3 @@ def program(in_field: _InField, out: _InField, d: LocalNamedTuple): lower, upper = past_node.body[0].kwargs["domain"].values_[0].elts assert lower.type == ts.ScalarType(kind=ts.ScalarKind.INT32) assert upper.type == ts.ScalarType(kind=ts.ScalarKind.INT64) - - -def test_missing_enum_member(): - class Bounds(enum.IntEnum): - LOWER = 0 - - def program(in_field: _InField, out: _InField): - _identity(in_field, out=out, domain={IDim: (Bounds.LOWER, Bounds.UPPER)}) - - with pytest.raises(errors.MissingAttributeError, match="'UPPER'"): - ProgramParser.apply_to_function(program) From b45684b3bfa55e9b804bbeecf2031cae3ffe5202 Mon Sep 17 00:00:00 2001 From: Till Ehrengruber Date: Thu, 26 Nov 2026 11:51:57 +0000 Subject: [PATCH 09/15] refactor[next]: move the CollapseTuple remapped-argument fix to its own PR This reverts commit 3969b843867b3b1856b454e770db554f88dfec73. The fix now lives on tehrengruber/collapse-tuple-remapped-arg-capture, which names the remapped arguments with unique_symbol instead of uids. --- .../iterator/transforms/collapse_tuple.py | 5 +- .../transforms_tests/test_collapse_tuple.py | 59 ------------------- 2 files changed, 4 insertions(+), 60 deletions(-) diff --git a/src/gt4py/next/iterator/transforms/collapse_tuple.py b/src/gt4py/next/iterator/transforms/collapse_tuple.py index f399749565..08ad5c9ede 100644 --- a/src/gt4py/next/iterator/transforms/collapse_tuple.py +++ b/src/gt4py/next/iterator/transforms/collapse_tuple.py @@ -587,7 +587,10 @@ def transform_flatten_as_fieldop_args( for param, arg in zip(stencil.params, node.args, strict=True): if isinstance(arg.type, ts.TupleType): assert isinstance(param.type, it_ts.IteratorType) - ref_to_remapped_arg = im.ref(next(self.uids["__ct_flat_remapped"]), arg.type) + ref_to_remapped_arg = im.ref( + f"__ct_flat_remapped_{len(remapped_args)}", + arg.type, + ) self._preserve_annex(arg, ref_to_remapped_arg) remapped_args[im.sym(ref_to_remapped_arg.id, arg.type)] = arg new_params_inner, lift_params = [], [] diff --git a/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_collapse_tuple.py b/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_collapse_tuple.py index 995b6d841f..18d1bdc08c 100644 --- a/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_collapse_tuple.py +++ b/tests/next_tests/unit_tests/iterator_tests/transforms_tests/test_collapse_tuple.py @@ -472,62 +472,3 @@ def test_flatten_as_fieldop_args_scan(uids: utils.IDGeneratorPool): uids=uids, ) assert actual == expected - - -def test_flatten_as_fieldop_args_no_capture_of_remapped_args(uids: utils.IDGeneratorPool): - # `{a + 1}` is not trivial, so the let binding it survives the first flattening and the - # second flattening (of `d[0]` and `d[1]`) happens inside it. - d_type = ts.TupleType( - types=[ - ts.TupleType(types=[int_type, int_type, int_type]), - ts.TupleType(types=[int_type, int_type]), - int_type, - ] - ) - x_type = ts.TupleType(types=[int_type]) - testee = im.as_fieldop( - im.lambda_( - im.sym("x", it_ts.IteratorType(position_dims=[], defined_dims=[], element_type=x_type)), - im.sym("d", it_ts.IteratorType(position_dims=[], defined_dims=[], element_type=d_type)), - )( - im.plus( - im.tuple_get(0, im.deref("x")), - im.plus( - im.tuple_get(2, im.tuple_get(0, im.deref("d"))), - im.tuple_get(2, im.deref("d")), - ), - ) - ) - )(im.make_tuple(im.plus(im.ref("a", int_type), 1)), im.ref("d", d_type)) - expected = im.as_fieldop( - im.lambda_( - "__ct_flat_el_0_x", - "__ct_flat_el_0_0_d", - "__ct_flat_el_0_1_d", - "__ct_flat_el_0_2_d", - "__ct_flat_el_1_0_d", - "__ct_flat_el_1_1_d", - "__ct_flat_el_2_d", - )( - im.plus( - im.deref("__ct_flat_el_0_x"), - im.plus(im.deref("__ct_flat_el_0_2_d"), im.deref("__ct_flat_el_2_d")), - ) - ) - )( - im.plus("a", 1), - im.tuple_get(0, im.tuple_get(0, "d")), - im.tuple_get(1, im.tuple_get(0, "d")), - im.tuple_get(2, im.tuple_get(0, "d")), - im.tuple_get(0, im.tuple_get(1, "d")), - im.tuple_get(1, im.tuple_get(1, "d")), - im.tuple_get(2, "d"), - ) - actual = CollapseTuple.apply( - testee, - enabled_transformations=~CollapseTuple.Transformation.PROPAGATE_TO_IF_ON_TUPLES, - allow_undeclared_symbols=True, - within_stencil=False, - uids=uids, - ) - assert actual == expected From 2bb6ecd021a8e7a8270f39f865dbaa1325f77d77 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Thu, 3 Dec 2026 12:18:09 +0100 Subject: [PATCH 10/15] fix[next]: index only plain tuples in programs, allowing negative indices Named collections are accessed by field name, as in field operators. Negative tuple indices count from the end and are lowered to the non-negative position. --- .../next/ffront/past_passes/type_deduction.py | 13 +++++++--- src/gt4py/next/ffront/past_to_itir.py | 7 +++-- .../ffront_tests/test_named_collections.py | 19 +++++++++----- .../ffront_tests/test_func_to_past.py | 26 ++++++++++++------- .../ffront_tests/test_past_to_gtir.py | 2 +- 5 files changed, 44 insertions(+), 23 deletions(-) diff --git a/src/gt4py/next/ffront/past_passes/type_deduction.py b/src/gt4py/next/ffront/past_passes/type_deduction.py index 1f156590b4..4a03ddd8f4 100644 --- a/src/gt4py/next/ffront/past_passes/type_deduction.py +++ b/src/gt4py/next/ffront/past_passes/type_deduction.py @@ -144,16 +144,23 @@ def visit_Subscript(self, node: past.Subscript, **kwargs: Any) -> past.Subscript value = self.visit(node.value, **kwargs) slice_ = self.visit(node.slice_, **kwargs) new_type = value.type - if isinstance(value.type, (ts.TupleType, ts.NamedCollectionType)): + if isinstance(value.type, ts.TupleType): + size = len(value.type.types) index = slice_.value if isinstance(slice_, past.Constant) else None # `type(...) is int` rejects `bool` - if type(index) is not int or not 0 <= index < len(value.type.types): + if type(index) is not int or not -size <= index < size: raise errors.DSLError( node.location, f"Tuples need to be indexed with literal integers in " - f"[0, {len(value.type.types)}), got '{node.slice_}'.", + f"[-{size}, {size}), got '{node.slice_}'.", ) new_type = value.type.types[index] + elif isinstance(value.type, ts.NamedCollectionType): + raise errors.DSLError( + node.location, + f"Values of type '{value.type}' can not be subscripted, access the fields of " + f"named collections by name: {', '.join(value.type.keys)}.", + ) elif not isinstance(value.type, ts.FieldType): raise errors.DSLError( node.location, f"Values of type '{value.type}' can not be subscripted." diff --git a/src/gt4py/next/ffront/past_to_itir.py b/src/gt4py/next/ffront/past_to_itir.py index 21eb241e8f..b50722e3eb 100644 --- a/src/gt4py/next/ffront/past_to_itir.py +++ b/src/gt4py/next/ffront/past_to_itir.py @@ -521,9 +521,12 @@ def visit_Attribute(self, node: past.Attribute, **kwargs: Any) -> itir.FunCall: return im.tuple_get(named_tup_type.keys.index(node.attr), self.visit(node.value, **kwargs)) def visit_Subscript(self, node: past.Subscript, **kwargs: Any) -> itir.FunCall: - assert isinstance(node.value.type, (ts.TupleType, ts.NamedCollectionType)) + assert isinstance(node.value.type, ts.TupleType) assert isinstance(node.slice_, past.Constant) - return im.tuple_get(node.slice_.value, self.visit(node.value, **kwargs)) + index = node.slice_.value + if index < 0: # `tuple_get` takes the non-negative position + index += len(node.value.type.types) + return im.tuple_get(index, self.visit(node.value, **kwargs)) def visit_BinOp(self, node: past.BinOp, **kwargs: Any) -> itir.FunCall: return itir.FunCall( diff --git a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_named_collections.py b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_named_collections.py index 32fe08baed..ba9acdfce4 100644 --- a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_named_collections.py +++ b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_named_collections.py @@ -762,23 +762,28 @@ def scale_by(a: cases.IJField, scale: gtx.int32) -> cases.IJField: return scale * a @gtx.program - def testee(a: cases.IJField, bounds: NestedBounds, out: cases.IJField): + def testee( + a: cases.IJField, + bounds: tuple[IBounds, tuple[gtx.int32, gtx.int32], gtx.int32], + out: cases.IJField, + ): scale_by( a, - bounds[2], + bounds[-1], out=out, domain={ - IDim: (bounds[0][0], bounds[0][2]), - JDim: (bounds[1].lower, bounds.j[1]), + IDim: (bounds[0].lower, bounds[0].upper), + JDim: (bounds[1][0], bounds[1][-1]), }, ) - bounds = _nested_bounds(cartesian_case) + nested = _nested_bounds(cartesian_case) + bounds = (nested.i, tuple(nested.j), nested.scale) a = cases.allocate(cartesian_case, testee, "a")() out = cases.allocate(cartesian_case, testee, "out").zeros()() ref = np.zeros_like(out.asnumpy()) - region = (slice(bounds.i.lower, bounds.i.upper), slice(bounds.j.lower, bounds.j.upper)) - ref[region] = bounds.scale * a.asnumpy()[region] + region = (slice(nested.i.lower, nested.i.upper), slice(nested.j.lower, nested.j.upper)) + ref[region] = nested.scale * a.asnumpy()[region] cases.verify(cartesian_case, testee, a, bounds, out=out, ref=ref) diff --git a/tests/next_tests/unit_tests/ffront_tests/test_func_to_past.py b/tests/next_tests/unit_tests/ffront_tests/test_func_to_past.py index 4e7b5f25f7..0da6051501 100644 --- a/tests/next_tests/unit_tests/ffront_tests/test_func_to_past.py +++ b/tests/next_tests/unit_tests/ffront_tests/test_func_to_past.py @@ -289,8 +289,17 @@ def _out_of_range_index(in_field: _InField, out: _InField, t: tuple[gtx.int32, g _identity(in_field, out=out, domain={IDim: (t[0], t[2])}) -def _negative_index(in_field: _InField, out: _InField, t: tuple[gtx.int32, gtx.int32]): - _identity(in_field, out=out, domain={IDim: (t[0], t[-1])}) +def _negative_out_of_range_index(in_field: _InField, out: _InField, t: tuple[gtx.int32, gtx.int32]): + _identity(in_field, out=out, domain={IDim: (t[-3], t[1])}) + + +class _Bounds(NamedTuple): + lower: gtx.int32 + upper: gtx.int32 + + +def _named_collection_index(in_field: _InField, out: _InField, d: _Bounds): + _identity(in_field, out=out, domain={IDim: (d[0], d[1])}) def _bool_index(in_field: _InField, out: _InField, t: tuple[gtx.int32, gtx.int32]): @@ -307,7 +316,8 @@ def _scalar_index(in_field: _InField, out: _InField, s: gtx.int32): (_scalar_index, "can not be subscripted"), (_non_literal_index, "Tuples need to be indexed with literal integers"), (_out_of_range_index, "Tuples need to be indexed with literal integers"), - (_negative_index, "Tuples need to be indexed with literal integers"), + (_negative_out_of_range_index, "Tuples need to be indexed with literal integers"), + (_named_collection_index, "access the fields of named collections by name: lower, upper"), (_bool_index, "Tuples need to be indexed with literal integers"), ], ) @@ -316,13 +326,9 @@ def test_invalid_collection_element_access(program, message): ProgramParser.apply_to_function(program) -def test_locally_defined_named_tuple_subscript(): - class LocalNamedTuple(NamedTuple): - lower: gtx.int32 - upper: gtx.int64 - - def program(in_field: _InField, out: _InField, d: LocalNamedTuple): - _identity(in_field, out=out, domain={IDim: (d[0], d[1])}) +def test_negative_tuple_subscript_type(): + def program(in_field: _InField, out: _InField, t: tuple[gtx.int32, gtx.int64]): + _identity(in_field, out=out, domain={IDim: (t[-2], t[-1])}) past_node = ProgramParser.apply_to_function(program) diff --git a/tests/next_tests/unit_tests/ffront_tests/test_past_to_gtir.py b/tests/next_tests/unit_tests/ffront_tests/test_past_to_gtir.py index c72e40d631..a25dbf7a8f 100644 --- a/tests/next_tests/unit_tests/ffront_tests/test_past_to_gtir.py +++ b/tests/next_tests/unit_tests/ffront_tests/test_past_to_gtir.py @@ -219,7 +219,7 @@ def program( out: gtx.Field[[IDim], float64], t: tuple[gtx.int32, tuple[gtx.int32, gtx.int32]], ): - identity(in_field, out=out, domain={IDim: (t[0], t[1][1])}) + identity(in_field, out=out, domain={IDim: (t[0], t[-1][-1])}) itir_node = ProgramLowering.apply( ProgramParser.apply_to_function(program), From ada7573b0e0b23e01a5dee5f6457b506015caaeb Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Thu, 3 Dec 2026 13:32:21 +0100 Subject: [PATCH 11/15] fix[next]: lower negative tuple indices in field operators Field operators accepted t[-1] but passed the negative index to tuple_get, which the compiled backends do not handle for tuples that reach them. --- src/gt4py/next/ffront/foast_to_gtir.py | 6 +++++- .../feature_tests/ffront_tests/test_tuples.py | 13 +++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/src/gt4py/next/ffront/foast_to_gtir.py b/src/gt4py/next/ffront/foast_to_gtir.py index c453193eba..f54f068e9f 100644 --- a/src/gt4py/next/ffront/foast_to_gtir.py +++ b/src/gt4py/next/ffront/foast_to_gtir.py @@ -251,7 +251,11 @@ def visit_Subscript(self, node: foast.Subscript, **kwargs: Any) -> itir.Expr: return im.as_fieldop_deref_list_get( node.index.args[0].value, self.visit(node.value, **kwargs) ) - return im.tuple_get(foast_utils.expr_to_index(node.index), self.visit(node.value, **kwargs)) + index = foast_utils.expr_to_index(node.index) + if index < 0: # `tuple_get` takes the non-negative position + assert isinstance(node.value.type, ts.TupleType) + index += len(node.value.type.types) + return im.tuple_get(index, self.visit(node.value, **kwargs)) def visit_TupleExpr(self, node: foast.TupleExpr, **kwargs: Any) -> itir.Expr: return im.make_tuple(*[self.visit(el, **kwargs) for el in node.elts]) diff --git a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_tuples.py b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_tuples.py index 91025f156f..c94f908748 100644 --- a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_tuples.py +++ b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_tuples.py @@ -106,6 +106,19 @@ def testee(a: tuple[int32, tuple[int32, cases.IField, int32]]) -> cases.IField: ) +@pytest.mark.uses_tuple_args +def test_negative_tuple_index(cartesian_case): + @gtx.field_operator + def testee(a: tuple[cases.IField, tuple[int32, cases.IField]]) -> cases.IField: + return a[-2] + 2 * a[-1][-1] + 3 * a[1][-2] + + cases.verify_with_default_data( + cartesian_case, + testee, + ref=lambda a: a[0] + 2 * a[1][1] + 3 * a[1][0], + ) + + @pytest.mark.uses_tuple_args @pytest.mark.uses_tuple_args_with_different_but_promotable_dims def test_tuple_arg_with_different_but_promotable_dims(cartesian_case): From f9053dda692d2e8ab75d9105840ff9f699daed29 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Thu, 3 Dec 2026 17:03:37 +0100 Subject: [PATCH 12/15] fix[next]: share the tuple index check between field operators and programs Field operators accepted bool tuple indices and raised a bare IndexError for out-of-range ones. Both frontends now use one check: literal integers in [-n, n), bool rejected, with a DSLError otherwise. --- .../ffront/foast_passes/type_deduction.py | 14 +++---- .../next/ffront/past_passes/type_deduction.py | 17 ++++---- src/gt4py/next/ffront/type_info.py | 36 +++++++++++++++-- .../ffront_tests/test_type_deduction.py | 39 +++++++++++++++++++ 4 files changed, 86 insertions(+), 20 deletions(-) diff --git a/src/gt4py/next/ffront/foast_passes/type_deduction.py b/src/gt4py/next/ffront/foast_passes/type_deduction.py index 738b105a61..af63c8d1b4 100644 --- a/src/gt4py/next/ffront/foast_passes/type_deduction.py +++ b/src/gt4py/next/ffront/foast_passes/type_deduction.py @@ -18,6 +18,7 @@ dialect_ast_enums, experimental, fbuiltins, + type_info as ffront_type_info, type_specifications as ts_ffront, ) from gt4py.next.ffront.ast_passes import single_static_assign as ssa @@ -447,15 +448,14 @@ def visit_Subscript(self, node: foast.Subscript, **kwargs: Any) -> foast.Subscri new_type: Optional[ts.TypeSpec] = None match new_value.type: - case ts.TupleType(types=types): + case ts.TupleType(): try: index = foast_utils.expr_to_index(node.index) - except ValueError as ex: - raise errors.DSLError( - node.location, - f"Tuples need to be indexed with literal integers, got '{node.index}'.", - ) from ex - new_type = types[index] + except ValueError: + index = None + new_type = ffront_type_info.tuple_element_type( + new_value.type, index, location=node.location, index_repr=str(node.index) + ) case ts.OffsetType(source=source, target=(target1, target2), tag=tag): if not target2.kind == DimensionKind.LOCAL: raise errors.DSLError( diff --git a/src/gt4py/next/ffront/past_passes/type_deduction.py b/src/gt4py/next/ffront/past_passes/type_deduction.py index 4a03ddd8f4..bd5779b16d 100644 --- a/src/gt4py/next/ffront/past_passes/type_deduction.py +++ b/src/gt4py/next/ffront/past_passes/type_deduction.py @@ -12,6 +12,7 @@ from gt4py.next.ffront import ( dialect_ast_enums, program_ast as past, + type_info as ffront_type_info, type_specifications as ts_ffront, ) from gt4py.next.type_system import type_info, type_specifications as ts @@ -145,16 +146,12 @@ def visit_Subscript(self, node: past.Subscript, **kwargs: Any) -> past.Subscript slice_ = self.visit(node.slice_, **kwargs) new_type = value.type if isinstance(value.type, ts.TupleType): - size = len(value.type.types) - index = slice_.value if isinstance(slice_, past.Constant) else None - # `type(...) is int` rejects `bool` - if type(index) is not int or not -size <= index < size: - raise errors.DSLError( - node.location, - f"Tuples need to be indexed with literal integers in " - f"[-{size}, {size}), got '{node.slice_}'.", - ) - new_type = value.type.types[index] + new_type = ffront_type_info.tuple_element_type( + value.type, + slice_.value if isinstance(slice_, past.Constant) else None, + location=node.location, + index_repr=str(node.slice_), + ) elif isinstance(value.type, ts.NamedCollectionType): raise errors.DSLError( node.location, diff --git a/src/gt4py/next/ffront/type_info.py b/src/gt4py/next/ffront/type_info.py index 0959524ea3..aa906d543b 100644 --- a/src/gt4py/next/ffront/type_info.py +++ b/src/gt4py/next/ffront/type_info.py @@ -8,16 +8,46 @@ import functools import inspect from collections.abc import Callable, Iterable -from typing import Any, Iterator, Sequence, cast +from typing import Any, Iterator, Optional, Sequence, cast import gt4py.next.ffront.type_specifications as ts_ffront import gt4py.next.type_system.type_specifications as ts -from gt4py.eve import datamodels -from gt4py.next import common, utils +from gt4py.eve import SourceLocation, datamodels +from gt4py.next import common, errors, utils from gt4py.next.ffront.type_specifications import ProgramType from gt4py.next.type_system import type_info +def tuple_element_type( + tuple_type: ts.TupleType, + index: Any, + *, + location: Optional[SourceLocation], + index_repr: str, +) -> ts.TypeSpec: + """ + Return the type of the element of a tuple at `index`, with negative indices counting from the end. + + Args: + tuple_type: The type of the subscripted tuple. + index: The value of the index, `None` if it is not a literal. + location: Location of the subscript, used for the error. + index_repr: The index as written, used for the error. + + Raises: + DSLError: If `index` is not a literal integer within the bounds of the tuple. + """ + size = len(tuple_type.types) + # `type(...) is int` rejects `bool` + if type(index) is not int or not -size <= index < size: + raise errors.DSLError( + location, + f"Tuples need to be indexed with literal integers in [-{size}, {size}), " + f"got '{index_repr}'.", + ) + return tuple_type.types[index] + + named_collections_to_tuple_types = cast( Callable[..., ts.TupleType], utils.tree_map( diff --git a/tests/next_tests/unit_tests/ffront_tests/test_type_deduction.py b/tests/next_tests/unit_tests/ffront_tests/test_type_deduction.py index b6ae674312..79af7ae24f 100644 --- a/tests/next_tests/unit_tests/ffront_tests/test_type_deduction.py +++ b/tests/next_tests/unit_tests/ffront_tests/test_type_deduction.py @@ -798,3 +798,42 @@ def testee( match="Second and third argument to 'concat_where' must have the same tuple/collection structure", ): parsed = FieldOperatorParser.apply_to_function(testee) + + +def _tuple_index_non_literal(t: tuple[int32, int32], i: int32) -> int32: + return t[i] + + +def _tuple_index_out_of_range(t: tuple[int32, int32]) -> int32: + return t[2] + + +def _tuple_index_negative_out_of_range(t: tuple[int32, int32]) -> int32: + return t[-3] + + +def _tuple_index_bool(t: tuple[int32, int32]) -> int32: + return t[True] + + +@pytest.mark.parametrize( + "definition", + [ + _tuple_index_non_literal, + _tuple_index_out_of_range, + _tuple_index_negative_out_of_range, + _tuple_index_bool, + ], +) +def test_invalid_tuple_index(definition): + with pytest.raises(errors.DSLError, match="Tuples need to be indexed with literal integers"): + _ = FieldOperatorParser.apply_to_function(definition) + + +def test_negative_tuple_index_type(): + def negative_index(t: tuple[int32, int64]) -> int64: + return t[-1] + + parsed = FieldOperatorParser.apply_to_function(negative_index) + + assert parsed.body.stmts[-1].value.type == ts.ScalarType(kind=ts.ScalarKind.INT64) From f17b2b04575794e0b254163ba53300a0b086efbc Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Thu, 3 Dec 2026 18:05:11 +0100 Subject: [PATCH 13/15] refactor[next]: resolve tuple indices through one helper in type deduction and lowering --- src/gt4py/next/ffront/foast_passes/type_deduction.py | 3 ++- src/gt4py/next/ffront/foast_to_gtir.py | 12 ++++++++---- src/gt4py/next/ffront/past_passes/type_deduction.py | 3 ++- src/gt4py/next/ffront/past_to_itir.py | 9 ++++++--- src/gt4py/next/ffront/type_info.py | 8 ++++---- 5 files changed, 22 insertions(+), 13 deletions(-) diff --git a/src/gt4py/next/ffront/foast_passes/type_deduction.py b/src/gt4py/next/ffront/foast_passes/type_deduction.py index af63c8d1b4..bc4cb7bb41 100644 --- a/src/gt4py/next/ffront/foast_passes/type_deduction.py +++ b/src/gt4py/next/ffront/foast_passes/type_deduction.py @@ -453,9 +453,10 @@ def visit_Subscript(self, node: foast.Subscript, **kwargs: Any) -> foast.Subscri index = foast_utils.expr_to_index(node.index) except ValueError: index = None - new_type = ffront_type_info.tuple_element_type( + index = ffront_type_info.tuple_index( new_value.type, index, location=node.location, index_repr=str(node.index) ) + new_type = new_value.type.types[index] case ts.OffsetType(source=source, target=(target1, target2), tag=tag): if not target2.kind == DimensionKind.LOCAL: raise errors.DSLError( diff --git a/src/gt4py/next/ffront/foast_to_gtir.py b/src/gt4py/next/ffront/foast_to_gtir.py index f54f068e9f..bc7ab44800 100644 --- a/src/gt4py/next/ffront/foast_to_gtir.py +++ b/src/gt4py/next/ffront/foast_to_gtir.py @@ -20,6 +20,7 @@ foast_introspection, lowering_utils, stages as ffront_stages, + type_info as ffront_type_info, type_specifications as ts_ffront, ) from gt4py.next.ffront.foast_passes import utils as foast_utils @@ -251,10 +252,13 @@ def visit_Subscript(self, node: foast.Subscript, **kwargs: Any) -> itir.Expr: return im.as_fieldop_deref_list_get( node.index.args[0].value, self.visit(node.value, **kwargs) ) - index = foast_utils.expr_to_index(node.index) - if index < 0: # `tuple_get` takes the non-negative position - assert isinstance(node.value.type, ts.TupleType) - index += len(node.value.type.types) + assert isinstance(node.value.type, ts.TupleType) + index = ffront_type_info.tuple_index( + node.value.type, + foast_utils.expr_to_index(node.index), + location=node.location, + index_repr=str(node.index), + ) return im.tuple_get(index, self.visit(node.value, **kwargs)) def visit_TupleExpr(self, node: foast.TupleExpr, **kwargs: Any) -> itir.Expr: diff --git a/src/gt4py/next/ffront/past_passes/type_deduction.py b/src/gt4py/next/ffront/past_passes/type_deduction.py index bd5779b16d..87e4014667 100644 --- a/src/gt4py/next/ffront/past_passes/type_deduction.py +++ b/src/gt4py/next/ffront/past_passes/type_deduction.py @@ -146,12 +146,13 @@ def visit_Subscript(self, node: past.Subscript, **kwargs: Any) -> past.Subscript slice_ = self.visit(node.slice_, **kwargs) new_type = value.type if isinstance(value.type, ts.TupleType): - new_type = ffront_type_info.tuple_element_type( + index = ffront_type_info.tuple_index( value.type, slice_.value if isinstance(slice_, past.Constant) else None, location=node.location, index_repr=str(node.slice_), ) + new_type = value.type.types[index] elif isinstance(value.type, ts.NamedCollectionType): raise errors.DSLError( node.location, diff --git a/src/gt4py/next/ffront/past_to_itir.py b/src/gt4py/next/ffront/past_to_itir.py index a0b1b88fbc..66cfeb223f 100644 --- a/src/gt4py/next/ffront/past_to_itir.py +++ b/src/gt4py/next/ffront/past_to_itir.py @@ -491,9 +491,12 @@ def visit_Attribute(self, node: past.Attribute, **kwargs: Any) -> itir.FunCall: def visit_Subscript(self, node: past.Subscript, **kwargs: Any) -> itir.FunCall: assert isinstance(node.value.type, ts.TupleType) assert isinstance(node.slice_, past.Constant) - index = node.slice_.value - if index < 0: # `tuple_get` takes the non-negative position - index += len(node.value.type.types) + index = ffront_ti.tuple_index( + node.value.type, + node.slice_.value, + location=node.location, + index_repr=str(node.slice_), + ) return im.tuple_get(index, self.visit(node.value, **kwargs)) def visit_BinOp(self, node: past.BinOp, **kwargs: Any) -> itir.FunCall: diff --git a/src/gt4py/next/ffront/type_info.py b/src/gt4py/next/ffront/type_info.py index aa906d543b..b22ad50159 100644 --- a/src/gt4py/next/ffront/type_info.py +++ b/src/gt4py/next/ffront/type_info.py @@ -18,15 +18,15 @@ from gt4py.next.type_system import type_info -def tuple_element_type( +def tuple_index( tuple_type: ts.TupleType, index: Any, *, location: Optional[SourceLocation], index_repr: str, -) -> ts.TypeSpec: +) -> int: """ - Return the type of the element of a tuple at `index`, with negative indices counting from the end. + Return the non-negative position of `index` in a tuple, with negative indices counting from the end. Args: tuple_type: The type of the subscripted tuple. @@ -45,7 +45,7 @@ def tuple_element_type( f"Tuples need to be indexed with literal integers in [-{size}, {size}), " f"got '{index_repr}'.", ) - return tuple_type.types[index] + return index % size named_collections_to_tuple_types = cast( From ac6a5c58783a9c0c7bfe18308cefc959a3cab6b7 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Thu, 3 Dec 2026 18:10:49 +0100 Subject: [PATCH 14/15] refactor[next]: keep tuple index validation in type deduction, normalise in lowering --- src/gt4py/next/ffront/foast_passes/type_deduction.py | 3 +-- src/gt4py/next/ffront/foast_to_gtir.py | 9 ++------- src/gt4py/next/ffront/past_passes/type_deduction.py | 3 +-- src/gt4py/next/ffront/past_to_itir.py | 8 ++------ src/gt4py/next/ffront/type_info.py | 8 ++++---- 5 files changed, 10 insertions(+), 21 deletions(-) diff --git a/src/gt4py/next/ffront/foast_passes/type_deduction.py b/src/gt4py/next/ffront/foast_passes/type_deduction.py index bc4cb7bb41..af63c8d1b4 100644 --- a/src/gt4py/next/ffront/foast_passes/type_deduction.py +++ b/src/gt4py/next/ffront/foast_passes/type_deduction.py @@ -453,10 +453,9 @@ def visit_Subscript(self, node: foast.Subscript, **kwargs: Any) -> foast.Subscri index = foast_utils.expr_to_index(node.index) except ValueError: index = None - index = ffront_type_info.tuple_index( + new_type = ffront_type_info.tuple_element_type( new_value.type, index, location=node.location, index_repr=str(node.index) ) - new_type = new_value.type.types[index] case ts.OffsetType(source=source, target=(target1, target2), tag=tag): if not target2.kind == DimensionKind.LOCAL: raise errors.DSLError( diff --git a/src/gt4py/next/ffront/foast_to_gtir.py b/src/gt4py/next/ffront/foast_to_gtir.py index bc7ab44800..0e04895230 100644 --- a/src/gt4py/next/ffront/foast_to_gtir.py +++ b/src/gt4py/next/ffront/foast_to_gtir.py @@ -20,7 +20,6 @@ foast_introspection, lowering_utils, stages as ffront_stages, - type_info as ffront_type_info, type_specifications as ts_ffront, ) from gt4py.next.ffront.foast_passes import utils as foast_utils @@ -253,12 +252,8 @@ def visit_Subscript(self, node: foast.Subscript, **kwargs: Any) -> itir.Expr: node.index.args[0].value, self.visit(node.value, **kwargs) ) assert isinstance(node.value.type, ts.TupleType) - index = ffront_type_info.tuple_index( - node.value.type, - foast_utils.expr_to_index(node.index), - location=node.location, - index_repr=str(node.index), - ) + # `tuple_get` takes the non-negative position, the index is in bounds after type deduction + index = foast_utils.expr_to_index(node.index) % len(node.value.type.types) return im.tuple_get(index, self.visit(node.value, **kwargs)) def visit_TupleExpr(self, node: foast.TupleExpr, **kwargs: Any) -> itir.Expr: diff --git a/src/gt4py/next/ffront/past_passes/type_deduction.py b/src/gt4py/next/ffront/past_passes/type_deduction.py index 87e4014667..bd5779b16d 100644 --- a/src/gt4py/next/ffront/past_passes/type_deduction.py +++ b/src/gt4py/next/ffront/past_passes/type_deduction.py @@ -146,13 +146,12 @@ def visit_Subscript(self, node: past.Subscript, **kwargs: Any) -> past.Subscript slice_ = self.visit(node.slice_, **kwargs) new_type = value.type if isinstance(value.type, ts.TupleType): - index = ffront_type_info.tuple_index( + new_type = ffront_type_info.tuple_element_type( value.type, slice_.value if isinstance(slice_, past.Constant) else None, location=node.location, index_repr=str(node.slice_), ) - new_type = value.type.types[index] elif isinstance(value.type, ts.NamedCollectionType): raise errors.DSLError( node.location, diff --git a/src/gt4py/next/ffront/past_to_itir.py b/src/gt4py/next/ffront/past_to_itir.py index 66cfeb223f..79854bf170 100644 --- a/src/gt4py/next/ffront/past_to_itir.py +++ b/src/gt4py/next/ffront/past_to_itir.py @@ -491,12 +491,8 @@ def visit_Attribute(self, node: past.Attribute, **kwargs: Any) -> itir.FunCall: def visit_Subscript(self, node: past.Subscript, **kwargs: Any) -> itir.FunCall: assert isinstance(node.value.type, ts.TupleType) assert isinstance(node.slice_, past.Constant) - index = ffront_ti.tuple_index( - node.value.type, - node.slice_.value, - location=node.location, - index_repr=str(node.slice_), - ) + # `tuple_get` takes the non-negative position, the index is in bounds after type deduction + index = node.slice_.value % len(node.value.type.types) return im.tuple_get(index, self.visit(node.value, **kwargs)) def visit_BinOp(self, node: past.BinOp, **kwargs: Any) -> itir.FunCall: diff --git a/src/gt4py/next/ffront/type_info.py b/src/gt4py/next/ffront/type_info.py index b22ad50159..aa906d543b 100644 --- a/src/gt4py/next/ffront/type_info.py +++ b/src/gt4py/next/ffront/type_info.py @@ -18,15 +18,15 @@ from gt4py.next.type_system import type_info -def tuple_index( +def tuple_element_type( tuple_type: ts.TupleType, index: Any, *, location: Optional[SourceLocation], index_repr: str, -) -> int: +) -> ts.TypeSpec: """ - Return the non-negative position of `index` in a tuple, with negative indices counting from the end. + Return the type of the element of a tuple at `index`, with negative indices counting from the end. Args: tuple_type: The type of the subscripted tuple. @@ -45,7 +45,7 @@ def tuple_index( f"Tuples need to be indexed with literal integers in [-{size}, {size}), " f"got '{index_repr}'.", ) - return index % size + return tuple_type.types[index] named_collections_to_tuple_types = cast( From 0a96f96d480a7c03854f8538f78a899a165cb495 Mon Sep 17 00:00:00 2001 From: Hannes Vogt Date: Thu, 3 Dec 2026 19:29:43 +0100 Subject: [PATCH 15/15] fix[next]: lower tuple unpacking with the type of the unpacked collection --- src/gt4py/next/ffront/foast_passes/iterable_unpack.py | 2 +- src/gt4py/next/ffront/foast_to_gtir.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/gt4py/next/ffront/foast_passes/iterable_unpack.py b/src/gt4py/next/ffront/foast_passes/iterable_unpack.py index 88feb9350b..2c208fc8b2 100644 --- a/src/gt4py/next/ffront/foast_passes/iterable_unpack.py +++ b/src/gt4py/next/ffront/foast_passes/iterable_unpack.py @@ -67,7 +67,7 @@ def visit_BlockStmt(self, node: foast.BlockStmt, **kwargs: Any) -> foast.BlockSt for index, subtarget in zip(indices, targets): el_type = subtarget.type tuple_name = foast.Name( - id=tuple_symbol.id, type=el_type, location=tuple_symbol.location + id=tuple_symbol.id, type=tuple_symbol.type, location=tuple_symbol.location ) if isinstance(index, tuple): # handle starred target lower, upper = index diff --git a/src/gt4py/next/ffront/foast_to_gtir.py b/src/gt4py/next/ffront/foast_to_gtir.py index 0e04895230..64fb5daba2 100644 --- a/src/gt4py/next/ffront/foast_to_gtir.py +++ b/src/gt4py/next/ffront/foast_to_gtir.py @@ -251,7 +251,7 @@ def visit_Subscript(self, node: foast.Subscript, **kwargs: Any) -> itir.Expr: return im.as_fieldop_deref_list_get( node.index.args[0].value, self.visit(node.value, **kwargs) ) - assert isinstance(node.value.type, ts.TupleType) + assert isinstance(node.value.type, ts.COLLECTION_TYPE_SPECS) # `tuple_get` takes the non-negative position, the index is in bounds after type deduction index = foast_utils.expr_to_index(node.index) % len(node.value.type.types) return im.tuple_get(index, self.visit(node.value, **kwargs))