Skip to content

Implement import parser#13

Merged
leynos merged 3 commits intomainfrom
codex/implement-imprt-parser-for-import-statements
Jun 26, 2025
Merged

Implement import parser#13
leynos merged 3 commits intomainfrom
codex/implement-imprt-parser-for-import-statements

Conversation

@leynos
Copy link
Copy Markdown
Owner

@leynos leynos commented Jun 25, 2025

Summary

  • recognise import statements with optional aliases
  • represent import declarations with a new syntax node
  • expose typed Import nodes from the AST
  • add tests for valid and invalid import syntax
  • align docs with markdownlint

Testing

  • make fmt
  • make lint
  • make test

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

Summary by Sourcery

Implement import statement parsing with AST support, tests, and updated documentation

New Features:

  • Recognize and parse import statements with optional aliases into the AST
  • Expose typed Import nodes with path() and alias() accessors
  • Provide Root.imports() method to collect import statements

Enhancements:

  • Annotate import spans in the green tree builder and rename SyntaxKind::N_IMPORT to N_IMPORT_STMT
  • Refactor parser combinators to specifically handle import syntax
  • Revise Markdown docs and testing guide formatting for markdownlint compliance

Documentation:

  • Update parser and testing documentation with improved headings, bullet lists, and formatting adjustments

Tests:

  • Add tests for standard, aliased, and invalid import statements

@sourcery-ai
Copy link
Copy Markdown
Contributor

sourcery-ai Bot commented Jun 25, 2025

Reviewer's Guide

This PR adds full support for import statements by extending the parser combinators to capture import spans, weaving them into the green-tree builder to produce new N_IMPORT_STMT nodes, exposing a typed Import AST API, updating the syntax enum, covering the feature with new tests, and polishing the docs for consistency.

File-Level Changes

Change Details Files
Extend parser to capture import spans and embed import statements in the green tree
  • Changed parse to return import spans and pass them to build_green_tree
  • Replaced parse_tokens to use chumsky grammar for import (ws, ident, module_path, alias) and return Vec<Span>
  • Updated build_green_tree to open/close N_IMPORT_STMT nodes based on import spans
src/parser/mod.rs
Expose a typed AST API for import declarations
  • Added Root::imports() to collect all import statement nodes
  • Introduced Import struct with .syntax(), .path(), and .alias() accessors
  • Derived Debug and Clone for the new Import type
src/parser/mod.rs
Rename syntax kind for import statements
  • Renamed N_IMPORT to N_IMPORT_STMT in the syntax-kind enum
src/language.rs
Add parser tests for valid and invalid import syntax
  • Added test for a standard import without alias
  • Added test for import with as alias
  • Added test for import with missing path to validate error reporting
tests/parser.rs
Align and clean up markdown documentation
  • Reformatted headings, lists, and block quotes in the error-recovering-parser guide
  • Converted the testing strategy table into concise bullet lists
  • Applied markdownlint fixes for line wrapping and header levels
docs/building-an-error-recovering-parser-with-chumsky.md
docs/rust-parser-testing-comprehensive-guide.md

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 Jun 25, 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 7 minutes and 12 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 2a7767c and cab8250.

📒 Files selected for processing (4)
  • docs/building-an-error-recovering-parser-with-chumsky.md (1 hunks)
  • docs/rust-parser-testing-comprehensive-guide.md (1 hunks)
  • src/parser/mod.rs (4 hunks)
  • tests/parser.rs (2 hunks)

Summary by CodeRabbit

  • New Features

    • Enhanced parser to explicitly recognise and represent import statements, including optional aliases, providing structured access to import paths and aliases in the AST.
  • Bug Fixes

    • Improved error detection for malformed import statements.
  • Documentation

    • Reformatted and clarified documentation for better readability and consistency.
    • Simplified the summary of parser testing strategies for clearer presentation.
  • Tests

    • Added tests to verify correct parsing of import statements, including cases with and without aliases, and handling of invalid input.

Walkthrough

This update introduces structured parsing and AST support for import statements in the parser module. The parser now identifies import statements, including those with optional aliases, and represents them as dedicated nodes in the CST and AST. Corresponding methods for extracting import paths and aliases are added, and new tests verify correct parsing and error handling for import statements. Documentation files are also reformatted for clarity.

Changes

File(s) Change Summary
docs/building-an-error-recovering-parser-with-chumsky.md Reformatted headings, line breaks, and spacing for improved readability; no substantive content changes.
docs/rust-parser-testing-comprehensive-guide.md Replaced detailed markdown table of testing strategies with a concise bulleted list; simplified presentation.
src/language.rs Renamed SyntaxKind enum variant from N_IMPORT to N_IMPORT_STMT.
src/parser/mod.rs Implemented targeted parsing for import statements with/without alias; added AST Import struct and methods.
tests/parser.rs Added three tests for parsing import statements: standard, with alias, and invalid (missing path).

Sequence Diagram(s)

sequenceDiagram
    participant SourceFile
    participant Parser
    participant CST as ConcreteSyntaxTree
    participant AST as AbstractSyntaxTree
    participant ImportNode

    SourceFile->>Parser: Provide source code
    Parser->>Parser: Parse tokens, recognise 'import' statements
    Parser->>CST: Create N_IMPORT_STMT nodes for imports
    Parser->>AST: Create Import struct for each import node
    AST->>ImportNode: Provide methods for path and alias extraction
