Skip to content

Fix async attribute wrapping with punctuation#85

Merged
leynos merged 3 commits intomainfrom
codex/add-test-for-rstest-macro-punctuation
Jul 17, 2025
Merged

Fix async attribute wrapping with punctuation#85
leynos merged 3 commits intomainfrom
codex/add-test-for-rstest-macro-punctuation

Conversation

@leynos
Copy link
Copy Markdown
Owner

@leynos leynos commented Jul 17, 2025

Summary

  • ensure wrapping doesn't split closing punctuation from inline code
  • add regression test for #[awt] and #[future] wording

Testing

  • make fmt
  • make lint
  • make test
  • make markdownlint
  • make nixie

https://chatgpt.com/codex/tasks/task_e_68784f200da083228290b49a660bbeae

Summary by Sourcery

Improve markdown line wrapping logic to handle inline code and punctuation correctly, and add tests to prevent regressions with async attribute formatting.

Bug Fixes:

  • Fix line wrapping to prevent splitting closing punctuation from inline code in markdown.

Tests:

  • Add regression test to verify correct wrapping of async attribute syntax with punctuation.

@sourcery-ai
Copy link
Copy Markdown
Contributor

sourcery-ai Bot commented Jul 17, 2025

Reviewer's Guide

This pull request refines the text wrapping logic to ensure that closing punctuation is not separated from inline code spans, and adds a regression test to verify correct handling of async attribute syntax with punctuation.

Class diagram for test updates in wrap.rs

classDiagram
    class tests {
        +test_wrap_preserving_code() // updated expected output for punctuation handling
        +test_dangling_code_span() // updated expected output for inline code and punctuation
    }
Loading

File-Level Changes

Change Details Files
Improve line wrapping logic to prevent splitting closing punctuation from inline code spans.
  • Track last whitespace position to determine safe wrap points.
  • Adjust wrapping to avoid breaking after inline code followed by punctuation.
  • Update affected test cases to reflect new wrapping behavior.
src/wrap.rs
Add regression test to verify correct wrapping of async attribute syntax with punctuation.
  • Introduce new integration test for #[awt] and #[future] attribute wrapping.
  • Validate that punctuation is not split from inline code in output.
tests/integration.rs

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Jul 17, 2025

Summary by CodeRabbit

  • Bug Fixes

    • Improved line wrapping to ensure breaks occur at whitespace boundaries, preventing inline code spans and punctuation from being split across lines.
  • Tests

    • Added a new integration test to verify correct wrapping of bullet list items containing inline code spans and punctuation.
    • Updated existing test cases to reflect the refined wrapping behaviour.

Summary by CodeRabbit

  • Bug Fixes

    • Improved line wrapping to avoid breaking lines mid-word or within code spans, resulting in more natural and readable formatting.
  • Tests

    • Updated existing test cases to reflect improved wrapping behaviour.
    • Added a new integration test to verify correct wrapping of lines containing inline code spans and punctuation.

Walkthrough

Update the internal line-wrapping logic in wrap_preserving_code to prefer splitting lines at whitespace rather than mid-token, enhancing the preservation of inline code spans and punctuation. Adjust related test cases and add a new integration test to verify correct wrapping of attribute-like inline code spans within list items.

Changes

File(s) Change Summary
src/wrap.rs Refactor wrap_preserving_code to track last whitespace and split lines at whitespace boundaries, not mid-token. Updated two test cases to match new behaviour.
tests/integration.rs Add integration test test_wrap_future_attribute_punctuation for wrapping attribute-like inline code spans in lists.

Sequence Diagram(s)

sequenceDiagram
    participant Input
    participant wrap_preserving_code
    participant Output

    Input->>wrap_preserving_code: Provide tokens for a line
    loop For each token
        wrap_preserving_code->>wrap_preserving_code: Check if token fits in current line
        alt Token fits
            alt Token is whitespace
                wrap_preserving_code->>wrap_preserving_code: Update last_split position
            end
            wrap_preserving_code->>wrap_preserving_code: Append token to buffer
        else Token does not fit
            alt last_split exists
                wrap_preserving_code->>Output: Push line up to last_split
                wrap_preserving_code->>wrap_preserving_code: Start new buffer with remainder and current token
            else
                wrap_preserving_code->>Output: Push current buffer as line
                wrap_preserving_code->>wrap_preserving_code: Start new buffer with current token
            end
        end
    end
    wrap_preserving_code->>Output: Push any remaining buffer as line
Loading

Possibly related issues

Possibly related PRs

Poem

Wrapping lines with gentle care,
No more words split in mid-air.
Code spans safe, with space in tow,
Attributes wrapped in tidy flow.
Whitespace leads the way anew—
A neat display, both clear and true!
📝✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e2b7a65 and 3f51163.

