Skip to content
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

[Feature Request] Handle if + cfg! in const context #1018

Open
GrayJack opened this issue Oct 27, 2024 · 2 comments
Open

[Feature Request] Handle if + cfg! in const context #1018

GrayJack opened this issue Oct 27, 2024 · 2 comments

Comments

@GrayJack
Copy link
Contributor

Since the addition of if in const context, the usage of if + cfg! macro became a thing, since it reduces the need of replication of docs and definition.

pub const MYCONST: i32 = if cfg!(target_os = "linux") {
    10
} else if cfg!(windows) {
    5
} else {
    0
}

Currently, cbindgen ignores this kind of construction, but ideally, supporting that would make easier for maintaining C-exported constants that differ on targets.

Possible expected result:

#if defined(⟨USER_DEFINED_LINUX_FLAG_HERE⟩)
    #define MYCONST   10
#elsif defined(⟨USER_DEFINED_WINDOWS_FLAG_HERE⟩)
    #define MYCONST   5
#else
    0
#endif

In const context, an if must always have an else, so it is also common to have panicking macros, like panic!, unimplemented!, todo! and unreacheble! in the else clause. That causes an compiler error with the panic message if it reaches the panic. I think this could generate an #error directive with the message.

Example

pub const MYCONST: i32 = if cfg!(target_os = "linux") {
    10
} else if cfg!(windows) {
    5
} else {
    panic!("We only support linux and windows for now!")
}
#if defined(⟨USER_DEFINED_LINUX_FLAG_HERE⟩)
    #define MYCONST   10
#elsif defined(⟨USER_DEFINED_WINDOWS_FLAG_HERE⟩)
    #define MYCONST   5
#else
    #error "We only support linux and windows for now!"
#endif
@GrayJack
Copy link
Contributor Author

Its unclear to me how this would work with the macro expansion feature. I'm not using the expasion feature in none of my projects that uses cbindgen

@GrayJack
Copy link
Contributor Author

I currently have a working version for C/C++, but I have no idea how would be the equivalent for Cython to turn panics-> #error

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

1 participant