c3lang / c3c

Compiler for the C3 language
https://c3-lang.org
GNU Lesser General Public License v3.0
2.78k stars 168 forks source link

Type suggestion: CBool #1530

Open TheOnlySilverClaw opened 1 week ago

TheOnlySilverClaw commented 1 week ago

For type-safe interaction with C APIs, it would be helpful to have a CBool type that behaves like an integer that can only be assigned 0 or 1 and be implicitly cast to bool where needed.


fn void test_cbool() @test {

    CBool value;
    value =  true;
    value = false;
    value = 0;
    value = 1;
    value = 2; // compiler error
    value = -1; // compiler error

    bool b = value;

    assert(CBool.sizeof == CInt.sizeof);
}

I know integers can already be used in conditions, but this would also communicate the allowed values and prevent accidental assignment of a wrong one for functions like these:


fn extern void foo(CInt boolFlag) {

}
lerno commented 1 week ago

I want to avoid adding things merely for the convenience of C bindings. Is there some other use for this?

TheOnlySilverClaw commented 1 week ago

I can't think of much. The name was deliberately chosen to reflect that usage.

I know it sounds a little weird, but so far all the C bindings I've used had at least one place where it would have been useful and I've tried emulating it with enums and bitstructs each time.

It almost nearly works this way:

bitstruct CBool : CInt {
    bool flag;
}

fn void test_cbool() @test {

    CBool value = { false };
    assert((CInt) value == 0);

    value = (CBool) 1;
    assert((CInt) value == 1);
    assert(value.flag == true);
}

It's just slightly short of being convenient with all the casts required.

So maybe a more general case could be an inline bitstruct?

lerno commented 1 week ago

You could do:

enum CBool : CInt
{
  FALSE,
  TRUE
}

And now your call becomes:

foo(TRUE);
foo(FALSE);
TheOnlySilverClaw commented 1 week ago

Yes, been there. I guess it works. Would you mind adding that to the standard library types?

lerno commented 1 week ago

Done!

lerno commented 1 week ago

See if it works as expected.

TheOnlySilverClaw commented 1 week ago

Looks good:

https://codeberg.org/Silverclaw/glfw.c3l/commit/72061fb010513b281d85aaa7d468ee2b44db3555