Skip to content

Add more error functions to the c-api#8248

Open
bschoenmaeckers wants to merge 11 commits into
RustPython:mainfrom
bschoenmaeckers:c-api-more-error
Open

Add more error functions to the c-api#8248
bschoenmaeckers wants to merge 11 commits into
RustPython:mainfrom
bschoenmaeckers:c-api-more-error

Conversation

@bschoenmaeckers

@bschoenmaeckers bschoenmaeckers commented Jul 10, 2026

Copy link
Copy Markdown
Contributor

Summary by CodeRabbit

  • New Features
    • Expanded C API support for Python exception lifecycle control, including traceback handling plus clear/match and fetch/restore and exc-info/pending exception helpers.
    • Added OS-error helpers for raising Python exceptions, including errno-based and Windows-specific variants with optional filename support.
    • Added C-ABI functions for creating Unicode decode/encode/translate error objects and getting/setting their attributes.
  • Bug Fixes
    • Improved native/FFI error propagation for functions that don’t return a value.
    • Adjusted PyUnicodeDecodeError.__str__ byte hex formatting.

@bschoenmaeckers bschoenmaeckers changed the title C api more error Add more error functions to the c-api Jul 10, 2026
@coderabbitai

coderabbitai Bot commented Jul 10, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

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: 210d835e-e494-43fe-9132-b6e438d2ad9b

📥 Commits

Reviewing files that changed from the base of the PR and between 6d1ac15 and 8be67af.

📒 Files selected for processing (8)
  • crates/host_env/src/fileutils.rs
  • crates/host_env/src/posix.rs
  • crates/stdlib/src/binascii.rs
  • crates/stdlib/src/pyexpat.rs
  • crates/stdlib/src/ssl.rs
  • crates/vm/src/exceptions.rs
  • crates/vm/src/stdlib/_io.rs
  • crates/vm/src/stdlib/_signal.rs
🚧 Files skipped from review as they are similar to previous changes (1)
  • crates/vm/src/stdlib/_io.rs

📝 Walkthrough

Walkthrough

The C-API exception layer adds VM-backed exception state operations, errno and Windows error conversion helpers, Unicode error accessors, pointer-returning FFI error handling, and independent Rust syntax, formatting, and lint cleanup.

Changes

Exception and error C-API

Layer / File(s) Summary
Exception state and FFI error plumbing
crates/capi/src/pyerrors.rs, crates/capi/src/util.rs
Adds traceback, pending-exception, interrupt, fatal-error, exception-triple, handled-exception, exc_info, and exception-args APIs, plus public helper re-exports and pointer-returning error conversion.
Errno exception construction
crates/capi/src/pyerrors/errno.rs
Adds errno-based exception constructors supporting C-string and Python filename arguments, EINTR signal checks, and exception-instance validation.
Unicode error accessors
crates/capi/src/pyerrors/unicode.rs
Adds Unicode decode-error construction and attribute getters/setters for decode, encode, and translate errors, including bounds and UTF-8 validation.
Windows error construction
crates/capi/src/pyerrors/windows.rs
Adds Windows error conversion helpers for targeted exception types and OSError, with optional filename arguments and last-error lookup.

Rust cleanup

Layer / File(s) Summary
Compiler and symbol-table pattern cleanup
crates/codegen/src/compile.rs, crates/codegen/src/symboltable.rs
Simplifies AST destructuring while preserving symbol lookup, scanning, scope, and validation behavior.
Runtime formatting and propagation cleanup
crates/derive-impl/src/util.rs, crates/vm/**, src/lib.rs
Removes redundant formatting borrows, simplifies AST argument destructuring, and replaces one explicit error match with ? without described behavior changes.
Clippy lint expectations
crates/host_env/**, crates/stdlib/**, crates/vm/src/stdlib/**
Adds scoped lint expectations for documented std-versus-core false positives.

Estimated code review effort: 4 (Complex) | ~75 minutes

Sequence Diagram(s)

sequenceDiagram
  participant C_API
  participant VM
  participant OS_Error
  participant Exception_Type
  C_API->>VM: invoke exception or OS-error helper
  VM->>OS_Error: read errno or Windows last-error data
  OS_Error-->>VM: return error code and message
  VM->>Exception_Type: construct exception with optional filenames
  Exception_Type-->>C_API: return exception object
Loading

Possibly related PRs

Suggested reviewers: youknowone, ShaharNaveh

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 77.27% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main change: adding additional error-handling functions to the C-API.
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.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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

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

@coderabbitai coderabbitai Bot left a comment

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.

Actionable comments posted: 1

🧹 Nitpick comments (1)
crates/capi/src/pyerrors/errno.rs (1)

18-56: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Reduce duplication by delegating to the object-based helper.

PyErr_SetFromErrnoWithFilename re-implements the errno read, EINTR handling, message construction, downcast, and call logic that already exists in PyErr_SetFromErrnoWithFilenameObjects. As in CPython, this can decode the filename and then delegate to PyErr_SetFromErrnoWithFilenameObject, keeping the errno/message logic in one place.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@crates/capi/src/pyerrors/errno.rs` around lines 18 - 56, Refactor
PyErr_SetFromErrnoWithFilename to only decode the optional C filename, convert
it to a Python object, and delegate to PyErr_SetFromErrnoWithFilenameObject.
Remove its duplicated errno retrieval, EINTR handling, message construction,
exception downcast, and call logic so the object-based helper remains the single
implementation.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@crates/capi/src/pyerrors/windows.rs`:
- Around line 69-84: In the Windows error conversion branch, avoid leaking the
decoded filename created by decode_fsdefault_and_size. Update the
Some(Ok(filename)) handling to keep the PyObjectRef alive locally and pass its
borrowed raw pointer to set_windows_error, rather than calling into_raw();
preserve the existing error and None handling.

---

Nitpick comments:
In `@crates/capi/src/pyerrors/errno.rs`:
- Around line 18-56: Refactor PyErr_SetFromErrnoWithFilename to only decode the
optional C filename, convert it to a Python object, and delegate to
PyErr_SetFromErrnoWithFilenameObject. Remove its duplicated errno retrieval,
EINTR handling, message construction, exception downcast, and call logic so the
object-based helper remains the single implementation.
🪄 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: 05c2152b-5010-4ab6-a5ca-c0afe9842760

📥 Commits

Reviewing files that changed from the base of the PR and between 9c064c1 and bebdf8e.

📒 Files selected for processing (5)
  • crates/capi/src/pyerrors.rs
  • crates/capi/src/pyerrors/errno.rs
  • crates/capi/src/pyerrors/unicode.rs
  • crates/capi/src/pyerrors/windows.rs
  • crates/capi/src/util.rs

Comment thread crates/capi/src/pyerrors/windows.rs
bschoenmaeckers and others added 6 commits July 10, 2026 17:47
- exceptions.rs: {b:#02x} -> {b:#04x} (unused_format_specs); output
  unchanged for decode-error bytes (always >= 0x80)
- binascii.rs: [b'\r', b'\n'] -> b"\r\n" (byte_str_slice)
- host_env, _io.rs, ssl.rs, pyexpat.rs: expect std_instead_of_core where
  the suggested core::io items (ErrorKind, Cursor) are unstable (core_io);
  use expect so the suppression is flagged for removal once core::io
  stabilizes. build_posix_spawn_attrs co-gates the expect with the cfg
  block so it is not left unfulfilled on platforms compiling it out.

Assisted-by: Claude
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