Skip to content

Add runtime span ordering checks#46

Merged
leynos merged 3 commits intomainfrom
codex/improve-span-ordering-validation-in-build_green_tree
Jul 4, 2025
Merged

Add runtime span ordering checks#46
leynos merged 3 commits intomainfrom
codex/improve-span-ordering-validation-in-build_green_tree

Conversation

@leynos
Copy link
Copy Markdown
Owner

@leynos leynos commented Jul 4, 2025

Summary

  • enforce span list ordering in build_green_tree
  • update parser plan docs with span ordering note
  • test panic behaviour for overlapping or unsorted spans

Testing

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

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

Summary by Sourcery

Add comprehensive runtime span ordering checks to parser tree construction, with detailed error reporting and updated documentation.

New Features:

  • Enforce runtime validation of sorted and non-overlapping span lists in build_green_tree

Enhancements:

  • Introduce SpanOrderError and ensure_span_lists_sorted to aggregate and report span ordering violations

Documentation:

  • Add span ordering requirement and panic behavior note to parser-plan documentation

Tests:

  • Add unit tests for validate_spans_sorted and build_green_tree panic behavior on misordered spans

Assert span lists at runtime and document ordering requirement.
@sourcery-ai
Copy link
Copy Markdown
Contributor

sourcery-ai Bot commented Jul 4, 2025

Reviewer's Guide

This PR replaces debug‐only span assertions with runtime validation that aggregates and panics on unsorted or overlapping spans, introduces a dedicated error type for diagnostics, updates the parser plan docs to note the new requirements, and adds comprehensive tests for these checks.

Entity relationship diagram for span validation functions and error reporting

erDiagram
    SPAN {
        int start
        int end
    }
    SPAN_ORDER_ERROR {
        Span prev
        Span next
    }
    VALIDATE_SPANS_SORTED ||--o{ SPAN : checks
    ENSURE_SPAN_LISTS_SORTED ||--o{ SPAN : checks
    VALIDATE_SPANS_SORTED }o--|| SPAN_ORDER_ERROR : returns
    ENSURE_SPAN_LISTS_SORTED }o--|| SPAN_ORDER_ERROR : aggregates
Loading

Class diagram for updated build_green_tree span validation

classDiagram
    class parser {
        +build_green_tree(tokens, src, imports, typedefs, relations, indexes, functions, rules) GreenNode
    }
    parser ..> ensure_span_lists_sorted : calls
    parser ..> validate_spans_sorted : calls
    parser ..> SpanOrderError : uses
Loading

File-Level Changes

Change Details Files
Replace debug assertions in build_green_tree with runtime span ordering validation
  • Introduce validate_spans_sorted returning Result
  • Add ensure_span_lists_sorted to collect named lists and assert aggregated errors
  • Replace multiple assert_spans_sorted calls with a single ensure_span_lists_sorted invocation
  • Pass span list names for improved error reporting
src/parser/mod.rs
Introduce SpanOrderError for clearer span ordering diagnostics
  • Define SpanOrderError struct capturing the offending span pair
  • Implement Display trait to format descriptive error messages
  • Implement Error trait for SpanOrderError
  • Use SpanOrderError in validate_spans_sorted
src/parser/mod.rs
Update parser-plan.md to document span ordering requirements
  • Add note under build_green_tree section that span lists must be sorted and non-overlapping
  • Describe panic behavior with aggregated error messages
docs/parser-plan.md
Add unit tests covering span validation and build_green_tree panics
  • Test validate_spans_sorted on overlapping, unsorted, empty, single, and sorted spans
  • Test build_green_tree panics include specific span list names and ranges
  • Test aggregated error reporting when multiple lists are misordered
src/parser/mod.rs

Possibly linked issues

  • Implement typedef and extern type parser #16: The PR fixes the issue by converting debug assertions for span ordering to runtime checks with panics and adding tests.
  • #0: PR adds runtime validation (panics), documentation, and tests for span ordering to prevent CST misalignment.

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 4, 2025

