diff --git a/src/gt4py/next/__init__.py b/src/gt4py/next/__init__.py index 3b9f97592f..1fffc296e6 100644 --- a/src/gt4py/next/__init__.py +++ b/src/gt4py/next/__init__.py @@ -83,6 +83,7 @@ neg, neighbor_sum, power, + scan, sin, sinh, sqrt, @@ -186,6 +187,7 @@ "neg", "neighbor_sum", "power", + "scan", "sin", "sinh", "sqrt", diff --git a/src/gt4py/next/ffront/fbuiltins.py b/src/gt4py/next/ffront/fbuiltins.py index 2fd072a483..010a3267d2 100644 --- a/src/gt4py/next/ffront/fbuiltins.py +++ b/src/gt4py/next/ffront/fbuiltins.py @@ -61,6 +61,7 @@ "where", "broadcast", "astype", + "scan", "abs", "neg", "sin", @@ -293,6 +294,51 @@ def broadcast( return field # type: ignore[return-value] # see comment above +class ScanBuiltinFunction(BuiltInFunction[_R, _P]): + def __gt_type__(self) -> ts.FunctionType: + return ts.FunctionType( + pos_only_args=[ts.DeferredType(constraint=None)], + pos_or_kw_args={}, + kw_only_args={ + "axis": ts.DeferredType(constraint=ts.DimensionType), + "forward": ts.DeferredType(constraint=ts.ScalarType), + "init": ts.DeferredType(constraint=(ts.ScalarType, ts.TupleType)), + }, + returns=ts.DeferredType(constraint=None), + ) + + +@ScanBuiltinFunction +def scan( + scan_pass: Callable, + /, + *, + axis: common.Dimension | None = None, + forward: bool = True, + init: core_defs.Scalar | Tuple = 0.0, +) -> Callable[..., common.Field | Tuple]: + """ + Create a scan operator from a scan pass, to be called inside a field operator. + + Args: + scan_pass: Field operator `(carry, *args) -> carry` on scalars (or tuples thereof). + axis: Vertical dimension to scan along. If omitted, it is the unique vertical + dimension of the arguments the scan operator is called with. + forward: Scan direction. + init: Initial value of the carry, a compile-time constant. + + Examples: + >>> scan(my_pass, axis=KDim, forward=True, init=0.0)(a) # doctest: +SKIP + """ + from gt4py.next.embedded import context as embedded_context, operators as embedded_operators + + def scan_operator(*args: Any, **kwargs: Any) -> common.Field | Tuple: + scan_axis = axis if axis is not None else embedded_context.get_closure_column_range().dim + return embedded_operators.ScanOperator(scan_pass, forward, init, scan_axis)(*args, **kwargs) + + return scan_operator + + @WhereBuiltinFunction def where( mask: common.Field, @@ -453,6 +499,7 @@ def impl( "broadcast", "where", "astype", + "scan", *MATH_BUILTIN_NAMES, ] diff --git a/src/gt4py/next/ffront/foast_passes/type_deduction.py b/src/gt4py/next/ffront/foast_passes/type_deduction.py index 738b105a61..8415e43135 100644 --- a/src/gt4py/next/ffront/foast_passes/type_deduction.py +++ b/src/gt4py/next/ffront/foast_passes/type_deduction.py @@ -163,6 +163,64 @@ def _no_implicit_conversion_diagnostic(left: foast.Expr, right: foast.Expr) -> d } +def _is_scan_builtin(expr: foast.Expr) -> bool: + return isinstance(expr, foast.Name) and expr.id == "scan" + + +def _is_literal(expr: foast.Expr) -> bool: + match expr: + case foast.Constant(): + return True + case foast.TupleExpr(): + return all(_is_literal(el) for el in expr.elts) + case foast.UnaryOp(): + return _is_literal(expr.operand) + case foast.Call(func=foast.Name(type=ts.ConstructorType())): + return all(_is_literal(arg) for arg in expr.args) + return False + + +def _check_scan_pass( + location: eve.SourceLocation, + name: str, + pass_type: ts.FunctionType, + forward_type: ts.TypeSpec, + init_type: ts.TypeSpec, +) -> None: + if not (isinstance(forward_type, ts.ScalarType) and forward_type.kind == ts.ScalarKind.BOOL): + raise errors.DSLError( + location, f"Argument 'forward' to scan operator '{name}' must be a boolean." + ) + if not all( + type_info.is_arithmetic(type_) or type_info.is_logical(type_) + for type_ in type_info.primitive_constituents(init_type) + ): + raise errors.DSLError( + location, + f"Argument 'init' to scan operator '{name}' must " + "be an arithmetic type or a logical type or a composite of arithmetic and logical types.", + ) + if not pass_type.pos_or_kw_args: + raise errors.DSLError( + location, + f"Scan operator '{name}' must have at least one argument (the carry).", + ) + carry_arg_name = next(iter(pass_type.pos_or_kw_args.keys())) + carry_type = pass_type.pos_or_kw_args[carry_arg_name] + if carry_type != pass_type.returns: + raise errors.DSLError( + location, + f"Argument '{carry_arg_name}' to scan operator '{name}' must have same type as its return: " + f"expected '{pass_type.returns}', got '{carry_type}'.", + ) + elif init_type != carry_type: + raise errors.DSLError( + location, + f"Argument 'init' to scan operator '{name}' must have same type as '{carry_arg_name}' argument: " + f"expected '{carry_type}', got '{init_type}'.", + ) + + class FieldOperatorTypeDeduction(traits.VisitorWithSymbolTableTrait, NodeTranslator): """ Deduce and check types of FOAST expressions and symbols. @@ -250,51 +308,115 @@ def visit_ScanOperator(self, node: foast.ScanOperator, **kwargs: Any) -> foast.S f"Argument 'axis' to scan operator '{node.id}' must be a vertical dimension.", ) new_forward = self.visit(node.forward, **kwargs) - if not new_forward.type.kind == ts.ScalarKind.BOOL: - raise errors.DSLError( - node.location, f"Argument 'forward' to scan operator '{node.id}' must be a boolean." - ) new_init = self.visit(node.init, **kwargs) - if not all( - type_info.is_arithmetic(type_) or type_info.is_logical(type_) - for type_ in type_info.primitive_constituents(new_init.type) - ): + new_definition = self.visit(node.definition, **kwargs) + _check_scan_pass( + node.location, node.id, new_definition.type, new_forward.type, new_init.type + ) + + new_type = ts_ffront.ScanOperatorType( + axis=new_axis.type.dim, definition=new_definition.type + ) + return foast.ScanOperator( + id=node.id, + axis=new_axis, + forward=new_forward, + init=new_init, + definition=new_definition, + type=new_type, + location=node.location, + ) + + def _visit_scan_call( + self, node: foast.Call, scan_arg_types: list[ts.TypeSpec], **kwargs: Any + ) -> foast.Call: + """Type `scan(pass, axis=..., forward=..., init=...)`, the callee of a call-site scan.""" + new_func = self.visit(node.func, **kwargs) + if len(node.args) != 1: raise errors.DSLError( node.location, - f"Argument 'init' to scan operator '{node.id}' must " - "be an arithmetic type or a logical type or a composite of arithmetic and logical types.", + f"'scan' takes exactly one positional argument (the scan pass), got {len(node.args)}.", ) - new_definition = self.visit(node.definition, **kwargs) - new_def_type = new_definition.type - if not new_def_type.pos_or_kw_args: + if unexpected := set(node.kwargs) - {"axis", "forward", "init"}: raise errors.DSLError( node.location, - f"Scan operator '{node.id}' must have at least one argument (the carry).", + f"Unexpected keyword argument(s) {', '.join(sorted(unexpected))} to 'scan'.", ) - carry_arg_name = next(iter(new_def_type.pos_or_kw_args.keys())) - carry_type = new_def_type.pos_or_kw_args[carry_arg_name] - if carry_type != new_def_type.returns: + new_pass = self.visit(node.args[0], **kwargs) + if not isinstance(new_pass.type, ts_ffront.FieldOperatorType): raise errors.DSLError( - node.location, - f"Argument '{carry_arg_name}' to scan operator '{node.id}' must have same type as its return: " - f"expected '{new_def_type.returns}', got '{carry_type}'.", + new_pass.location, + f"The scan pass must be a field operator, got '{new_pass.type}'.", ) - elif new_init.type != carry_type: + pass_type = new_pass.type.definition + pass_name = str(new_pass) + + new_kwargs = { + "forward": foast.Constant(value=True, location=node.location), + "init": foast.Constant(value=0.0, location=node.location), + **node.kwargs, + } + new_kwargs = {name: self.visit(arg, **kwargs) for name, arg in new_kwargs.items()} + for name in ("forward", "init"): + if not _is_literal(new_kwargs[name]): + raise errors.DSLError( + new_kwargs[name].location, + f"Argument '{name}' to 'scan' must be a compile-time constant.", + ) + _check_scan_pass( + node.location, pass_name, pass_type, new_kwargs["forward"].type, new_kwargs["init"].type + ) + if not all( + isinstance(t, ts.ScalarType) + for param in [*pass_type.pos_or_kw_args.values(), pass_type.returns] + for t in type_info.primitive_constituents(param) + ): raise errors.DSLError( - node.location, - f"Argument 'init' to scan operator '{node.id}' must have same type as '{carry_arg_name}' argument: " - f"expected '{carry_type}', got '{new_init.type}'.", + new_pass.location, + f"The scan pass '{pass_name}' must take and return scalars or tuples of scalars.", + ) + if pass_type.pos_only_args or pass_type.kw_only_args: + raise errors.DSLError( + new_pass.location, + f"The scan pass '{pass_name}' must not have positional-only or keyword-only arguments.", ) - new_type = ts_ffront.ScanOperatorType(axis=new_axis.type.dim, definition=new_def_type) - return foast.ScanOperator( - id=node.id, - axis=new_axis, - forward=new_forward, - init=new_init, - definition=new_definition, - type=new_type, + if "axis" in new_kwargs: + axis_type = new_kwargs["axis"].type + if not isinstance(axis_type, ts.DimensionType): + raise errors.DSLError( + new_kwargs["axis"].location, "Argument 'axis' to 'scan' must be a dimension." + ) + axis = axis_type.dim + if axis.kind != DimensionKind.VERTICAL: + raise errors.DSLError( + new_kwargs["axis"].location, + "Argument 'axis' to 'scan' must be a vertical dimension.", + ) + else: + vertical_dims = { + dim + for arg_type in scan_arg_types + for el in type_info.primitive_constituents(arg_type) + for dim in type_info.extract_dims(el) + if dim.kind == DimensionKind.VERTICAL + } + if len(vertical_dims) != 1: + found = ", ".join(sorted(f"'{d.value}'" for d in vertical_dims)) or "none" + raise errors.DSLError( + node.location, + "Cannot infer the 'axis' of 'scan' from its arguments, expected exactly one " + f"vertical dimension, found {found}.", + hints=["Pass the axis explicitly, e.g. 'scan(..., axis=KDim)'."], + ) + (axis,) = vertical_dims + + return foast.Call( + func=new_func, + args=[new_pass], + kwargs=new_kwargs, location=node.location, + type=ts_ffront.ScanOperatorType(axis=axis, definition=pass_type), ) def visit_Name(self, node: foast.Name, **kwargs: Any) -> foast.Name: @@ -757,9 +879,22 @@ def visit_TupleExpr(self, node: foast.TupleExpr, **kwargs: Any) -> foast.TupleEx return foast.TupleExpr(elts=new_elts, type=new_type, location=node.location) def visit_Call(self, node: foast.Call, **kwargs: Any) -> foast.Call: - new_func = self.visit(node.func, **kwargs) + if _is_scan_builtin(node.func): + raise errors.DSLError( + node.location, + "'scan' creates a scan operator which must be called directly: " + "'scan(scan_pass, ...)(args)'.", + ) new_args = self.visit(node.args, **kwargs) new_kwargs = self.visit(node.kwargs, **kwargs) + if isinstance(node.func, foast.Call) and _is_scan_builtin(node.func.func): + new_func = self._visit_scan_call( + node.func, + scan_arg_types=[arg.type for arg in [*new_args, *new_kwargs.values()]], + **kwargs, + ) + else: + new_func = self.visit(node.func, **kwargs) func_type = new_func.type arg_types = [arg.type for arg in new_args] @@ -779,6 +914,9 @@ def visit_Call(self, node: foast.Call, **kwargs: Any) -> foast.Call: if not isinstance( new_func, (foast.FunctionDefinition, foast.FieldOperator, foast.ScanOperator, foast.Name), + ) and not ( + isinstance(new_func, foast.Call) + and isinstance(new_func.type, ts_ffront.ScanOperatorType) ): raise errors.DSLError(node.location, "Functions can only be called directly.") elif isinstance(new_func.type, ts.FieldType): @@ -811,6 +949,7 @@ def visit_Call(self, node: foast.Call, **kwargs: Any) -> foast.Call: f"Expression of type '{new_func.type}' is not callable, must be a 'Function', 'FieldOperator', 'ScanOperator' or 'Field'.", ) + assert isinstance(func_type, ts.CallableType) # ensure signature is valid try: type_info.accepts_args( diff --git a/src/gt4py/next/ffront/foast_to_gtir.py b/src/gt4py/next/ffront/foast_to_gtir.py index 9b3c15d7eb..3e2e957d2b 100644 --- a/src/gt4py/next/ffront/foast_to_gtir.py +++ b/src/gt4py/next/ffront/foast_to_gtir.py @@ -351,7 +351,11 @@ def _visit_shift(self, node: foast.Call, **kwargs: Any) -> itir.Expr: return current_expr def visit_Call(self, node: foast.Call, **kwargs: Any) -> itir.Expr: - if type_info.type_class(node.func.type) is ts.FieldType: + if isinstance(node.func, foast.Call) and isinstance( + node.func.type, ts_ffront.ScanOperatorType + ): + return self._visit_scan_call(node, **kwargs) + elif type_info.type_class(node.func.type) is ts.FieldType: return self._visit_shift(node, **kwargs) elif isinstance(node.func, foast.Name) and node.func.id in fbuiltins.MATH_BUILTIN_NAMES: return self._visit_math_built_in(node, **kwargs) @@ -393,6 +397,26 @@ def visit_Call(self, node: foast.Call, **kwargs: Any) -> itir.Expr: f"Call to object of type '{type(node.func.type).__name__}' not understood." ) + def _visit_scan_call(self, node: foast.Call, **kwargs: Any) -> itir.Expr: + # `scan(scan_pass, forward=..., init=...)(*args)` + scan_call = node.func + assert isinstance(scan_call, foast.Call) + assert isinstance(scan_call.type, ts_ffront.ScanOperatorType) + scan_pass = self.visit(scan_call.args[0], **kwargs) + forward = self.visit(scan_call.kwargs["forward"], **kwargs) + init = self.visit(scan_call.kwargs["init"], **kwargs) + + lowered_args, lowered_kwargs = type_info.canonicalize_arguments( + scan_call.type, self.visit(node.args, **kwargs), self.visit(node.kwargs, **kwargs) + ) + stencil_args = [*lowered_args, *lowered_kwargs.values()] + carry = next(self.uid_generator["__scan_carry"]) + params = [next(self.uid_generator["__scan_arg"]) for _ in stencil_args] + definition = im.lambda_(carry, *params)( + im.call(scan_pass)(carry, *(im.deref(param) for param in params)) + ) + return im.as_fieldop(im.scan(definition, forward, init))(*stencil_args) + def _visit_astype(self, node: foast.Call, **kwargs: Any) -> itir.Expr: # Note: the type to convert to is uniquely identified by its GT4Py type (`ConstructorType`), # not by e.g. its name. diff --git a/src/gt4py/next/ffront/foast_to_past.py b/src/gt4py/next/ffront/foast_to_past.py index beabe53c71..edc37bdeb8 100644 --- a/src/gt4py/next/ffront/foast_to_past.py +++ b/src/gt4py/next/ffront/foast_to_past.py @@ -36,6 +36,10 @@ class ItirShim: definition: ConcreteFOASTOperatorDef foast_to_itir: workflow.Workflow[ConcreteFOASTOperatorDef, itir.FunctionDefinition] + @property + def foast_stage(self) -> ffront_stages.FOASTOperatorDef: + return self.definition.data + def __gt_closure_vars__(self) -> Optional[dict[str, Any]]: return self.definition.data.closure_vars diff --git a/src/gt4py/next/ffront/past_to_itir.py b/src/gt4py/next/ffront/past_to_itir.py index cd908fca14..dfa3d4b5cd 100644 --- a/src/gt4py/next/ffront/past_to_itir.py +++ b/src/gt4py/next/ffront/past_to_itir.py @@ -18,6 +18,7 @@ from gt4py.next import common, config, errors, utils from gt4py.next.ffront import ( fbuiltins, + field_operator_ast as foast, gtcallable, program_ast as past, stages as ffront_stages, @@ -168,6 +169,17 @@ def _column_axis(all_closure_vars: dict[str, Any]) -> Optional[common.Dimension] ).items(): if isinstance((type_ := gt_callable.__gt_type__()), ts_ffront.ScanOperatorType): scanops_per_axis.setdefault(type_.axis, []).append(name) + elif isinstance( + foast_stage := getattr(gt_callable, "foast_stage", None), ffront_stages.FOASTOperatorDef + ): + for scan_call in ( + foast_stage.foast_node.walk_values() + .if_isinstance(foast.Call) + .filter(lambda call: isinstance(call.type, ts_ffront.ScanOperatorType)) + ): + scanops_per_axis.setdefault(scan_call.type.axis, []).append( + f"scan in '{name}' (line {scan_call.location.line})" + ) if len(scanops_per_axis.values()) == 0: return None diff --git a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_foast_pretty_printer.py b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_foast_pretty_printer.py index 8ba6f3091a..3d0ab5e772 100644 --- a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_foast_pretty_printer.py +++ b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_foast_pretty_printer.py @@ -70,17 +70,17 @@ def test_scanop(): KDim = Dimension("KDim", kind=DimensionKind.VERTICAL) @scan_operator(axis=KDim, forward=False, init=1) - def scan(inp: int32) -> int32: + def scan_op(inp: int32) -> int32: foo = inp return inp expected = textwrap.dedent( f""" @scan_operator(axis=KDim[vertical], forward=False, init=1) - def scan(inp: int32) -> int32: + def scan_op(inp: int32) -> int32: {ssa.unique_name("foo", 0)} = inp return inp """ ).strip() - assert pretty_format(scan.foast_stage.foast_node) == expected + assert pretty_format(scan_op.foast_stage.foast_node) == expected diff --git a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_scan.py b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_scan.py index ae9e9b37ef..508c3b0d1a 100644 --- a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_scan.py +++ b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_scan.py @@ -11,7 +11,7 @@ import pytest import gt4py.next as gtx -from gt4py.next import errors, float64, int32 +from gt4py.next import errors, float64, int32, scan from gt4py.next.ffront.decorator import program, scan_operator from next_tests.integration_tests import cases @@ -391,3 +391,68 @@ def test_scan_without_carry(cartesian_case): @scan_operator(axis=KDim, forward=True, init=0) def testee_scan() -> float: return 1.0 + + +@pytest.mark.uses_scan +@pytest.mark.uses_scan_in_field_operator +def test_scan_call(cartesian_case): + @gtx.field_operator + def add(carry: float, inp: float) -> float: + return carry + inp + + @gtx.field_operator + def testee(inp: cases.IKFloatField) -> cases.IKFloatField: + return scan(add, axis=KDim, forward=True, init=1.0)(inp) + + inp = cases.allocate(cartesian_case, testee, "inp")() + out = cases.allocate(cartesian_case, testee, cases.RETURN).zeros()() + + cases.verify(cartesian_case, testee, inp, out=out, ref=1.0 + np.cumsum(inp.asnumpy(), axis=1)) + + +@pytest.mark.uses_scan +@pytest.mark.uses_scan_in_field_operator +def test_scan_call_backward_inferred_axis(cartesian_case): + @gtx.field_operator + def add(carry: float, inp: float, scalar: float) -> float: + return carry + inp * scalar + + @gtx.field_operator + def testee(inp: cases.IKFloatField, scalar: float) -> cases.IKFloatField: + return scan(add, forward=False, init=-1.0)(inp, scalar) + inp + + inp = cases.allocate(cartesian_case, testee, "inp")() + out = cases.allocate(cartesian_case, testee, cases.RETURN).zeros()() + inp_np = inp.asnumpy() + backward_cumsum = np.flip(np.cumsum(np.flip(2.0 * inp_np, axis=1), axis=1), axis=1) + + cases.verify(cartesian_case, testee, inp, 2.0, out=out, ref=backward_cumsum - 1.0 + inp_np) + + +@pytest.mark.uses_scan +@pytest.mark.uses_scan_in_field_operator +@pytest.mark.uses_tuple_returns +def test_scan_call_tuple_carry(cartesian_case): + @gtx.field_operator + def sum_and_count(carry: tuple[float, int32], inp: float) -> tuple[float, int32]: + return carry[0] + inp, carry[1] + int32(1) + + @gtx.field_operator + def testee(inp: cases.IKFloatField) -> tuple[cases.IKFloatField, cases.IKField]: + return scan(sum_and_count, axis=KDim, init=(0.0, int32(0)))(inp) + + inp = cases.allocate(cartesian_case, testee, "inp")() + out = cases.allocate(cartesian_case, testee, cases.RETURN).zeros()() + isize = cartesian_case.default_sizes[IDim] + ksize = cartesian_case.default_sizes[KDim] + + cases.verify( + cartesian_case, + testee, + inp, + out=out, + ref=( + np.cumsum(inp.asnumpy(), axis=1), + np.full((isize, ksize), np.arange(1, ksize + 1, dtype=np.int32)), + ), + ) 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..3ddee90be9 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 @@ -26,7 +26,9 @@ float64, int32, int64, + field_operator, neighbor_sum, + scan, where, ) from gt4py.next.ffront.experimental import concat_where @@ -798,3 +800,75 @@ def testee( match="Second and third argument to 'concat_where' must have the same tuple/collection structure", ): parsed = FieldOperatorParser.apply_to_function(testee) + + +KDim = Dimension("KDim", kind=DimensionKind.VERTICAL) + + +@field_operator +def _scan_pass(carry: float, inp: float) -> float: + return carry + inp + + +def test_scan_call(): + def scan_call(a: Field[[TDim, KDim], float64]) -> Field[[TDim, KDim], float64]: + return scan(_scan_pass, init=0.0)(a) + + parsed = FieldOperatorParser.apply_to_function(scan_call) + + assert parsed.type.returns == ts.FieldType( + dims=[TDim, KDim], dtype=ts.ScalarType(kind=ts.ScalarKind.FLOAT64) + ) + + +def test_scan_call_not_called(): + def scan_not_called(a: Field[[TDim, KDim], float64]) -> Field[[TDim, KDim], float64]: + op = scan(_scan_pass, axis=KDim) + return a + + with pytest.raises( + errors.DSLError, match=r"'scan' creates a scan operator which must be called" + ): + _ = FieldOperatorParser.apply_to_function(scan_not_called) + + +def test_scan_call_axis_not_inferable(): + def no_vertical_dim(a: Field[[TDim], float64]) -> Field[[TDim, KDim], float64]: + return scan(_scan_pass)(a) + + with pytest.raises(errors.DSLError, match=r"Cannot infer the 'axis' of 'scan'"): + _ = FieldOperatorParser.apply_to_function(no_vertical_dim) + + +def test_scan_call_non_vertical_axis(): + def non_vertical_axis(a: Field[[TDim, KDim], float64]) -> Field[[TDim, KDim], float64]: + return scan(_scan_pass, axis=TDim)(a) + + with pytest.raises(errors.DSLError, match=r"'axis' to 'scan' must be a vertical dimension"): + _ = FieldOperatorParser.apply_to_function(non_vertical_axis) + + +def test_scan_call_non_constant_init(): + def non_constant_init( + a: Field[[TDim, KDim], float64], init: float64 + ) -> Field[[TDim, KDim], float64]: + return scan(_scan_pass, axis=KDim, init=init)(a) + + with pytest.raises(errors.DSLError, match=r"'init' to 'scan' must be a compile-time constant"): + _ = FieldOperatorParser.apply_to_function(non_constant_init) + + +def test_scan_call_wrong_init_type(): + def wrong_init_type(a: Field[[TDim, KDim], float64]) -> Field[[TDim, KDim], float64]: + return scan(_scan_pass, axis=KDim, init=0)(a) + + with pytest.raises(errors.DSLError, match=r"Argument 'init' to scan operator '_scan_pass'"): + _ = FieldOperatorParser.apply_to_function(wrong_init_type) + + +def test_scan_call_pass_not_a_field_operator(): + def pass_is_builtin(a: Field[[TDim, KDim], float64]) -> Field[[TDim, KDim], float64]: + return scan(where, axis=KDim)(a) + + with pytest.raises(errors.DSLError, match=r"The scan pass must be a field operator"): + _ = FieldOperatorParser.apply_to_function(pass_is_builtin)