fix(formatter): avoid usize underflow on over-wide comment prefixes - #10035
Conversation
format_leading_comment computed max_comment_width as `max_line_width - cur_indent - n_slashes - n_exclamations - n_leading_spaces` in usize. When the prefix exceeds max_line_width (a deeply-indented or long divider comment), this underflows: debug panics, release wraps. Use saturating_sub so the width floors at 0 and the comment is left unwrapped. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This stack of pull requests is managed by Graphite. Learn more about stacking. |
PR SummaryLow Risk Overview Adds a formatter test ( Reviewed by Cursor Bugbot for commit 81c4dd6. Bugbot is set up for automated code reviews on this repo. Configure here. |
eytan-starkware
left a comment
There was a problem hiding this comment.
@eytan-starkware reviewed 4 files and all commit messages, and made 1 comment.
Reviewable status:complete! all files reviewed, all discussions resolved (waiting on TomerStarkware).

Summary
Fixes an integer underflow (panic) in
format_leading_commentwhen computingmax_comment_width. The subtraction ofcur_indent,n_slashes,n_exclamations, andn_leading_spacesfrommax_line_widthis now done withsaturating_subto prevent wrapping/panicking when the prefix length exceedsmax_line_width.Type of change
Please check one:
Why is this change needed?
When a comment line has a prefix (indentation + slashes + exclamations + leading spaces) whose total length exceeds
max_line_width, the plain arithmetic subtraction would underflow in debug builds (panic) or wrap in release builds, producing an enormousmax_comment_widthvalue and incorrect formatting behavior. This is a real scenario with long section-divider comments made of many slashes.What was the behavior or documentation before?
A comment like:
would cause a panic (debug) or silent integer wrap (release) during formatting due to the underflow when computing the available comment width.
What is the behavior or documentation after?
max_comment_widthsaturates to0instead of underflowing, allowing the formatter to handle over-long comment prefixes gracefully. The comment is wrapped correctly:A new test case (
comment_overflow.cairo) is added to cover this scenario.Related issue or discussion (if any)
N/A
Additional context
The fix is minimal and surgical — only the four subtractions in
format_leading_commentare changed to usesaturating_sub.