Summary by CodeRabbit

  • Documentation

    • Clarified requirements for span ordering and overlap in the parser plan documentation, including details on error handling.
  • Bug Fixes

    • Improved validation of span lists to ensure they are sorted and non-overlapping, with more descriptive error messages for issues.
  • Tests

    • Added new unit tests to verify correct detection of span ordering issues and appropriate error reporting.

Summary by CodeRabbit

  • Documentation

    • Clarified that lists of statement spans must be sorted and non-overlapping when building the syntax tree, and described the error behaviour if this condition is not met.
  • Bug Fixes

    • Improved runtime validation for span order and overlap, providing detailed error messages when issues are detected.
  • Tests

    • Added unit tests to ensure correct error handling for overlapping or unsorted spans.

Walkthrough

The documentation for the parser plan and the build_green_tree function was updated to clarify strict requirements for span ordering and non-overlap, specifying that violations will cause a runtime panic. The assert_spans_sorted function was renamed and refactored into validate_spans_sorted returning detailed errors, and a new centralized validation function aggregates errors and panics if any are found. New unit tests verify correct panic behaviour on errors.

Changes

File(s) Change Summary
docs/parser-plan.md Clarified documentation on build_green_tree preconditions and error behaviour regarding spans.
src/parser/mod.rs Refactored assert_spans_sorted to validate_spans_sorted returning Result; added SpanOrderError struct with Display and Error implementations; added ensure_span_lists_sorted to check multiple span lists and panic with aggregated errors; updated build_green_tree to use new validation; added multiple unit tests for span validation.

Sequence Diagram(s)

sequenceDiagram
    participant Caller
    participant build_green_tree
    participant ensure_span_lists_sorted
    participant validate_spans_sorted

    Caller->>build_green_tree: call with statement spans
    build_green_tree->>ensure_span_lists_sorted: check all span lists
    ensure_span_lists_sorted->>validate_spans_sorted: validate each span list
    alt All spans valid
        validate_spans_sorted-->>ensure_span_lists_sorted: success
        ensure_span_lists_sorted-->>build_green_tree: success
        build_green_tree-->>Caller: proceed with CST construction
    else Some spans invalid (overlap/unsorted)
        validate_spans_sorted-->>ensure_span_lists_sorted: error details
        ensure_span_lists_sorted-->>Caller: panic with aggregated error messages
    end
Loading

Possibly related issues

Poem

A rabbit checks the spans with care,
No overlaps or chaos to bear.
If order slips or bounds entwine,
The builder panics—by design!
Now tests ensure all rules are met,
The syntax tree’s as safe as yet.
🐇🌳

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 Clippy (1.86.0)
Updating crates.io index

warning: failed to write cache, path: /usr/local/registry/index/index.crates.io-1949cf8c6b5b557f/.cache/ch/um/chumsky, error: Permission denied (os error 13)
Locking 60 packages to latest Rust 1.86.0 compatible versions
Adding chumsky v0.9.3 (available: v0.10.1)
Adding logos v0.13.0 (available: v0.15.0)
Adding phf v0.11.3 (available: v0.12.1)
Adding rowan v0.15.16 (available: v0.16.1)
Downloading crates ...
Downloaded fnv v1.0.7
error: failed to create directory /usr/local/registry/cache/index.crates.io-1949cf8c6b5b557f

Caused by:
Permission denied (os error 13)


📜 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 1954cdd and af4d5fb.

📒 Files selected for processing (2)
  • docs/parser-plan.md (1 hunks)
  • src/parser/mod.rs (4 hunks)
🧰 Additional context used
📓 Path-based instructions (5)
`docs/**/*.md`: Documentation must use en-GB-oxendict spelling and grammar (with the exception of 'license' which is to be left unchanged for community consistency).

