|
|
Subscribe / Log in / New account

Insulating layer?

Insulating layer?

Posted Oct 11, 2024 14:29 UTC (Fri) by adobriyan (subscriber, #30858)
In reply to: Insulating layer? by asahilina
Parent article: On Rust in enterprise kernels

Speaking of macros, can they do:

struct S {
int a;
#ifdef CONFIG_B
int b;
#endif
};

I've seen std::conditional_t implementation on some video (which looks almost exactly like C++ version) which makes me think they can not.


to post comments

Insulating layer?

Posted Oct 11, 2024 15:11 UTC (Fri) by farnz (subscriber, #17727) [Link]

That's built-in, and can be done via macros, or via the existing #[cfg] attribute. Macros in general in Rust get an AST, and output a new AST, so can do pretty much anything (noting that only function-like macros get an arbitrary AST; attribute macros and derive macros must be given valid Rust source code).

But using the built-in #[cfg] mechanism, along with feature flags, you'd write that as:

struct S {
    a: i32,
    #[cfg(feature = "config_b")]
    b: i32
}

This says that the field b only exists if the feature flag "config_b" is set at compile time; there's also preset cfg items, like target_has_atomic, which lets you write #[cfg(target_has_atomic = "64")] to only include a chunk of code on platforms with support for 64 bit atomics.

Insulating layer?

Posted Oct 11, 2024 15:26 UTC (Fri) by khim (subscriber, #9252) [Link]

You don't need macros for that because that's handled by separate facility in Rust.

> I've seen std::conditional_t implementation on some video (which looks almost exactly like C++ version) which makes me think they can not.

You probably misunderstood the precise limitation, I'm afraid. Macros in Rust are incredibly powerful, but they still work with a token trees. You can support configurable code and conditional compilation with them just fine, but they don't have access to the type information. std::conditional_t (and whatever Rust equivalent you saw) work with types, not with defines, and yes, that's something macros couldn't touch (neither in C/C++ nor in Rust) simply because macros work before types come into existence.

If you go from C++ to Rust then yes, this limitation feels quite stifling. If you go from C to Rust… nope: C simply doesn't have anything similar to reflection. magic_enum couldn't be replicated in Rust, but then it doesn't work with C, either.


Copyright © 2025, Eklektix, Inc.
Comments and public postings are copyrighted by their creators.
Linux is a registered trademark of Linus Torvalds