Skip to content

Use cfg_select in a bunch more places#7740

Merged
coolreader18 merged 2 commits into
RustPython:mainfrom
coolreader18:cfg_select
May 4, 2026
Merged

Use cfg_select in a bunch more places#7740
coolreader18 merged 2 commits into
RustPython:mainfrom
coolreader18:cfg_select

Conversation

@coolreader18
Copy link
Copy Markdown
Member

@coolreader18 coolreader18 commented Apr 30, 2026

A sort of follow-up to #7636. I tried to not overdo it here, and I think most of the places I chose are genuinely easier to understand than before.

Summary by CodeRabbit

  • Refactor
    • Unified platform- and feature-specific branching across the codebase, consolidating conditional compilation into a single selection mechanism. Changes touch many subsystems (stdlib, stdlib modules, VM, I/O, crypto, signals, time, versioning) with no user-facing behavior changes—maintenance and consistency improvements only.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Apr 30, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro

Run ID: 77f7958f-3e06-4c87-a695-68606e7e020a

📥 Commits

Reviewing files that changed from the base of the PR and between 79c4439 and 615583d.

📒 Files selected for processing (2)
  • crates/stdlib/src/faulthandler.rs
  • crates/stdlib/src/openssl.rs
🚧 Files skipped from review as they are similar to previous changes (1)
  • crates/stdlib/src/openssl.rs

📝 Walkthrough

Walkthrough

This PR replaces many scattered #[cfg(...)] attribute blocks with unified cfg_select! macro expressions across the codebase, consolidating platform- and feature-gated type aliases and in-function branching without changing observable behavior.

Changes

Type alias consolidation with cfg_select!

Layer / File(s) Summary
Data Shape / Type aliases
crates/common/src/rc.rs, crates/common/src/str.rs, crates/host_env/src/crt_fd.rs, crates/vm/src/buffer.rs, crates/vm/src/codecs.rs, crates/vm/src/stdlib/_signal.rs, crates/vm/src/stdlib/_ctypes/simple.rs
Replace multiple #[cfg]-gated type/const definitions with single cfg_select! expressions for platform- or feature-dependent aliases (PyRc<T>, wchar_t, Offset, Raw, NativeEndian, UTF_*_NE, sighandler_t, SIMPLE_TYPE_CHARS).
Wiring / Usage
crates/vm/src/codecs.rs, crates/vm/src/buffer.rs, crates/vm/src/stdlib/_signal.rs
Updated code now refers to the unified aliases/constants; no semantic changes to consumers' logic.
Tests / Docs (implicit)
(none changed)
No public API signatures changed; behavior preserved at compile-time selection sites.

Conditional function/method logic refactoring

Layer / File(s) Summary
Platform/feature branching refactor
crates/common/src/refcount.rs, crates/stdlib/src/faulthandler.rs, crates/stdlib/src/openssl.rs, crates/stdlib/src/socket.rs, crates/stdlib/src/ssl.rs, crates/vm/src/exceptions.rs, crates/vm/src/getpath.rs, crates/vm/src/stdlib/_ctypes/function.rs, crates/vm/src/stdlib/_io.rs, crates/vm/src/stdlib/os.rs, crates/vm/src/stdlib/time.rs, crates/vm/src/version.rs
Replace #[cfg]-gated code paths inside functions/methods with cfg_select! expressions, consolidating platform/feature-specific control flow (signal-safe writes, OpenSSL version dispatch, endianness/encoding constants, path/stdlib selection, time conversion, error fields).
Behavioral preservation
various
All branches preserve former behavior per-target/version; selection mechanism is now macro-based rather than #[cfg] block splitting.
Tests / Validation (implicit)
(none changed)
No public signatures changed; tests not modified in this diff.

High-level runtime & VM conditionalization

Layer / File(s) Summary
VM/runtime initialization
crates/vm/src/vm/mod.rs, crates/vm/src/vm/vm_object.rs, src/interpreter.rs, src/lib.rs
Consolidate feature/platform conditional logic in VM init, exception panic handling, frozen vs dynamic stdlib setup, and run_file execution path to cfg_select!-based dispatches instead of separate #[cfg] branches.
Control flow
same files
Preserves original platform/feature behavior (main-thread checks, signal handling, wasm/no-wasm panic paths, host_env vs sandbox run_file).
Tests / Docs (implicit)
(none changed)
No API surface changes; runtime behaviors remain targeted per config.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related issues

Possibly related PRs

Suggested reviewers

  • ShaharNaveh
  • youknowone

Poem

🐰
I hopped through cfg blocks with delight,
Replaced the scattered guards with one bright light,
cfg_select! now picks the right way,
Clean compile-time choices — hip hip hooray! ✨

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title directly and accurately describes the main change: applying cfg_select macro in multiple places throughout the codebase instead of using #[cfg] conditional compilation blocks.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Tip

