Skip to content

Add docs for markdown tokenizer#163

Merged
leynos merged 7 commits intomainfrom
sm4qxh-codex/add-documentation-to-tokenize_markdown-function
Aug 3, 2025
Merged

Add docs for markdown tokenizer#163
leynos merged 7 commits intomainfrom
sm4qxh-codex/add-documentation-to-tokenize_markdown-function

Conversation

@leynos
Copy link
Copy Markdown
Owner

@leynos leynos commented Jul 31, 2025

Summary

  • expand documentation for tokenizer functions in wrap::tokenize
  • re-export tokenize_markdown from the wrap module

Testing

  • make fmt
  • make lint
  • make test

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

Summary by Sourcery

Add thorough documentation and examples for markdown tokenizer utilities and re-export tokenize_markdown from the wrap module

New Features:

  • Re-export tokenize_markdown from the wrap module

Documentation:

  • Add doc comments with usage examples for scan_while, collect_range, parse_link_or_image, is_trailing_punctuation, segment_inline, tokenize_inline, and tokenize_markdown

@sourcery-ai
Copy link
Copy Markdown
Contributor

sourcery-ai Bot commented Jul 31, 2025

Reviewer's Guide

This PR enriches the wrap::tokenize module by adding detailed Rustdoc comments with usage examples to its scanning and tokenization functions, updates the high-level tokenize_markdown documentation, and re-exports tokenize_markdown from the wrap module for external use.

File-Level Changes

Change Details Files
Added doc comments and examples for low-level scanning helpers
  • Document scan_while with usage example
  • Document collect_range with usage example
  • Document parse_link_or_image with nested-parentheses example
  • Document is_trailing_punctuation with example
src/wrap/tokenize.rs
Document inline segmentation and token emission functions
  • Add doc comment and example for segment_inline
  • Add doc comment and example for tokenize_inline
src/wrap/tokenize.rs
Expand documentation for tokenize_markdown behavior
  • Describe fenced mode, backtick scanning, and whitespace preservation in Rustdoc with example
src/wrap/tokenize.rs
Re-export tokenize_markdown
  • Add pub use tokenize::tokenize_markdown in wrap module
src/wrap.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 31, 2025

Warning

Rate limit exceeded

@leynos has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 11 minutes and 23 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 74be69c and 9b677fa.

📒 Files selected for processing (2)
  • src/wrap.rs (1 hunks)
  • src/wrap/tokenize.rs (5 hunks)

Summary by CodeRabbit

  • Documentation
    • Added detailed documentation and usage examples to various Markdown tokenisation functions and the Token enum, improving clarity for end-users and developers.
  • Refactor
    • Reformatted several internal functions for improved readability without altering their behaviour.
  • New Features
    • Made Markdown tokenisation functionality available for downstream use via a new public export.

Walkthrough

Expose the tokenize_markdown function from the internal tokenize module by publicly re-exporting it in src/wrap.rs. Add comprehensive documentation comments and illustrative examples to multiple functions and types within src/wrap/tokenize.rs, clarifying their usage and behaviour. No functional or logic changes are introduced.

Changes

Cohort / File(s) Change Summary
Public Re-export Addition
src/wrap.rs
Add public re-export: pub use tokenize::tokenize_markdown; with inline docs. Reformat some private methods and is_fence function without logic change.
Documentation Enhancements
src/wrap/tokenize.rs
Add detailed doc comments with usage examples to multiple functions and the Token enum. Update scan_while signature to accept FnMut. Remove outdated comment.
Code Formatting Refinements
src/html.rs
Reformat is_table_cell and contains_strong functions from single-line expressions to multi-line blocks without changing logic.

Estimated code review effort

🎯 1 (Trivial) | ⏱️ ~3 minutes

Possibly related PRs

  • Improve tokenization docs #115: Enhances documentation of the tokenize_markdown function and related logic in the same module, directly aligning with this PR's documentation focus.
  • Simplify token processing #161: Introduces and re-exports tokenize_markdown, refactoring token processing—strongly connected to this PR’s re-export and documentation updates.
  • Move wrap tests to module #152: Refactors by moving and re-exporting tokenize_markdown and Token, laying groundwork for the re-export performed in this PR.

Poem

Markdown tokens now step into the light,
With comments and examples, their purpose is bright.
No logic is shifted, no code rearranged,
Just clarity and access, the docs are exchanged.
So wrap up your code, let tokens parade—
In the land of the documented, confusion will fade!
✨📚

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch sm4qxh-codex/add-documentation-to-tokenize_markdown-function