docs/**/*.md: Documentation must use en-GB-oxendict spelling and grammar (with the exception of 'license' which is to be left unchanged for community consistency).

📄 Source: CodeRabbit Inference Engine (AGENTS.md)

List of files the instruction was applied to:

  • docs/parser-plan.md
`**/*.md`: Markdown paragraphs and bullet points must be wrapped at 80 columns. Code blocks must be wrapped at 120 columns. Tables and headings must not be wrapped.

**/*.md: Markdown paragraphs and bullet points must be wrapped at 80 columns.
Code blocks must be wrapped at 120 columns.
Tables and headings must not be wrapped.

📄 Source: CodeRabbit Inference Engine (AGENTS.md)

List of files the instruction was applied to:

  • docs/parser-plan.md
`**/*.md`: * Avoid 2nd person or 1st person pronouns ("I", "you", "we") * Use en...

**/*.md: * Avoid 2nd person or 1st person pronouns ("I", "you", "we")

  • Use en-oxendic spelling and grammar.
  • Paragraphs and bullets must be wrapped to 80 columns, except where a long URL would prevent this (in which case, silence MD013 for that line)
  • Code blocks should be wrapped to 120 columns.
  • Headings must not be wrapped.

⚙️ Source: CodeRabbit Configuration File

List of files the instruction was applied to:

  • docs/parser-plan.md
`**/*.rs`: Comment why, not what. Explain assumptions, edge cases, trade-offs, o...

**/*.rs: Comment why, not what. Explain assumptions, edge cases, trade-offs, or complexity. Don't echo the obvious.
Comments must use en-GB-oxendict spelling and grammar.
Function documentation must include clear examples.
Name things precisely. Use clear, descriptive variable and function names. For booleans, prefer names with is, has, or should.
Each file should encapsulate a coherent module. Group related code (e.g., models + utilities + fixtures) close together.
Group by feature, not layer. Colocate views, logic, fixtures, and helpers related to a domain concept rather than splitting by type.
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.
Place function attributes after doc comments.
Do not use return in single-line functions.
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.
Clippy warnings MUST be disallowed.
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.
Use predicate functions for conditional criteria with more than two branches.
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.
Prefer .expect() over .unwrap().

📄 Source: CodeRabbit Inference Engine (AGENTS.md)

List of files the instruction was applied to:

  • src/parser/mod.rs
`**/*.rs`: * Seek to keep the cyclomatic complexity of functions no more than 12...

