mozilla / mozilla/cbindgen

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

Open
#1,018 4 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Rust
Stars
3k
Forks
386
Avg merge
1h 43m
Merged PRs (30d)
1

Description

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

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by tracing how cbindgen handles Rust const expressions and cfg! conditions. Review the two examples and determine how target flags and panic-style else branches should map to generated C preprocessor directives. Done means supported const if/cfg! expressions produce the expected conditional definitions and unsupported branches can emit the requested error directive.

Written by the indexing model from the issue text.

Assessment

Tech stack
c, rust
Domain
tooling
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.