Skip to content

Extract span scanner module#75

Merged
leynos merged 1 commit intomainfrom
codex/extract-parser-span_scanner-module
Jul 16, 2025
Merged

Extract span scanner module#75
leynos merged 1 commit intomainfrom
codex/extract-parser-span_scanner-module

Conversation

@leynos
Copy link
Copy Markdown
Owner

@leynos leynos commented Jul 16, 2025

Summary

  • move span scanning helpers to new span_scanner module
  • reference the scanner from the parser entry point

Testing

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

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

Summary by Sourcery

Extract span scanning logic from the main parser module into its own span_scanner module and update the parser entry point to use the new module.

Enhancements:

  • Move span scanning helpers into a dedicated span_scanner module under src/parser
  • Update parser/mod.rs to reference the parse_tokens function from the new module

@sourcery-ai
Copy link
Copy Markdown
Contributor

sourcery-ai Bot commented Jul 16, 2025

Reviewer's Guide

Refactor parser by extracting all span scanning logic into a dedicated span_scanner module, streamlining mod.rs and centralizing boundary collection functions for imports, typedefs, relations, indexes, functions, transformers, and rules.

Class diagram for parser module refactor with span_scanner extraction

classDiagram
    class ParserMod {
        +parse(src: &str) Parsed
        +parse_tokens -- moved --> SpanScanner::parse_tokens
    }
    class SpanScanner {
        +parse_tokens(tokens: &[(SyntaxKind, Span)], src: &str) -> (ParsedSpans, Vec<Simple<SyntaxKind>>)
        +collect_import_spans(tokens, src)
        +collect_typedef_spans(tokens, src)
        +collect_relation_spans(tokens, src)
        +collect_index_spans(tokens, src)
        +collect_function_spans(tokens, src)
        +collect_transformer_spans(tokens, src)
        +collect_rule_spans(tokens, src)
    }
    ParserMod ..> SpanScanner : uses
    class ParsedSpans
    class SyntaxKind
    class Span
    class Simple
    ParserMod --> ParsedSpans
    SpanScanner --> ParsedSpans
    SpanScanner --> SyntaxKind
    SpanScanner --> Span
    SpanScanner --> Simple
Loading

File-Level Changes

Change Details Files
Remove inline span scanning implementations and delegate to new module
  • Deleted parse_tokens and all collect_* span functions from mod.rs
  • Replaced direct span scanning calls with a reference to span_scanner::parse_tokens
  • Added module import for span_scanner in parser entry point
src/parser/mod.rs
Add new span_scanner module containing span scanning helpers
  • Created span_scanner.rs with the parse_tokens function and error aggregation
  • Moved all collect_* span scanning functions into the new module
  • Imported required utilities from lexer_helpers and span_collector
src/parser/span_scanner.rs

Possibly linked issues


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

Summary by CodeRabbit

  • Refactor

    • Replaced the internal logic for scanning and grouping top-level statements in the parser with a new, modular implementation.
    • Improved the structure and maintainability of the code responsible for identifying statement spans such as imports, typedefs, relations, indexes, functions, transformers, and rules.
  • Chores

    • Updated internal module structure to support the new parsing approach.

Walkthrough

Replace all internal span collection and token scanning logic in src/parser/mod.rs with a new implementation located in src/parser/span_scanner.rs. Remove all previous private span collection functions. Import and delegate to the new parse_tokens function from the span_scanner module, maintaining the existing public interface.

Changes

File(s) Change Summary
src/parser/mod.rs Remove all internal span collection functions; add import and delegation to span_scanner::parse_tokens.
src/parser/span_scanner.rs Add new module implementing all span scanning and collection functions; provide parse_tokens as main entrypoint.

Sequence Diagram(s)

sequenceDiagram
    participant Parser as parser/mod.rs
    participant Scanner as span_scanner.rs

    Parser->>Scanner: parse_tokens(tokens, src)
    Scanner->>Scanner: Collect import, typedef, relation, index, function, transformer, rule spans
    Scanner-->>Parser: (ParsedSpans, Errors)
    Parser->>Parser: Continue CST construction with returned spans
Loading

Possibly related PRs

Poem

Out with the old, in with the scan,
Spans now collected by a brand new plan!
Mod.rs is lighter, its duties are few—
Span_scanner takes charge, parsing anew.
Tokens march forth, errors in tow,
The parser and scanner now steal the show.
🦀✨


📜 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 f6878e0 and c9470e4.

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

Instructions used from:

Sources:
⚙️ CodeRabbit Configuration File

🧬 Code Graph Analysis (1)
src/parser/mod.rs (1)
src/parser/span_scanner.rs (1)
  • parse_tokens (19-50)
🔇 Additional comments (11)
src/parser/mod.rs (2)

21-23: LGTM! Clean module extraction.

The span scanner module is properly declared and the import statement correctly brings in the parse_tokens function. This aligns with the PR's objective of modularizing the span scanning logic.


180-180: Function correctly delegates to the new module.

The parse function now uses span_scanner::parse_tokens, maintaining the same interface while achieving the modularization goal.

