Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
3969b84
fix[next]: take CollapseTuple's remapped-argument names from uids
havogt Nov 24, 2026
764f97f
fix[next]: lower attribute access on named collections in programs
havogt Nov 24, 2026
0ba19fe
fix[next]: support indexing tuples and named collections in programs
havogt Nov 25, 2026
08eb826
test[next]: mark nested named-tuple concat_where test as using a scal…
havogt Nov 25, 2026
6d2fe14
fix[next]: validate element access on collections in programs
havogt Nov 25, 2026
beaeedd
fix[next]: reject subscripts of non-collections and sliced inputs in …
havogt Nov 25, 2026
5340d7c
fix[next]: fold enum and constant-namespace attributes in programs
havogt Nov 25, 2026
32fd317
refactor[next]: move element-access validation beyond indices to a fo…
havogt Nov 26, 2026
b45684b
refactor[next]: move the CollapseTuple remapped-argument fix to its o…
tehrengruber Nov 26, 2026
593d014
Merge remote-tracking branch 'upstream/main' into named-collection-args
havogt Nov 30, 2026
2bb6ecd
fix[next]: index only plain tuples in programs, allowing negative ind…
havogt Dec 3, 2026
46ba99d
Merge remote-tracking branch 'upstream/main' into named-collection-args
havogt Dec 3, 2026
ada7573
fix[next]: lower negative tuple indices in field operators
havogt Dec 3, 2026
f9053dd
fix[next]: share the tuple index check between field operators and pr…
havogt Dec 3, 2026
f17b2b0
refactor[next]: resolve tuple indices through one helper in type dedu…
havogt Dec 3, 2026
ac6a5c5
refactor[next]: keep tuple index validation in type deduction, normal…
havogt Dec 3, 2026
0a96f96
fix[next]: lower tuple unpacking with the type of the unpacked collec…
havogt Dec 3, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/gt4py/next/ffront/foast_passes/iterable_unpack.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
14 changes: 7 additions & 7 deletions src/gt4py/next/ffront/foast_passes/type_deduction.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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(
Expand Down
5 changes: 4 additions & 1 deletion src/gt4py/next/ffront/foast_to_gtir.py
Original file line number Diff line number Diff line change
Expand Up @@ -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])
Expand Down
2 changes: 1 addition & 1 deletion src/gt4py/next/ffront/func_to_past.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
27 changes: 21 additions & 6 deletions src/gt4py/next/ffront/past_passes/type_deduction.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down
19 changes: 18 additions & 1 deletion src/gt4py/next/ffront/past_to_itir.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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),
Expand Down
2 changes: 1 addition & 1 deletion src/gt4py/next/ffront/program_ast.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ class Call(Expr):


class Subscript(Expr):
value: Name
value: Expr
slice_: Expr


Expand Down
36 changes: 33 additions & 3 deletions src/gt4py/next/ffront/type_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
Loading