💬 Introducing Slack Agent: The best way for teams to turn conversations into code.

Slack Agent is built on CodeRabbit's deep understanding of your code, so your team can collaborate across the entire SDLC without losing context.

  • Generate code and open pull requests
  • Plan features and break down work
  • Investigate incidents and troubleshoot customer tickets together
  • Automate recurring tasks and respond to alerts with triggers
  • Summarize progress and report instantly

Built for teams:

  • Shared memory across your entire org—no repeating context
  • Per-thread sandboxes to safely plan and execute work
  • Governance built-in—scoped access, auditability, and budget controls

One agent for your entire SDLC. Right inside Slack.

👉 Get started


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
Review rate limit: 7/8 reviews remaining, refill in 7 minutes and 30 seconds.

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
crates/stdlib/src/faulthandler.rs (1)

151-167: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Fix decimal buffer slice offset in dump_decimal.

At Line 167, the function writes digits into the tail of buf, but emits a prefix slice. That can output leading \0 bytes and malformed decimal text in fault dumps.

Suggested fix
-        puts_bytes(fd, &buf[..buf.len() - i]);
+        puts_bytes(fd, &buf[i..]);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@crates/stdlib/src/faulthandler.rs` around lines 151 - 167, The dump_decimal
function writes digits right-aligned into buf and then slices the output
incorrectly: replace the problematic puts_bytes(fd, &buf[..buf.len() - i]) with
puts_bytes(fd, &buf[i..]) so that the emitted slice starts at index i (the first
digit) and does not include leading zero bytes; update the call site in
dump_decimal accordingly (referencing buf, i, and puts_bytes).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@crates/stdlib/src/openssl.rs`:
- Around line 1566-1569: The binding certs is only created under the ossl300 cfg
so code that references certs later will fail to compile on other targets;
update the cfg_select! expression that defines certs (the let certs =
cfg_select! { ... } using ctx.cert_store().all_certificates() and
ctx.cert_store().objects().iter().filter_map(|x| x.x509())) so it always
declares certs on all targets—either by providing a non-ossl300 arm that yields
an equivalent iterator/collection type (or an empty iterator) with matching item
type, or by moving the let certs = ... outside the conditional and having
cfg_select! return only the inner expression; keep references to
ctx.cert_store() and the existing iterator transformation
(objects().iter().filter_map(|x| x.x509())) when building the non-ossl300 arm.
- Around line 1310-1316: Change the cfg gate used where SSL_CTX_get_num_tickets
and SSL_CTX_set_num_tickets are referenced from ossl110 to ossl111: locate the
cfg_select! blocks that wrap the calls to sys::SSL_CTX_get_num_tickets and
sys::SSL_CTX_set_num_tickets (references around the methods using self.ctx() /
ctx.as_ptr()) and replace the ossl110 arm with ossl111 so the calls are only
enabled for OpenSSL 1.1.1 and later; keep the fallback arms (e.g., _ => Ok(0) or
identical behavior) unchanged.

---

Outside diff comments:
In `@crates/stdlib/src/faulthandler.rs`:
- Around line 151-167: The dump_decimal function writes digits right-aligned
into buf and then slices the output incorrectly: replace the problematic
puts_bytes(fd, &buf[..buf.len() - i]) with puts_bytes(fd, &buf[i..]) so that the
emitted slice starts at index i (the first digit) and does not include leading
zero bytes; update the call site in dump_decimal accordingly (referencing buf,
i, and puts_bytes).
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro

Run ID: 0048983b-d7bc-4286-afd7-a13984451f9a

📥 Commits

Reviewing files that changed from the base of the PR and between 6e895fb and 79c4439.

📒 Files selected for processing (23)
  • crates/common/src/rc.rs
  • crates/common/src/refcount.rs
  • crates/common/src/str.rs
  • crates/host_env/src/crt_fd.rs
  • crates/stdlib/src/faulthandler.rs
  • crates/stdlib/src/openssl.rs
  • crates/stdlib/src/socket.rs
  • crates/stdlib/src/ssl.rs
  • crates/vm/src/buffer.rs
  • crates/vm/src/codecs.rs
  • crates/vm/src/exceptions.rs
  • crates/vm/src/getpath.rs
  • crates/vm/src/stdlib/_ctypes/function.rs
  • crates/vm/src/stdlib/_ctypes/simple.rs
  • crates/vm/src/stdlib/_io.rs
  • crates/vm/src/stdlib/_signal.rs
  • crates/vm/src/stdlib/os.rs
  • crates/vm/src/stdlib/time.rs
  • crates/vm/src/version.rs
  • crates/vm/src/vm/mod.rs
  • crates/vm/src/vm/vm_object.rs
  • src/interpreter.rs
  • src/lib.rs

