E3046

E3046 — A for loop over a tensor that is not a variable or a flat array literal, such as one a function call returns, or a nested array literal. The loop reads the tensor by index, so it needs a name: bind the tensor with let first. Also a loop over &mut t: the loop gives copies of the elements, so it cannot change them.

What the compiler reports

Error[E3046] at {{.*}}for_loop_over_a_tensor_with_no_name.vx:25:12: a `for` loop over a tensor reads it by index
Error[E3046] at {{.*}}for_loop_over_a_tensor_with_no_name.vx:28:3: a `for` loop cannot go over a nested array literal
Error[E3046] at {{.*}}for_loop_over_a_tensor_with_no_name.vx:32:12: a `for` loop over a tensor gives copies of its elements
{{^}}Semantic check failed on {{.*}}: 3 error(s) emitted

The fragments the test suite holds the compiler to. An ellipsis marks text the test does not constrain; the emitted message also carries a source location.

A program that triggers it

//
// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions.
// See LICENSE for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
// A `for` loop reads a tensor by index, so it needs the tensor in a variable or a flat array
// literal. A tensor a function returns, and a nested array literal, get E3046. The loop gives
// copies of the elements, so a loop over `&mut t` also gets E3046.

fn make() -> Tensor<i32, [3]> {
  let t = Tensor<i32, [3]>::new();
  return t;
}

fn main() -> i32 {
  let mut s = 0;
  for x in make() {
    s = s + x;
  }
  for r in [[1, 2], [3, 4]] {
    s = s + r[1];
  }
  let mut t = Tensor<i32, [3]>::new();
  for x in &mut t {
    s = s + x;
  }
  return s;
}

From tests/frontend/fail/for_loop_over_a_tensor_with_no_name.vx, which asserts this diagnostic on every commit.

Related