src/parser/span_scanner.rs (9)

1-7: Module documentation meets requirements.

The module-level doc comment properly explains the module's purpose and utility using the required //! format.


19-50: Well-structured orchestration function.

The parse_tokens function effectively coordinates span collection across all statement types and properly aggregates errors. The return type correctly provides both spans and errors.


52-103: Import span collection correctly implemented.

The function properly handles import statements with module paths and optional aliases, with appropriate error recovery that skips to line end on failure.


105-153: Generic extern declaration handler well designed.

The function provides good reusability for parsing various extern declarations. It correctly validates that the expected declaration type follows the extern keyword and returns appropriate spans.


155-188: Typedef collection handles both forms correctly.

The function properly handles both typedef and extern type declarations using direct token manipulation, which is appropriate for these simpler statement forms.


190-302: Comprehensive relation span collection.

The function correctly handles all relation declaration variants (input, output, and plain relation) with proper parsing of column lists and primary key clauses. Good error recovery at multiple parsing stages.


304-351: Index span collection properly structured.

The function correctly parses index declarations including name, target relation, and column list. Good use of balanced_block_nonempty to ensure the column list contains content.


353-454: Function span collection handles both declaration types.

The implementation correctly differentiates between extern function declarations (optional body) and regular function definitions (required body). Good use of conditional parsing based on the function type.


484-567: Rule span collection with proper line-start validation.

The function correctly ensures rules only start at the beginning of lines and properly parses both facts (head only) and rules (head with body). The line-start detection logic is well implemented.

✨ 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/extract-parser-span_scanner-module

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

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

### Comment 1
<location> `src/parser/span_scanner.rs:52` </location>
<code_context>
-/// let (import_spans, errors) = collect_import_spans(&tokens, src);
-/// assert!(!import_spans.is_empty());
-/// ```
-fn collect_import_spans(
-    tokens: &[(SyntaxKind, Span)],
-    src: &str,
</code_context>

<issue_to_address>
Consider extracting the common span-collection logic in the `collect_*_spans` functions into a generic helper to reduce duplication.

```markdown
Most of the `collect_*_spans` functions share the same “instantiate a `SpanCollector`, hook up a single‐token dispatch, run `parse_span`, then either push or skip on error” pattern.  You can factor that out into a small generic helper and then each `collect_*_spans` becomes just “call `collect_with_parser` with my keyword and parser builder.”  

Example:

```rust
fn collect_with_parser<F, P>(
    tokens: &[(SyntaxKind, Span)],
    src: &str,
    kind: SyntaxKind,
    mk_parser: F,
) -> (Vec<Span>, Vec<Simple<SyntaxKind>>)
where
    F: Fn() -> P,
    P: Parser<SyntaxKind, Span, Error = Simple<SyntaxKind>>,
{
    type State<'a> = SpanCollector<'a, Vec<Simple<SyntaxKind>>>;
    let mut st = State::new(tokens, src, Vec::new());
    let handler = move |st: &mut State<'_>, span: Span| {
        let (res, errs) = st.parse_span(mk_parser(), span.start);
        if let Some(sp) = res {
            st.spans.push(sp.clone());
            st.stream.skip_until(sp.end);
        } else {
            st.extra.extend(errs);
            st.skip_line();
        }
    };
    token_dispatch!(st, { kind => handler });
    st.into_parts()
}
```

Then rewrite `collect_import_spans` as:

```rust
fn collect_import_spans(
    tokens: &[(SyntaxKind, Span)],
    src: &str,
) -> (Vec<Span>, Vec<Simple<SyntaxKind>>) {
    collect_with_parser(tokens, src, SyntaxKind::K_IMPORT, || {
        let ws = inline_ws().repeated();
        let ident = ident();
        let module_path = ident.clone()
            .then(just(SyntaxKind::T_COLON_COLON)
                .padded_by(ws.clone())
                .ignore_then(ident.clone())
                .repeated())
            .ignored();
        let alias = just(SyntaxKind::K_AS).padded_by(ws.clone()).ignore_then(ident);
        just(SyntaxKind::K_IMPORT)
            .padded_by(ws.clone())
            .ignore_then(module_path)
            .then(alias.or_not())
            .padded_by(ws)
            .map_with_span(|_, sp| sp)
    })
}
```

You can apply the same pattern to `collect_index_spans`, `collect_transformer_spans`, `collect_function_spans`, etc., collapsing ~120 lines of duplicated span‐collection boilerplate while keeping each grammar fragment intact.
</issue_to_address>

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/span_scanner.rs
Repository owner deleted a comment from coderabbitai Bot Jul 16, 2025
@leynos
Copy link
Copy Markdown
Owner Author

leynos commented Jul 16, 2025

@coderabbitai review

@coderabbitai
Copy link
Copy Markdown
Contributor

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

@leynos leynos merged commit c960a35 into main Jul 16, 2025
2 checks passed
@leynos leynos deleted the codex/extract-parser-span_scanner-module branch July 16, 2025 22:52
@coderabbitai coderabbitai Bot mentioned this pull request Jul 30, 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