Loading

Possibly related PRs

  • Introduce basic parser skeleton #10: Introduced the parser skeleton; this PR directly builds upon it by adding specific import statement parsing logic, AST node definitions, and related tests.

Poem

In the warren of code, a parser awakes,
Now sniffing out imports for syntax’s sake.
With aliases found and errors detected,
The AST’s branches are neatly connected.
Documentation tidied, tests join the dance—
This bunny’s parser now leaps in advance!
🐇📦

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate Unit Tests
  • Create PR with Unit Tests
  • Post Copyable Unit Tests in Comment
  • Commit Unit Tests in branch codex/implement-imprt-parser-for-import-statements

🪧 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 Jun 26, 2025

@coderabbitai review

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Jun 26, 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: 7

🔭 Outside diff range comments (1)
src/parser/mod.rs (1)

104-141: Complex span matching logic needs careful consideration.

The logic for matching token spans with import spans is intricate. Consider adding comments to explain the algorithm, particularly:

  • Why we need to skip past import spans that have already ended (lines 104-110)
  • The relationship between token spans and import spans
  • Why we check both start and end boundaries
 for (kind, span) in tokens {
+    // Skip any import spans that have already ended before this token
     while let Some(next) = import_iter.peek() {
         if span.start >= next.end {
             import_iter.next();
         } else {
             break;
         }
     }
+    // Start an import node if this token begins at an import span start
     if import_iter
         .peek()
         .is_some_and(|current| span.start == current.start)
     {
         builder.start_node(DdlogLanguage::kind_to_raw(SyntaxKind::N_IMPORT_STMT));
     }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 656f35b and 2a7767c.

📒 Files selected for processing (5)
  • docs/building-an-error-recovering-parser-with-chumsky.md (1 hunks)
  • docs/rust-parser-testing-comprehensive-guide.md (1 hunks)
  • src/language.rs (1 hunks)
  • src/parser/mod.rs (4 hunks)
  • tests/parser.rs (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
src/parser/mod.rs (1)
src/language.rs (1)
  • kind_to_raw (182-187)
🪛 LanguageTool
docs/building-an-error-recovering-parser-with-chumsky.md

[grammar] ~19-~19: Please add a punctuation mark at the end of paragraph.
Context: ...tc.”) - Examples of legal and illegal programmes ### 2 Feed It Tokens, Not Breadcrumbs ...

(PUNCTUATION_PARAGRAPH_END)


[uncategorized] ~38-~38: Loose punctuation mark.
Context: ...rser. Forward references? Wrap them in recursive(|expr| { … }) so Chumsky can see round corners. Am...

(UNLIKELY_OPENING_PUNCTUATION)


[uncategorized] ~52-~52: Possible missing comma found.
Context: ...Option`; missing bits propagate but the parse soldier on. In practice y...

(AI_HYDRA_LEO_MISSING_COMMA)


[uncategorized] ~53-~53: The grammatical number of this noun doesn’t look right. Consider replacing it.
Context: ...missing bits propagate but the parse soldier on. In practice you’ll compose the bui...

(AI_EN_LECTOR_REPLACEMENT_NOUN_NUMBER)


[uncategorized] ~55-~55: A comma is probably missing here.
Context: ...pagate but the parse soldier on. In practice you’ll compose the built-ins (`NestedDe...

(MISSING_COMMA_AFTER_INTRODUCTORY_PHRASE)


[uncategorized] ~60-~60: Possible missing comma found.
Context: ...Tall Neural Net) Codex is a marvellous companion so long as you: - **Constrain its univ...

(AI_HYDRA_LEO_MISSING_COMMA)


[misspelling] ~66-~66: This word is normally spelled as one.
Context: ...** Generate random AST → pretty-print → re-parse → assert equality. Failures mean Code...

(EN_COMPOUNDS_RE_PARSE)

🔇 Additional comments (3)
src/language.rs (1)

165-165: Good naming improvement!

The rename from N_IMPORT to N_IMPORT_STMT better reflects that this represents a complete import statement node in the AST, making the code more self-documenting.

tests/parser.rs (1)

91-103: Well-structured test for aliased imports.

The test properly validates both the import path and alias extraction.

src/parser/mod.rs (1)

64-97: Well-structured parser combinator implementation.

The import parser correctly handles module paths with :: separators and optional aliases. The use of padded_by for whitespace handling is appropriate.

Comment thread docs/building-an-error-recovering-parser-with-chumsky.md Outdated
Comment thread docs/building-an-error-recovering-parser-with-chumsky.md Outdated
Comment thread docs/rust-parser-testing-comprehensive-guide.md Outdated
Comment thread tests/parser.rs
Comment thread tests/parser.rs
Comment thread src/parser/mod.rs
Comment thread src/parser/mod.rs
@leynos leynos merged commit 405aba1 into main Jun 26, 2025
2 checks passed
@leynos leynos deleted the codex/implement-imprt-parser-for-import-statements branch June 26, 2025 18:46
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