Skip to content

fix: prevent panic when formatting complex generics #6630

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

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

avrabe
Copy link

@avrabe avrabe commented Aug 10, 2025

Fixes #6571

Problem

rustfmt panics with Option::unwrap() on a None value when formatting enums with very long generic type constraints. This occurs when the generic constraints exceed the available width budget (~80-100 characters), causing rewrite_generics to fail and format_generics to return None, which is then unwrapped.

Solution

This PR implements a three-tier fallback strategy in format_generics:

  1. First attempt: Try formatting with normal width constraint
  2. Second attempt: If that fails, retry with infinite width using shape.infinite_width()
  3. Fallback: If even that fails, preserve the original source formatting

Changes

  • Modified format_generics function in src/items.rs to handle width budget exhaustion gracefully
  • Added regression test case issue-6571.rs to prevent future regressions

Testing

  • All existing tests pass
  • New regression test verifies the fix works for complex generic constraints
  • Tested on the original failing codebase that triggered the issue

This fix ensures rustfmt can process files with complex generic constraints without crashing, while maintaining proper formatting where possible.

Handle cases where rewrite_generics fails due to long generic constraints
by implementing a fallback to infinite width and preserving original
formatting when necessary.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

rustfmt panic: Option::unwrap() on None value in items.rs:562
2 participants