Skip to content

Commit

Permalink
[Lang] Type check assignments between tensors (taichi-dev#7480)
Browse files Browse the repository at this point in the history
Issue: fix taichi-dev#7453

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
  • Loading branch information
2 people authored and quadpixels committed May 13, 2023
1 parent bfea99d commit 8926716
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
13 changes: 13 additions & 0 deletions taichi/transforms/frontend_type_check.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,20 @@ class FrontendTypeCheck : public IRVisitor {
}

void visit(FrontendAssignStmt *stmt) override {
auto lhs_type = stmt->lhs->ret_type;
auto rhs_type = stmt->rhs->ret_type;

auto error = [&]() {
throw TaichiTypeError(fmt::format("{}cannot assign '{}' to '{}'",
stmt->tb, rhs_type->to_string(),
lhs_type->to_string()));
};

// No implicit cast at frontend for now
if (is_tensor(lhs_type) && is_tensor(rhs_type) &&
lhs_type.get_shape() != rhs_type.get_shape()) {
error();
}
}

void visit(FrontendIfStmt *stmt) override {
Expand Down
15 changes: 15 additions & 0 deletions tests/python/test_type_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,3 +80,18 @@ def foo():
"Only 0-dimensional numpy array can be used to initialize a scalar expression"
):
foo()


@test_utils.test(arch=ti.cpu)
def test_assign():
f = ti.Vector.field(4, dtype=ti.i32, shape=())

@ti.kernel
def floor():
f[None] = ti.Vector([1, 2, 3])

with pytest.raises(
ti.TaichiTypeError,
match=
r"cannot assign '\[Tensor \(3\) i32\]' to '\[Tensor \(4\) i32\]'"):
floor()

0 comments on commit 8926716

Please sign in to comment.