📒 Files selected for processing (1)
  • src/wrap.rs (3 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.rs

Instructions used from:

Sources:
📄 CodeRabbit Inference Engine

  • AGENTS.md

⚙️ CodeRabbit Configuration File

🔇 Additional comments (2)
src/wrap.rs (2)

374-375: Test update correctly reflects improved wrapping logic.

The updated assertion properly demonstrates that the code span powershell -Command now moves entirely to the next line rather than being split mid-token, which is the intended behaviour improvement.


412-412: Test update correctly reflects improved wrapping logic.

The updated assertion properly demonstrates that the unmatched backtick sequence now moves entirely to the next line rather than being split, which aligns with the whitespace-aware wrapping enhancement.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch codex/add-test-for-rstest-macro-punctuation

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai auto-generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Copy Markdown
Contributor

@sourcery-ai sourcery-ai Bot left a comment

Choose a reason for hiding this comment

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

Hey @leynos - I've reviewed your changes and they look great!


Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

@leynos
Copy link
Copy Markdown
Owner Author

leynos commented Jul 17, 2025

@coderabbitai review

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Jul 17, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

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: 1

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 171aae2 and 2893960.

📒 Files selected for processing (2)
  • src/wrap.rs (3 hunks)
  • tests/integration.rs (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.rs

Instructions used from:

Sources:
⚙️ CodeRabbit Configuration File

🧬 Code Graph Analysis (1)
tests/integration.rs (1)
src/process.rs (1)
  • process_stream (76-76)
🔇 Additional comments (3)
src/wrap.rs (2)

357-358: LGTM - test correctly validates improved code span preservation.

The updated expected output properly reflects the new whitespace-aware wrapping behavior, ensuring inline code spans remain intact across line breaks.


395-395: LGTM - test correctly handles unmatched backtick preservation.

The updated assertion properly validates that unmatched backticks and following text move together to the next line, maintaining the integrity of code-like tokens.

tests/integration.rs (1)

739-759: LGTM - comprehensive integration test for the async attribute wrapping fix.

This test effectively validates the core fix described in the PR objectives. It ensures that Rust attribute syntax in inline code spans (#[awt], #[future(awt)]) and their associated punctuation are preserved together during line wrapping, preventing the formatting issues that prompted this fix.

Comment thread src/wrap.rs
Comment on lines +79 to 112
let mut last_split: Option<usize> = None;
for token in tokenize_markdown(text) {
let token_width = UnicodeWidthStr::width(token.as_str());
if current_width + token_width <= width {
current.push_str(&token);
current_width += token_width;
if token.chars().all(char::is_whitespace) {
last_split = Some(current.len());
}
continue;
}

if let Some(pos) = last_split {
let line = current[..pos].to_string();
let mut rest = current[pos..].trim_start().to_string();
let trimmed = line.trim_end();
if !trimmed.is_empty() {
lines.push(trimmed.to_string());
}
rest.push_str(&token);
current = rest;
current_width = UnicodeWidthStr::width(current.as_str());
last_split = if token.chars().all(char::is_whitespace) {
Some(current.len())
} else {
None
};
if current_width > width {
lines.push(current.trim_end().to_string());
current.clear();
current_width = 0;
last_split = None;
}
continue;
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.

🧹 Nitpick (assertive)

Refactor the complex branching logic to improve readability.

The whitespace-aware wrapping implementation is correct, but the nested conditions and multiple control flow paths increase cyclomatic complexity. Extract the line-breaking logic into a separate predicate function to align with the coding guidelines.

+fn attempt_whitespace_break(
+    current: &mut String,
+    current_width: &mut usize,
+    last_split: &mut Option<usize>,
+    token: &str,
+    width: usize,
+    lines: &mut Vec<String>,
+) -> bool {
+    if let Some(pos) = *last_split {
+        let line = current[..pos].to_string();
+        let mut rest = current[pos..].trim_start().to_string();
+        let trimmed = line.trim_end();
+        if !trimmed.is_empty() {
+            lines.push(trimmed.to_string());
+        }
+        rest.push_str(token);
+        *current = rest;
+        *current_width = UnicodeWidthStr::width(current.as_str());
+        *last_split = if token.chars().all(char::is_whitespace) {
+            Some(current.len())
+        } else {
+            None
+        };
+        if *current_width > width {
+            lines.push(current.trim_end().to_string());
+            current.clear();
+            *current_width = 0;
+            *last_split = None;
+        }
+        true
+    } else {
+        false
+    }
+}

Then simplify the main logic:

         if current_width + token_width <= width {
             current.push_str(&token);
             current_width += token_width;
             if token.chars().all(char::is_whitespace) {
                 last_split = Some(current.len());
             }
             continue;
         }

-        if let Some(pos) = last_split {
-            let line = current[..pos].to_string();
-            let mut rest = current[pos..].trim_start().to_string();
-            let trimmed = line.trim_end();
-            if !trimmed.is_empty() {
-                lines.push(trimmed.to_string());
-            }
-            rest.push_str(&token);
-            current = rest;
-            current_width = UnicodeWidthStr::width(current.as_str());
-            last_split = if token.chars().all(char::is_whitespace) {
-                Some(current.len())
-            } else {
-                None
-            };
-            if current_width > width {
-                lines.push(current.trim_end().to_string());
-                current.clear();
-                current_width = 0;
-                last_split = None;
-            }
+        if attempt_whitespace_break(&mut current, &mut current_width, &mut last_split, &token, width, &mut lines) {
             continue;
         }
🤖 Prompt for AI Agents
In src/wrap.rs between lines 79 and 112, the current whitespace-aware wrapping
logic has complex nested conditions that reduce readability. Refactor by
extracting the line-breaking decision logic into a separate predicate function
that determines when to break lines based on width and whitespace. Then simplify
the main loop to call this function, reducing cyclomatic complexity and
improving clarity while preserving the existing behavior.

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: 1

♻️ Duplicate comments (1)
src/wrap.rs (1)

95-129: Approve the whitespace-aware wrapping implementation.

The implementation correctly addresses the PR objective by preferring to split lines at whitespace boundaries rather than mid-token. The logic properly tracks the last whitespace position and attempts to break there when a token would exceed the width limit.

Note: The previous review comment about refactoring complex branching logic has been addressed by introducing the should_break_line helper function, which reduces the cyclomatic complexity of the main logic.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2893960 and e2b7a65.

📒 Files selected for processing (1)
  • src/wrap.rs (3 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.rs

Instructions used from:

Sources:
📄 CodeRabbit Inference Engine

  • AGENTS.md

⚙️ CodeRabbit Configuration File

🪛 GitHub Actions: CI
src/wrap.rs

[error] 80-85: Rust doctest failed: function should_break_line is private and cannot be accessed in the test. Error E0603 at src/wrap.rs:82:23.

🔇 Additional comments (2)
src/wrap.rs (2)

374-375: Verify the test case update reflects the new wrapping behaviour.

The test case has been updated to show that `powershell -Command` now moves entirely to the next line rather than being split mid-token. This change aligns with the improved whitespace-aware wrapping logic.


412-412: Verify the unmatched backticks test reflects the new wrapping behaviour.

The test case has been updated to show that `dangling now moves entirely to the next line with the following text, rather than splitting awkwardly. This demonstrates the improved preservation of inline code spans.

Comment thread src/wrap.rs
Comment on lines +73 to +87
/// Determine if the current line should break at the last whitespace.
///
/// Returns `true` if `current_width` exceeds `width` and a whitespace split
/// position is available.
///
/// # Examples
///
/// ```
/// use mdtablefix::wrap::should_break_line;
/// assert!(should_break_line(10, 12, Some(3)));
/// assert!(!should_break_line(10, 8, Some(3)));
/// ```
fn should_break_line(width: usize, current_width: usize, last_split: Option<usize>) -> bool {
current_width > width && last_split.is_some()
}
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

Fix the doctest visibility issue and remove the example.

The pipeline failure indicates that should_break_line is private and cannot be accessed in the doctest. Additionally, providing a doctest example for an internal helper function violates the principle of documenting only public APIs as specified in the coding guidelines.

Apply this diff to fix the issue:

-/// Determine if the current line should break at the last whitespace.
-///
-/// Returns `true` if `current_width` exceeds `width` and a whitespace split
-/// position is available.
-///
-/// # Examples
-///
-/// ```
-/// use mdtablefix::wrap::should_break_line;
-/// assert!(should_break_line(10, 12, Some(3)));
-/// assert!(!should_break_line(10, 8, Some(3)));
-/// ```
+/// Determine if the current line should break at the last whitespace.
+///
+/// Returns `true` if `current_width` exceeds `width` and a whitespace split
+/// position is available.
 fn should_break_line(width: usize, current_width: usize, last_split: Option<usize>) -> bool {
     current_width > width && last_split.is_some()
 }
📝 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
/// Determine if the current line should break at the last whitespace.
///
/// Returns `true` if `current_width` exceeds `width` and a whitespace split
/// position is available.
///
/// # Examples
///
/// ```
/// use mdtablefix::wrap::should_break_line;
/// assert!(should_break_line(10, 12, Some(3)));
/// assert!(!should_break_line(10, 8, Some(3)));
/// ```
fn should_break_line(width: usize, current_width: usize, last_split: Option<usize>) -> bool {
current_width > width && last_split.is_some()
}
/// Determine if the current line should break at the last whitespace.
///
/// Returns `true` if `current_width` exceeds `width` and a whitespace split
/// position is available.
fn should_break_line(width: usize, current_width: usize, last_split: Option<usize>) -> bool {
current_width > width && last_split.is_some()
}
🧰 Tools
🪛 GitHub Actions: CI

[error] 80-85: Rust doctest failed: function should_break_line is private and cannot be accessed in the test. Error E0603 at src/wrap.rs:82:23.

🤖 Prompt for AI Agents
In src/wrap.rs around lines 73 to 87, the doctest for the private function
should_break_line causes pipeline failure because the function is not accessible
in tests and internal helpers should not have public examples. Remove the
doctest code block entirely, including the use statement and assert examples,
leaving only the function documentation comments describing its behavior.

@leynos leynos merged commit 5ef7384 into main Jul 17, 2025
2 checks passed
@leynos leynos deleted the codex/add-test-for-rstest-macro-punctuation branch July 17, 2025 10:36
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant