Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
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
67 changes: 63 additions & 4 deletions src/gt4py/next/ffront/past_passes/type_deduction.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,18 @@
#
# Please, refer to the LICENSE file in the root directory.
# SPDX-License-Identifier: BSD-3-Clause
import enum
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,
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
from gt4py.next.type_system import type_info, type_specifications as ts, type_translation


def _ensure_no_sliced_field(entry: past.Expr) -> None:
Expand All @@ -33,6 +34,26 @@ 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_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)
Expand Down Expand Up @@ -116,6 +137,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=[],
Expand Down Expand Up @@ -146,6 +168,7 @@ 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):
_ensure_no_closure_var_access(value, node.location, kwargs["closure_var_ids"])
new_type = ffront_type_info.tuple_element_type(
value.type,
slice_.value if isinstance(slice_, past.Constant) else None,
Expand All @@ -164,13 +187,43 @@ 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 (
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:
Expand Down Expand Up @@ -248,6 +301,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
Expand Down
3 changes: 2 additions & 1 deletion src/gt4py/next/ffront/past_to_itir.py
Original file line number Diff line number Diff line change
Expand Up @@ -484,7 +484,8 @@ 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 are supported in compiled programs.",
"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))

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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,
)
Expand Down Expand Up @@ -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)
46 changes: 46 additions & 0 deletions tests/next_tests/unit_tests/ffront_tests/test_func_to_past.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
# Please, refer to the LICENSE file in the root directory.
# SPDX-License-Identifier: BSD-3-Clause

import enum
import re
from typing import NamedTuple

Expand Down Expand Up @@ -310,6 +311,26 @@ def _scalar_index(in_field: _InField, out: _InField, s: gtx.int32):
_identity(in_field, out=out, domain={IDim: (0, s[0])})


class _SpecialKeys(NamedTuple):
types: gtx.int32
keys: gtx.int64


def _unknown_attribute(in_field: _InField, out: _InField, d: _SpecialKeys):
_identity(in_field, out=out, domain={IDim: (d.types, d.upper)})


_CLOSURE_TUPLE = (gtx.int32(0), gtx.int32(1))


def _closure_tuple_index(in_field: _InField, out: _InField):
_identity(in_field, out=out, domain={IDim: (_CLOSURE_TUPLE[0], _CLOSURE_TUPLE[1])})


def _sliced_input(in_field: _InField, out: _InField):
_identity(in_field[1:3], out=out)


@pytest.mark.parametrize(
"program, message",
[
Expand All @@ -319,6 +340,9 @@ def _scalar_index(in_field: _InField, out: _InField, s: gtx.int32):
(_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"),
(_unknown_attribute, "has no attribute 'upper'"),
(_closure_tuple_index, "closure variable '_CLOSURE_TUPLE'"),
(_sliced_input, "Only the 'out' argument can be sliced"),
],
)
def test_invalid_collection_element_access(program, message):
Expand All @@ -335,3 +359,25 @@ def program(in_field: _InField, out: _InField, t: tuple[gtx.int32, gtx.int64]):
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_named_tuple_attributes_named_like_type_spec_fields():
def program(in_field: _InField, out: _InField, d: _SpecialKeys):
_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_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)