🪧 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 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 found some issues that need to be addressed.

Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments

### Comment 1
<location> `src/wrap/tokenize.rs:120` </location>
<code_context>
+/// # Examples
+///
+/// ```rust,ignore
+/// let tokens = segment_inline("see [link](url) and `code`");
+/// assert_eq!(
+///     tokens,
</code_context>

<issue_to_address>
The example for `segment_inline` omits edge cases like consecutive spaces.

Add an example with consecutive or unusual whitespace to demonstrate the function's handling of these cases.
</issue_to_address>

<suggested_fix>
<<<<<<< SEARCH
///
/// ```rust,ignore
/// let tokens = segment_inline("see [link](url) and `code`");
/// assert_eq!(
///     tokens,
///     vec!["see", " ", "[link](url)", " ", "and", " ", "`code`"]
/// );
/// ```
=======
///
/// ```rust,ignore
/// let tokens = segment_inline("see [link](url) and `code`");
/// assert_eq!(
///     tokens,
///     vec!["see", " ", "[link](url)", " ", "and", " ", "`code`"]
/// );
///
/// // Example with consecutive and unusual whitespace
/// let tokens = segment_inline("foo  bar\tbaz   `qux`");
/// assert_eq!(
///     tokens,
///     vec!["foo", "  ", "bar", "\t", "baz", "   ", "`qux`"]
/// );
/// ```
>>>>>>> REPLACE

</suggested_fix>

### Comment 2
<location> `src/wrap/tokenize.rs:186` </location>
<code_context>
+/// # Examples
+///
+/// ```rust,ignore
+/// tokenize_inline("run `cmd`", &mut |t| println!("{:?}", t));
+/// ```
 fn tokenize_inline<'a, F>(text: &'a str, emit: &mut F)
</code_context>

<issue_to_address>
The example for `tokenize_inline` does not show the output format.

Consider including the expected output or a description of the callback's input to clarify the example.
</issue_to_address>

<suggested_fix>
<<<<<<< SEARCH
///
/// ```rust,ignore
/// tokenize_inline("run `cmd`", &mut |t| println!("{:?}", t));
/// ```
=======
///
/// ```rust
/// // Prints:
/// // Token::Text("run ")
/// // Token::Code("cmd")
/// tokenize_inline("run `cmd`", &mut |t| println!("{:?}", t));
/// ```
///
/// // The callback receives each token as a `Token<'a>`:
/// // For example, Token::Text(&str) or Token::Code(&str)
>>>>>>> REPLACE

</suggested_fix>

### Comment 3
<location> `src/wrap/tokenize.rs:225` </location>
<code_context>
+/// returned as [`Token::Text`]. Whitespace is preserved exactly as it appears.
+///
+/// ```rust,no_run
+/// use mdtablefix::wrap::{Token, tokenize_markdown};
+///
+/// let tokens = tokenize_markdown("Example with `code`");
</code_context>

<issue_to_address>
The example for `tokenize_markdown` uses `no_run` but appears runnable.

If the example should be tested, remove `no_run`. Otherwise, add a comment explaining why it shouldn't be run.
</issue_to_address>

<suggested_fix>
<<<<<<< SEARCH
///
/// ```rust,no_run
/// use mdtablefix::wrap::{Token, tokenize_markdown};
///
=======
///
/// ```rust
/// use mdtablefix::wrap::{Token, tokenize_markdown};
///
>>>>>>> REPLACE

</suggested_fix>

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.

Comment thread src/wrap/tokenize.rs
Comment thread src/wrap/tokenize.rs
Comment thread src/wrap/tokenize.rs
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: 4

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 3b33368 and 6327fd6.

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

📄 CodeRabbit Inference Engine (AGENTS.md)

