rust-lang / rust-lang/rust-bindgen

[Feature Request] Keep the integer literal radices of C and C++ in generated Rust

Open
#3,236 8 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

enhancement
Dominant language
Rust
Stars
5.3k
Forks
829
Avg merge
1d 1h
Merged PRs (30d)
15

Description

It would be great if the Rust code generated by bindgen would keep the number bases of the integer literals in the input C and C++ code. After all, the writer of the C or C++ code probably had a good reason for using a specific radix.

C23[^1], C++14[^2], and Rust[^3] all support binary, octal, and hexadecimal base numbers, with C23 and C++14 sharing the same syntax. A one-to-one mapping with Rust seems to be possible.

For example, given the following code working in both C23 and C++14:

#define BIN_LIT 0b10
#define OCT_LIT 010
#define HEX_LIT 0x10

the generated Rust bindings would be:

pub const BIN_LIT: u32 = 0b10;
pub const OCT_LIT: u32 = 0o10;
pub const HEX_LIT: u32 = 0x10;

In addition to the #defined constants, the number bases of e.g. consts and enums would be kept as well.

A bit of not too serious motivation

Just for the reference, if someone finds this interesting. I ran the following command in a fresh git clone of the Linux kernel repository, finding lines in .h files only that have a #define with a hexadecimal literal later on that line:

rg "\#define.+\b0x" --type h | wc -l

Currently, that's 4 519 652 such lines.

@rustbot label enhancement

[^1]: ISO/IEC 9899:2024 (en), draft N3220, chapter 6.4.4.2 Integer constants
[^2]: ISO/IEC 14882:2014, draft N3797, chapter 2.14.2 Integer literals
[^3]: Rust Reference: 2.6 Tokens, Number literals, 8.2.1 Literal expressions, Integer literals expressions

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

The issue names no files or tests. Start by tracing how bindgen emits #define constants, consts, and enums from C/C++ integer literals; done means generated Rust preserves binary, octal, and hexadecimal bases as shown, with coverage for those forms.

Written by the indexing model from the issue text.

Assessment

Tech stack
c, cpp, rust
Domain
tooling
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.