Comment on lines +1310 to +1316
cfg_select! {
ossl110 => {
let ctx = self.ctx();
let num = unsafe { sys::SSL_CTX_get_num_tickets(ctx.as_ptr()) };
Ok(num)
}
_ => Ok(0),
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🌐 Web query:

In OpenSSL, what minimum version introduced SSL_CTX_get_num_tickets and SSL_CTX_set_num_tickets?

💡 Result:

The minimum OpenSSL version that introduced both SSL_CTX_get_num_tickets and SSL_CTX_set_num_tickets is 1.1.1.

Citations:


🏁 Script executed:

# Check the actual code at the specified lines in openssl.rs
cd crates/stdlib/src && head -1350 openssl.rs | tail -100 | head -50

Repository: RustPython/RustPython

Length of output: 2008


🏁 Script executed:

# Find all usages of SSL_CTX_get_num_tickets and SSL_CTX_set_num_tickets
rg "SSL_CTX_(?:get|set)_num_tickets" crates/stdlib/src/

Repository: RustPython/RustPython

Length of output: 312


🏁 Script executed:

# Check for cfg_select macro definitions and gate patterns
rg "cfg_select|ossl110|ossl111" crates/stdlib/src/openssl.rs | head -40

Repository: RustPython/RustPython

Length of output: 1055


🏁 Script executed:

# Get exact lines around 1310-1316 and 1331-1342
sed -n '1305,1320p' crates/stdlib/src/openssl.rs
echo "---"
sed -n '1326,1345p' crates/stdlib/src/openssl.rs

Repository: RustPython/RustPython

Length of output: 1347


🏁 Script executed:

# Verify that ossl111 is used elsewhere for similar version-gated APIs to confirm the pattern
rg -A 3 'cfg_select.*ossl111 =>' crates/stdlib/src/openssl.rs | head -30

Repository: RustPython/RustPython

Length of output: 47


🏁 Script executed:

# Search for how ossl111 gate is used in cfg_select blocks
rg 'cfg_select!' crates/stdlib/src/openssl.rs -A 2 | grep -A 2 'ossl111'

Repository: RustPython/RustPython

Length of output: 154


Change version gates from ossl110 to ossl111 for SSL_CTX_get_num_tickets and SSL_CTX_set_num_tickets

SSL_CTX_get_num_tickets and SSL_CTX_set_num_tickets were introduced in OpenSSL 1.1.1, not 1.1.0. Using the ossl110 gate will cause build or link failures on OpenSSL 1.1.0 targets. Both occurrences must be updated to use ossl111.

Required fix
             cfg_select! {
-                ossl110 => {
+                ossl111 => {
                     let ctx = self.ctx();
                     let num = unsafe { sys::SSL_CTX_get_num_tickets(ctx.as_ptr()) };
                     Ok(num)
                 }
                 _ => Ok(0),
             }
             cfg_select! {
-                ossl110 => {
+                ossl111 => {
                     let ctx = self.builder();
                     let result = unsafe { sys::SSL_CTX_set_num_tickets(ctx.as_ptr(), value as usize) };
                     if result != 1 {
                         return Err(vm.new_value_error("failed to set num tickets."));
                     }
                     Ok(())
                 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
cfg_select! {
ossl110 => {
let ctx = self.ctx();
let num = unsafe { sys::SSL_CTX_get_num_tickets(ctx.as_ptr()) };
Ok(num)
}
_ => Ok(0),
cfg_select! {
ossl111 => {
let ctx = self.ctx();
let num = unsafe { sys::SSL_CTX_get_num_tickets(ctx.as_ptr()) };
Ok(num)
}
_ => Ok(0),
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@crates/stdlib/src/openssl.rs` around lines 1310 - 1316, Change the cfg gate
used where SSL_CTX_get_num_tickets and SSL_CTX_set_num_tickets are referenced
from ossl110 to ossl111: locate the cfg_select! blocks that wrap the calls to
sys::SSL_CTX_get_num_tickets and sys::SSL_CTX_set_num_tickets (references around
the methods using self.ctx() / ctx.as_ptr()) and replace the ossl110 arm with
ossl111 so the calls are only enabled for OpenSSL 1.1.1 and later; keep the
fallback arms (e.g., _ => Ok(0) or identical behavior) unchanged.

Comment thread crates/stdlib/src/openssl.rs
Copy link
Copy Markdown
Contributor

@ShaharNaveh ShaharNaveh left a comment

Choose a reason for hiding this comment

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

I really like this change

@coolreader18 coolreader18 enabled auto-merge (squash) May 4, 2026 19:48
@coolreader18 coolreader18 merged commit 0293238 into RustPython:main May 4, 2026
21 checks passed
@coderabbitai coderabbitai Bot mentioned this pull request May 12, 2026
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

Successfully merging this pull request may close these issues.

2 participants