**/*.rs: Clippy warnings MUST be disallowed.
Fix any warnings emitted during tests in the code itself rather than silencing them.
Where a function is too long, extract meaningfully named helper functions adhering to separation of concerns and CQRS.
Where a function has too many parameters, group related parameters in meaningfully named structs.
Where a function is returning a large error consider using Arc to reduce the amount of data returned.
Write unit and behavioural tests for new functionality. Run both before and after making any change.
Every module must begin with a module level (//!) comment explaining the module's purpose and utility.
Document public APIs using Rustdoc comments (///) so documentation can be generated with cargo doc.
Prefer immutable data and avoid unnecessary mut bindings.
Handle errors with the Result type instead of panicking where feasible.
Avoid unsafe code unless absolutely necessary and document any usage clearly.
Place function attributes after doc comments.
Do not use return in single-line functions.
Use predicate functions for conditional criteria with more than two branches.
Lints must not be silenced except as a last resort.
Lint rule suppressions must be tightly scoped and include a clear reason.
Prefer expect over allow.
Prefer .expect() over .unwrap().
Use concat!() to combine long string literals rather than escaping newlines with a backslash.
Prefer semantic error enums: Derive std::error::Error (via the thiserror crate) for any condition the caller might inspect, retry, or map to an HTTP status.
Use an opaque error only at the app boundary: Use eyre::Report for human-readable logs; these should not be exposed in public APIs.
Never export the opaque type from a library: Convert to domain enums at API boundaries, and to eyre only in the main main() entrypoint or top-level async task.

Files:

  • src/wrap.rs
  • src/wrap/tokenize.rs

⚙️ CodeRabbit Configuration File

**/*.rs: * Seek to keep the cyclomatic complexity of functions no more than 12.

  • Adhere to single responsibility and CQRS

  • Place function attributes after doc comments.

  • Do not use return in single-line functions.

  • Move conditionals with >2 branches into a predicate function.

  • Avoid unsafe unless absolutely necessary.

  • Every module must begin with a //! doc comment that explains the module's purpose and utility.

  • Comments and docs must follow en-GB-oxendict (-ize / -our) spelling and grammar

  • Lints must not be silenced except as a last resort.

    • #[allow] is forbidden.
    • Only narrowly scoped #[expect(lint, reason = "...")] is allowed.
    • No lint groups, no blanket or file-wide suppression.
    • Include FIXME: with link if a fix is expected.
  • Use rstest fixtures for shared setup and to avoid repetition between tests.

  • Replace duplicated tests with #[rstest(...)] parameterised cases.

  • Prefer mockall for mocks/stubs.

  • Prefer .expect() over .unwrap()

  • Ensure that any API or behavioural changes are reflected in the documentation in docs/

  • Ensure that any completed roadmap steps are recorded in the appropriate roadmap in docs/

  • Files must not exceed 400 lines in length

    • Large modules must be decomposed
    • Long match statements or dispatch tables should be decomposed by domain and collocated with targets
    • Large blocks of inline data (e.g., test fixtures, constants or templates) must be moved to external files and inlined at compile-time or loaded at run-time.

Files:

  • src/wrap.rs
  • src/wrap/tokenize.rs
🧬 Code Graph Analysis (1)
src/wrap.rs (1)
src/wrap/tokenize.rs (1)
  • tokenize_markdown (234-268)

Comment thread src/wrap.rs
Comment thread src/wrap/tokenize.rs
Comment thread src/wrap/tokenize.rs
Comment thread src/wrap/tokenize.rs
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 (3)
src/wrap/tokenize.rs (3)

112-133: Whitespace edge-case example landed – thanks
Matches the earlier review request exactly. Nothing further.


185-202: Inline-token API example now shows output – good
This resolves the previous feedback.


228-246: Crate-relative path used – portable docs achieved
The example will now compile for downstream crates regardless of rename.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 6327fd6 and 74be69c.

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

📄 CodeRabbit Inference Engine (AGENTS.md)