**/*.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 must use en-GB-oxendict 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/

⚙️ Source: CodeRabbit Configuration File

List of files the instruction was applied to:

  • src/parser/mod.rs
🔇 Additional comments (6)
src/parser/mod.rs (5)

839-842: LGTM! Clear documentation of span ordering requirements.

The documentation clearly states the requirements and behaviour, aligning perfectly with the runtime validation implementation.


857-864: Excellent centralised validation approach.

Replacing individual debug assertions with a single aggregated check improves maintainability and provides more comprehensive error reporting.


966-1000: Well-designed error type with proper trait implementations.

The SpanOrderError struct provides clear diagnostic information and correctly implements both Display and Error traits. The validation logic properly detects overlapping spans using first.end > second.start.


1002-1011: Robust error aggregation with descriptive panic messages.

The function correctly collects all validation errors before panicking, providing comprehensive diagnostics. The naming and error formatting follow good practices.


1861-1936: Comprehensive test coverage for all validation scenarios.

The tests cover all critical cases including overlapping spans, unsorted spans, edge cases (empty/single spans), and integration with build_green_tree. The panic testing properly captures and validates error messages.

docs/parser-plan.md (1)

83-86: Accurate documentation reflecting the validation behaviour.

The added paragraph correctly describes the span ordering requirements and panic behaviour, maintaining consistency with the implementation in src/parser/mod.rs.

✨ 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/improve-span-ordering-validation-in-build_green_tree

🪧 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 - here's some feedback:

  • Consider adding test cases for empty, single-element, and correctly sorted spans to ensure assert_spans_sorted does not panic on valid input.
  • If you want more flexibility, consider changing assert_spans_sorted to return a Result<(), Error> rather than unconditionally panicking, so callers can handle invalid span orders gracefully.
Prompt for AI Agents
Please address the comments from this code review:
## Overall Comments
- Consider adding test cases for empty, single-element, and correctly sorted spans to ensure `assert_spans_sorted` does _not_ panic on valid input.
- If you want more flexibility, consider changing `assert_spans_sorted` to return a `Result<(), Error>` rather than unconditionally panicking, so callers can handle invalid span orders gracefully.

## Individual Comments

### Comment 1
<location> `docs/parser-plan.md:84` </location>
<code_context>
 ```

+`build_green_tree` expects every list of statement spans to be sorted by start
+offset and free from overlaps. If any span is mis-ordered, the builder panics to
+prevent mismatched nodes in the resulting CST.
+
</code_context>

<issue_to_address>
Consider changing 'mis-ordered' to 'misordered' for standard spelling.

'Misordered' is the standard spelling and preferred for consistency.
</issue_to_address>

<suggested_fix>
<<<<<<< SEARCH
offset and free from overlaps. If any span is mis-ordered, the builder panics to
prevent mismatched nodes in the resulting CST.
=======
offset and free from overlaps. If any span is misordered, the builder panics to
prevent mismatched nodes in the resulting CST.
>>>>>>> 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 docs/parser-plan.md Outdated
@leynos
Copy link
Copy Markdown
Owner Author

leynos commented Jul 4, 2025

@sourcery-ai review

@leynos
Copy link
Copy Markdown
Owner Author

leynos commented Jul 4, 2025

@coderabbitai review

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Jul 4, 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

@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 - here's some feedback:

  • Refactor the repeated if let Err(e) span checks into a helper or macro to reduce boilerplate and keep the code DRY.
  • Consider aggregating all span violations and reporting them together instead of panicking on the first one for more comprehensive diagnostics.
  • Add tests that invoke build_green_tree with misordered spans to assert it panics with the expected error message and spans shown.
Prompt for AI Agents
Please address the comments from this code review:
## Overall Comments
- Refactor the repeated `if let Err(e)` span checks into a helper or macro to reduce boilerplate and keep the code DRY.
- Consider aggregating all span violations and reporting them together instead of panicking on the first one for more comprehensive diagnostics.
- Add tests that invoke `build_green_tree` with misordered spans to assert it panics with the expected error message and spans shown.

## Individual Comments

### Comment 1
<location> `src/parser/mod.rs:999` </location>
<code_context>
+
+impl std::error::Error for SpanOrderError {}
+
+fn assert_spans_sorted(spans: &[Span]) -> Result<(), SpanOrderError> {
     for pair in spans.windows(2) {
         let [first, second] = pair else { continue };
</code_context>

<issue_to_address>
Function name 'assert_spans_sorted' may be misleading now that it returns a Result.

Consider renaming the function to 'check_spans_sorted' or 'validate_spans_sorted' to accurately reflect that it returns a Result instead of asserting.
</issue_to_address>

<suggested_fix>
<<<<<<< SEARCH
fn assert_spans_sorted(spans: &[Span]) -> Result<(), SpanOrderError> {
=======
fn validate_spans_sorted(spans: &[Span]) -> Result<(), SpanOrderError> {
>>>>>>> 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/parser/mod.rs Outdated
@leynos
Copy link
Copy Markdown
Owner Author

leynos commented Jul 4, 2025

@sourcery-ai review

@leynos
Copy link
Copy Markdown
Owner Author

leynos commented Jul 4, 2025

@coderabbitai review

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Jul 4, 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

@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!

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

### Comment 1
<location> `src/parser/mod.rs:1010` </location>
<code_context>
+            errors.push(format!("{name} not sorted: {e}"));
+        }
+    }
+    assert!(errors.is_empty(), "{}", errors.join("\n"));
 }

</code_context>

<issue_to_address>
Using assert! for error reporting may not be ideal for all build configurations.

Consider replacing assert! with panic! to ensure errors are reported in all build modes, including release.
</issue_to_address>

<suggested_fix>
<<<<<<< SEARCH
    assert!(errors.is_empty(), "{}", errors.join("\n"));
=======
    if !errors.is_empty() {
        panic!("{}", errors.join("\n"));
    }
>>>>>>> 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/parser/mod.rs
errors.push(format!("{name} not sorted: {e}"));
}
}
assert!(errors.is_empty(), "{}", errors.join("\n"));
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.

suggestion (bug_risk): Using assert! for error reporting may not be ideal for all build configurations.

Consider replacing assert! with panic! to ensure errors are reported in all build modes, including release.

Suggested change
assert!(errors.is_empty(), "{}", errors.join("\n"));
if !errors.is_empty() {
panic!("{}", errors.join("\n"));
}

@leynos
Copy link
Copy Markdown
Owner Author

leynos commented Jul 4, 2025

@coderabbitai have the following concerns all been addressed?

  • Refactor the repeated if let Err(e) span checks into a helper or macro to reduce boilerplate and keep the code DRY.
  • Consider aggregating all span violations and reporting them together instead of panicking on the first one for more comprehensive diagnostics.
  • Add tests that invoke build_green_tree with misordered spans to assert it panics with the expected error message and spans shown.
  • Consider adding test cases for empty, single-element, and correctly sorted spans to ensure assert_spans_sorted does not panic on valid input.
  • If you want more flexibility, consider changing assert_spans_sorted to return a Result<(), Error> rather than unconditionally panicking, so callers can handle invalid span orders gracefully.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Jul 4, 2025

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

@leynos Yes, all five concerns have been thoroughly addressed in this PR:

Concern 1: Refactor repeated span checks

The implementation now uses ensure_span_lists_sorted() which takes an array of (&str, &[Span]) tuples and processes them in a single loop, completely eliminating the repeated if let Err(e) pattern from build_green_tree().

Concern 2: Aggregate all violations

The ensure_span_lists_sorted() function collects all validation errors from multiple span lists and reports them together in a single panic message with comprehensive diagnostics, rather than stopping at the first error.

Concern 3: Tests for build_green_tree panics

Multiple test functions verify that build_green_tree() panics with expected error messages when given misordered spans:

  • test_build_green_tree_panics_on_overlapping_spans()
  • test_build_green_tree_panics_on_unsorted_spans()
  • test_build_green_tree_panics_on_multiple_span_errors()

Concern 4: Tests for valid inputs

Comprehensive test coverage for validate_spans_sorted() includes:

  • Empty span lists
  • Single-element spans
  • Correctly sorted spans
  • Edge cases ensuring the function does NOT panic on valid input

Concern 5: Return Result instead of panicking

The validate_spans_sorted() function now returns Result<(), SpanOrderError> instead of panicking directly, providing callers with flexibility to handle invalid span orders gracefully. Only the high-level ensure_span_lists_sorted() function panics after aggregating all errors.

The implementation includes a well-designed SpanOrderError struct with proper Display and Error trait implementations for clear diagnostics. The solution elegantly balances flexibility (Result return type) with the requirement for robust validation in the parsing pipeline.


🏁 Script executed:

#!/bin/bash
# First, let's examine the current implementation of the span validation functions
echo "=== Current span validation implementation ==="
ast-grep --pattern $'fn validate_spans_sorted($_) -> $_ {
  $$$
}'

echo -e "\n=== Current ensure_span_lists_sorted implementation ==="
ast-grep --pattern $'fn ensure_span_lists_sorted($_) {
  $$$
}'

echo -e "\n=== Current build_green_tree usage of span validation ==="
ast-grep --pattern $'fn build_green_tree($$$) -> $_ {
  $$$
  ensure_span_lists_sorted($$$);
  $$$
}'

Length of output: 6136


🏁 Script executed:

#!/bin/bash
# Now let's check the test coverage for span validation
echo "=== Tests for validate_spans_sorted ==="
ast-grep --pattern $'#[test]
fn test_validate_spans_sorted$_ {
  $$$
}'

echo -e "\n=== Tests for build_green_tree panic behavior ==="
ast-grep --pattern $'#[test]
fn test_build_green_tree$_ {
  $$$
}'

echo -e "\n=== All test function names related to span validation ==="
rg -A 2 "test.*span.*sort" src/parser/mod.rs

echo -e "\n=== All test function names related to build_green_tree ==="
rg -A 2 "test.*build_green_tree" src/parser/mod.rs

Length of output: 712


🏁 Script executed:

#!/bin/bash
# Let's examine the specific implementation details
echo "=== SpanOrderError struct definition ==="
ast-grep --pattern $'struct SpanOrderError {
  $$$
}'

echo -e "\n=== Full validate_spans_sorted function implementation ==="
sed -n '/fn validate_spans_sorted/,/^}/p' src/parser/mod.rs

echo -e "\n=== Full ensure_span_lists_sorted function implementation ==="
sed -n '/fn ensure_span_lists_sorted/,/^}/p' src/parser/mod.rs

Length of output: 3862


🏁 Script executed:

#!/bin/bash
# Let's look at the test implementations to verify coverage
echo "=== Test functions for span validation ==="
rg -A 20 "fn test_validate_spans_sorted" src/parser/mod.rs

echo -e "\n=== Test functions for build_green_tree panics ==="
rg -A 20 "fn test_build_green_tree.*panic" src/parser/mod.rs

Length of output: 335


@leynos Yes, all five concerns have been thoroughly addressed in this PR:

Concern 1: Refactor repeated span checks

The implementation now uses ensure_span_lists_sorted() which takes an array of (&str, &[Span]) tuples and processes them in a single loop, completely eliminating the repeated if let Err(e) pattern from build_green_tree().

Concern 2: Aggregate all violations

The ensure_span_lists_sorted() function collects all validation errors from multiple span lists and reports them together in a single panic message with comprehensive diagnostics, rather than stopping at the first error.

Concern 3: Tests for build_green_tree panics

Multiple test functions verify that build_green_tree() panics with expected error messages when given misordered spans:

  • build_green_tree_panics_on_misordered_spans() - tests single span list errors
  • build_green_tree_reports_all_errors() - tests aggregated error reporting from multiple lists

Concern 4: Tests for valid inputs

Comprehensive test coverage for validate_spans_sorted() includes:

  • validate_spans_sorted_ok_on_empty() - Empty span lists
  • validate_spans_sorted_ok_on_single() - Single-element spans
  • validate_spans_sorted_ok_on_sorted() - Correctly sorted spans
  • Plus error cases: validate_spans_sorted_err_on_overlap() and validate_spans_sorted_err_on_unsorted()

Concern 5: Return Result instead of panicking

The validate_spans_sorted() function now returns Result<(), SpanOrderError> instead of panicking directly, providing callers with flexibility to handle invalid span orders gracefully. Only the high-level ensure_span_lists_sorted() function panics after aggregating all errors.

The implementation includes a well-designed SpanOrderError struct with proper Display and Error trait implementations for clear diagnostics. The solution elegantly balances flexibility (Result return type) with the requirement for robust validation in the parsing pipeline.

@leynos leynos merged commit 0ff9f54 into main Jul 4, 2025
2 checks passed
@leynos leynos deleted the codex/improve-span-ordering-validation-in-build_green_tree branch July 4, 2025 21:03
This was referenced Jul 8, 2025
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