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_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/foast_to_gtir.py b/src/gt4py/next/ffront/foast_to_gtir.py index c453193eba..64fb5daba2 100644 --- a/src/gt4py/next/ffront/foast_to_gtir.py +++ b/src/gt4py/next/ffront/foast_to_gtir.py @@ -251,7 +251,10 @@ 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)) + 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)) 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/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..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 @@ -142,12 +143,26 @@ 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): + 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, + 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." + ) + 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 07b7a1d013..79854bf170 100644 --- a/src/gt4py/next/ffront/past_to_itir.py +++ b/src/gt4py/next/ffront/past_to_itir.py @@ -154,7 +154,7 @@ def past_to_gtir_factory( 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 @@ -413,6 +413,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) @@ -478,6 +479,22 @@ 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 + if not isinstance(named_tup_type, ts.NamedCollectionType): + raise errors.DSLError( + node.location, + "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)) + + def visit_Subscript(self, node: past.Subscript, **kwargs: Any) -> itir.FunCall: + assert isinstance(node.value.type, ts.TupleType) + assert isinstance(node.slice_, past.Constant) + # `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: 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/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/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..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 @@ -657,3 +657,133 @@ 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 +@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")() + 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) + + +@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: tuple[IBounds, tuple[gtx.int32, gtx.int32], gtx.int32], + out: cases.IJField, + ): + scale_by( + a, + bounds[-1], + out=out, + domain={ + IDim: (bounds[0].lower, bounds[0].upper), + JDim: (bounds[1][0], bounds[1][-1]), + }, + ) + + 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(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/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): 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..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 @@ -7,6 +7,7 @@ # SPDX-License-Identifier: BSD-3-Clause import re +from typing import NamedTuple import pytest @@ -251,3 +252,86 @@ 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) + + +_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_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]): + _identity(in_field, out=out, domain={IDim: (t[False], t[True])}) + + +def _scalar_index(in_field: _InField, out: _InField, s: gtx.int32): + _identity(in_field, out=out, domain={IDim: (0, s[0])}) + + +@pytest.mark.parametrize( + "program, message", + [ + (_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_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"), + ], +) +def test_invalid_collection_element_access(program, message): + with pytest.raises(errors.DSLError, match=message): + ProgramParser.apply_to_function(program) + + +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) + + 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) 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..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 @@ -8,7 +8,7 @@ import re -from typing import Literal +from typing import Literal, NamedTuple import pytest @@ -174,6 +174,65 @@ 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")), + ) + }, + ) + + +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") ) 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)