E3011

E3011 — An as cast between two types that it does not convert, such as from an integer or a float to bool. Rust refuses the same casts. A comparison such as x != 0 says which values count as true.

What the compiler reports

Error[E3011] at {{.*}}a_cast_from_a_number_to_bool.vx:16:13: cannot cast `i32` to `bool`: compare it with zero instead, as in `x != 0`
Error[E3011] at {{.*}}a_cast_from_a_number_to_bool.vx:19:13: cannot cast `f32` to `bool`: compare it with zero instead, as in `x != 0.0`
Error[E3011] at {{.*}}a_cast_from_a_number_to_bool.vx:22:17: cannot cast `u8` to `bool`
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
//
//
// Only a `bool` casts to a `bool`, as in Rust. A cast from an integer kept only the lowest bit,
// so `2 as bool` was `false`. A cast from a `bool` to an integer stays allowed.

fn main() -> i32 {
  let x : i32 = 2;
  let a = x as bool;
  let f : f32 = 0.5;
  let b = f as bool;
  let small : u8 = 1;
  let c = small as bool;
  let flag = true;
  let n : i32 = flag as i32;
  let nonzero : bool = x != 0;
  return 0;
}

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

Related