Skip to content

Conversation

@KaiserGranatapfel
Copy link

Description

This PR implements the if_cfg! macro as requested in issue #1183. The macro simplifies conditional compilation patterns by providing a more readable syntax for selecting code based on kernel configuration options.

Changes

  • Added if_cfg! macro to rust/kernel/lib.rs
  • Updated rust/kernel/time.rs to demonstrate usage (4 instances replaced)
  • Macro supports both expression and statement positions

Benefits

  • Reduces code duplication
  • Improves readability compared to verbose #[cfg(...)] / #[cfg(not(...))] blocks
  • Follows Rust idioms more closely

Testing

  • Code formatted with rustfmt
  • All linter checks pass
  • Macro compiles successfully

Related

Closes #1183

Copy link
Author

@KaiserGranatapfel KaiserGranatapfel left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Self-review

  • Code compiles and passes formatting/linting checks
  • Macro implementation follows existing kernel macro patterns
  • Documentation complete with examples
  • Tested with existing conditional compilation patterns in time.rs

Ready for review.

This macro simplifies conditional compilation patterns by providing a
more readable syntax for selecting code based on kernel configuration
options. It replaces verbose #[cfg(...)] and #[cfg(not(...))] blocks
with a cleaner if_cfg!(if CONFIG_FOO { expr1 } else { expr2 }) syntax.

The macro works in both expression and statement positions, making it
versatile for various use cases throughout the kernel.

Examples of usage:
- Expression: let value = if_cfg!(if CONFIG_64BIT { x / y } else { unsafe { div64_s64(x, y) } });
- Statement: if_cfg!(if CONFIG_FOO { let x = 1; } else { let x = 2; });

This implementation also includes updates to rust/kernel/time.rs to
demonstrate the macro's usage, replacing several instances of the
verbose conditional compilation pattern.

Suggested-by: Rust-for-Linux Issue Rust-for-Linux#1183 <Rust-for-Linux#1183>
Link: Rust-for-Linux#1183
Signed-off-by: KaiserGranatapfel <christopher.erleigh@gmail.com>
@ojeda
Copy link
Member

ojeda commented Jan 20, 2026

Note that we don't use PRs anymore (you can leave it open if you think it is useful for some reason, though).

I see you sent the patch to the mailing list but it didn't arrive there: https://lore.kernel.org/rust-for-linux/CANiq72nMpO0o-P0BbTgxPU4RSOttFPc4UQzH9Bs73F7Bnkyxmg@mail.gmail.com/

Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

add if_cfg! macro

2 participants