Skip to content

changetype number to bool #342

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
LiaoPeng opened this issue Nov 23, 2018 · 8 comments
Closed

changetype number to bool #342

LiaoPeng opened this issue Nov 23, 2018 · 8 comments

Comments

@LiaoPeng
Copy link
Contributor

The assemblyscript code

assert(true == changetype<boolean>(1));
assert(false == changetype<boolean>(0));
assert(true == changetype<boolean>(3));
assert(false == changetype<boolean>(2));

I expected:
assert(false == changetype(2)); // failed

In fact, all asserts passed.

It seemed that changetype number to bool just get the last bit.

@dcodeIO
Copy link
Member

dcodeIO commented Nov 23, 2018

Note that changetype isn't meant for casting, but actually for changing between a reference and a value type, i.e. between SomeObject and usize. This is unsafe and shouldn't be used unless absolutely necessary.

For casting, there is <bool>2, or its portable version bool(2). Also, conversion to bool is performed through & 1 currently, which might be unexpected and might need to be changed to != 0 maybe. In general, I'd recommend to do 2 != 0 for clarity instead of casting.

@MaxGraey
Copy link
Member

MaxGraey commented Nov 23, 2018

I think change this to != 0 instead & 1 is right approach

@dcodeIO
Copy link
Member

dcodeIO commented Nov 23, 2018

Does C/C++ handle bool specifically as != 0?

@MaxGraey
Copy link
Member

Currently assert(true == <bool>(2)); is fail btw. Rust and C++ use != 0 approach.

0b10 & 1 = 0 // false

@dcodeIO
Copy link
Member

dcodeIO commented Nov 23, 2018

Ok, so we should add a special case for bool I guess.

@dcodeIO
Copy link
Member

dcodeIO commented Nov 23, 2018

For reference:

#include <stdbool.h>

#define WASM_EXPORT __attribute__((visibility("default")))

WASM_EXPORT
bool test(int i) {
  return ((bool)i) == true;
}

compiles to

  (func $test (export "test") (type $t1) (param $p0 i32) (result i32)
    get_local $p0
    i32.const 0
    i32.ne
  )

so != 0 seems good.

@dcodeIO
Copy link
Member

dcodeIO commented Nov 23, 2018

Fixed in #343 for casts. Please keep in mind that changetype isn't meant for this.

@dcodeIO dcodeIO closed this as completed Nov 23, 2018
@LiaoPeng
Copy link
Contributor Author

cool

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants