Adding MlirBool to C Bindings

I think it would be useful to add an MlirBool type (similar to MlirLogicalResult) with the associated mlirBoolIs{True,False} accessors. This would be convenient in Swift because currently the return value for functions like mlirAttributeIsNull is mapped to Int32. Types aren’t automatically coerced to Bool in Swift so you can’t write if mlirAttributeIsNull(attr) and there is the tiniest bit of cognitive overhead for me to recall whether or not I need to check == 0 or != 0.
This isn’t a huge deal, so if it would be a pain for other bindings I’m not going to push on this too hard.

Can’t you map specifically mlirAttributeIsNull and other “boolean” API to use a Bool in Swift?

We can, manually. Swift also provides automatic mapping of C types into equivalent Swift types, so

static inline int mlirAttributeIsNull(MlirAttribute attr) { return !attr.ptr; }

is imported as

public func mlirAttributeIsNull(_ attr: MlirAttribute) -> Int32

I could add an extension on Int32 providing the property var boolValue: Bool { self != 0 } but that would add it to every Int32 in the API, which is likely fine but it would be cleaner to only provide that property on semantically-Bool values.

Again, this isn’t a major issue, just something that would make the code implementing the bindings a little cleaner.

Inventing a new concept and accessors for bool would make the API less usable from C, which seems weird.

I’d be fine with a couple of options, if they help:

  • Require c99, at least with respect to _Bool, which probably is fine. Msvc is the laggard here and has supported this since 2013.
  • Define an MlirBool enum with mlirFalse and mlirTrue members. Not sure if you could map this.

I’d just do the first option. Include stdbool.h and switch all of these to bool.

1 Like

Yeah, I’m not sure why we aren’t just using _Bool here, it seems portable enough and easy enough to #define for targets that don’t support it.

instead of:

inline int mlirAttributeIsNull(MlirAttribute attr) { return !attr.ptr; }

Just use:

inline _Bool mlirAttributeIsNull(MlirAttribute attr) { return !attr.ptr; }

Is there some disadvantage to that?


_Bool didn’t work for me, but bool did:

I don’t think _Bool is a c++ type. I think the “right way” to do this in a c header that can also be used in c++ is to include stdbool.h and use the bool type.

Could be wrong on this.

stdbool.h makes sense to me.