rustfmt icon indicating copy to clipboard operation
rustfmt copied to clipboard

fix: prevent panic when formatting complex generics

Open avrabe opened this issue 4 months ago • 2 comments

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.

avrabe avatar Aug 10 '25 05:08 avrabe

Hi, I just came across your PR. Would it be alright if I try it out to see if https://github.com/rust-lang/rustfmt/pull/6396 fixes the unwrap error in that test case? (This seems orthogonal to the mentioned PR though, so just to verify whether the issue is duplicate or not)

ding-young avatar Aug 31 '25 15:08 ding-young

@ding-young Sure, would be good to see. https://github.com/pulseengine/wrt is where my problem originate from. My patch makes this repository format again. Otherwise it actually stripped away code.

avrabe avatar Sep 01 '25 05:09 avrabe