**/*.rs: Clippy warnings MUST be disallowed.
Fix any warnings emitted during tests in the code itself rather than silencing them.
Where a function is too long, extract meaningfully named helper functions adhering to separation of concerns and CQRS.
Where a function has too many parameters, group related parameters in meaningfully named structs.
Where a function is returning a large error consider using Arc to reduce the amount of data returned.
Write unit and behavioural tests for new functionality. Run both before and after making any change.
Every module must begin with a module level (//!) comment explaining the module's purpose and utility.
Document public APIs using Rustdoc comments (///) so documentation can be generated with cargo doc.
Prefer immutable data and avoid unnecessary mut bindings.
Handle errors with the Result type instead of panicking where feasible.
Avoid unsafe code unless absolutely necessary and document any usage clearly.
Place function attributes after doc comments.
Do not use return in single-line functions.
Use predicate functions for conditional criteria with more than two branches.
Lints must not be silenced except as a last resort.
Lint rule suppressions must be tightly scoped and include a clear reason.
Prefer expect over allow.
Prefer .expect() over .unwrap().
Use concat!() to combine long string literals rather than escaping newlines with a backslash.
Prefer semantic error enums: Derive std::error::Error (via the thiserror crate) for any condition the caller might inspect, retry, or map to an HTTP status.
Use an opaque error only at the app boundary: Use eyre::Report for human-readable logs; these should not be exposed in public APIs.
Never export the opaque type from a library: Convert to domain enums at API boundaries, and to eyre only in the main main() entrypoint or top-level async task.

Files:

  • src/html.rs
  • src/wrap.rs
  • src/wrap/tokenize.rs

⚙️ CodeRabbit Configuration File

**/*.rs: * Seek to keep the cyclomatic complexity of functions no more than 12.

  • Adhere to single responsibility and CQRS

  • Place function attributes after doc comments.

  • Do not use return in single-line functions.

  • Move conditionals with >2 branches into a predicate function.

  • Avoid unsafe unless absolutely necessary.

  • Every module must begin with a //! doc comment that explains the module's purpose and utility.

  • Comments and docs must follow en-GB-oxendict (-ize / -our) spelling and grammar

  • Lints must not be silenced except as a last resort.

    • #[allow] is forbidden.
    • Only narrowly scoped #[expect(lint, reason = "...")] is allowed.
    • No lint groups, no blanket or file-wide suppression.
    • Include FIXME: with link if a fix is expected.
  • Use rstest fixtures for shared setup and to avoid repetition between tests.

  • Replace duplicated tests with #[rstest(...)] parameterised cases.

  • Prefer mockall for mocks/stubs.

  • Prefer .expect() over .unwrap()

  • Ensure that any API or behavioural changes are reflected in the documentation in docs/

  • Ensure that any completed roadmap steps are recorded in the appropriate roadmap in docs/

  • Files must not exceed 400 lines in length

    • Large modules must be decomposed
    • Long match statements or dispatch tables should be decomposed by domain and collocated with targets
    • Large blocks of inline data (e.g., test fixtures, constants or templates) must be moved to external files and inlined at compile-time or loaded at run-time.

Files:

  • src/html.rs
  • src/wrap.rs
  • src/wrap/tokenize.rs
🔇 Additional comments (7)
src/html.rs (2)

117-124: Early-return branch reads better – good call

Moving the is_bold_tag test out of the guard clarifies the intent and avoids a long if let with a guard. No further action required.


86-90: Preserve single-expression form unless a statement block is needed

The new multi-line body is correct but adds two extra branches and indentation for no functional gain. Retain the original single expression for terseness and hot-path readability.

-fn is_table_cell(handle: &Handle) -> bool {
-    is_element(handle, "td") || is_element(handle, "th")
-}
+fn is_table_cell(handle: &Handle) -> bool {
+    is_element(handle, "td") || is_element(handle, "th")
+}

Likely an incorrect or invalid review comment.

src/wrap/tokenize.rs (4)

6-18: Accept FnMut for stateful predicates – 👍

Switching the predicate bound to FnMut unblocks closures that mutate captured state. The extra mut cond parameter is required and correct.
No issues detected.


28-36: Doc comment looks good

The example compiles and showcases the helper succinctly.


58-66: Example clarifies nested-parenthesis handling

The additional sample demonstrates the edge case the parser is built for. Nice.


93-109: '(' is unlikely to be “trailing” punctuation – verify intent

segment_inline only scans after the link/image token. An opening parenthesis cannot appear after ")" without whitespace (e.g. "[link](url)("), so this extension may silently consume a character that belongs to the next token.

-        '.' | ',' | ';' | ':' | '!' | '?' | '(' | ')' | ']' | '"' | '\''
+        '.' | ',' | ';' | ':' | '!' | '?' | ')' | ']' | '"' | '\''

Confirm that you have a concrete input where ( follows the link and should be glued; otherwise drop it to avoid mis-tokenisation.

src/wrap.rs (1)

201-204: doc(hidden) hides is_fence from public API – approved

This keeps the helper usable internally while keeping the surface tidy.

Comment thread src/wrap.rs Outdated
leynos and others added 4 commits August 3, 2025 19:23
Removes an unused PrefixHandler abstraction and its associated regex captures
import from the markdown wrapping logic. Simplifies the code while preserving
all functionality. Also improves code clarity in the strong tag detection by
using Rust's let-and pattern matching syntax.
@leynos leynos merged commit 9180664 into main Aug 3, 2025
2 checks passed
@leynos leynos deleted the sm4qxh-codex/add-documentation-to-tokenize_markdown-function branch August 3, 2025 19:09
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