Skip to content

Implement typedef parser#15

Open
leynos wants to merge 1 commit intomainfrom
codex/implement-typedef-parser-for-typedef-and-extern-type
Open

Implement typedef parser#15
leynos wants to merge 1 commit intomainfrom
codex/implement-typedef-parser-for-typedef-and-extern-type

Conversation

@leynos
Copy link
Copy Markdown
Owner

@leynos leynos commented Jun 26, 2025

Summary

  • support typedef and extern type parsing
  • build N_TYPE_DEF CST nodes and expose typed accessors
  • add tests covering standard, complex, and extern typedefs

Testing

  • cargo clippy -- -D warnings
  • cargo test
  • make lint
  • make test

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

Summary by Sourcery

Implement typedef and extern type parsing by tracking typedef spans, building corresponding CST nodes, and providing typed AST wrappers with accessors for name, definition, and extern status, accompanied by comprehensive tests.

New Features:

  • Support parsing of typedef and extern type declarations
  • Expose TypeDef AST nodes with name, definition, and extern flag accessors
  • Add a type_defs collector on the Root AST node

Enhancements:

  • Classify parsed items into imports and typedefs in parse_tokens
  • Extend the CST builder to emit N_TYPE_DEF nodes alongside imports

Tests:

  • Add tests for standard typedefs, complex tuple typedefs, and extern type declarations

Parse typedef and extern type declarations, build N_TYPE_DEF nodes, and add typed AST accessors. Extend tests for type definitions.
@sourcery-ai
Copy link
Copy Markdown
Contributor

sourcery-ai Bot commented Jun 26, 2025

Reviewer's Guide

This PR adds support for typedef and extern type parsing by extending the token parser to record typedef spans, updating the CST builder to emit N_TYPE_DEF nodes, and exposing typed accessors in the AST, with accompanying tests.

Class diagram for new and updated AST node types (TypeDef and Root)

classDiagram
    class Root {
        +Vec<Import> imports()
        +Vec<TypeDef> type_defs()
    }
    class Import {
        +syntax: SyntaxNode
        +syntax() SyntaxNode
        +path() Option<String>
        +alias() Option<String>
    }
    class TypeDef {
        +syntax: SyntaxNode
        +syntax() SyntaxNode
        +name() Option<String>
        +is_extern() bool
        +definition() Option<String>
    }
    Root --> Import : contains
    Root --> TypeDef : contains
Loading

File-Level Changes

Change Details Files
Enhance token parser to recognize and record typedef and extern type declarations
  • Change parse_tokens to return ItemSpans instead of import spans
  • Introduce Item enum for imports and types
  • Define typedef_alias and extern_type parsers with span mapping
  • Add recursive type grammar for parsing complex type structures
src/parser/mod.rs
Update CST builder to wrap typedef spans in N_TYPE_DEF nodes
  • Accept ItemSpans in build_green_tree
  • Add type_iter alongside import_iter
  • Start and finish N_TYPE_DEF nodes based on typedef spans
  • Adjust comments to reference both imports and typedefs
src/parser/mod.rs
Extend AST with TypeDef wrapper and root accessor
  • Add type_defs() method to ast::Root
  • Introduce TypeDef struct with name(), is_extern(), and definition() accessors
  • Handle extern-type and alias scenarios in accessor implementations
src/parser/mod.rs
Add parser tests for typedef and extern type cases
  • Implement typedef_standard_case for simple alias parsing
  • Implement typedef_complex_case for tuple-type definitions
  • Implement extern_type_case to verify extern declarations
tests/parser.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 Jun 26, 2025

Summary by CodeRabbit

  • New Features

    • Added support for parsing and handling typedef and extern type declarations alongside imports.
    • Introduced new methods to access and introspect typedef nodes in the syntax tree.
  • Tests

    • Added tests to verify correct parsing and recognition of typedef and extern type declarations.

Walkthrough

The parser was extended to distinguish and process both import and typedef declarations at the top level. Internal data structures and functions were updated to track and handle spans for imports and typedefs separately. The typed AST gained a new TypeDef struct with introspection methods, and new tests were added for typedef parsing.

Changes

File(s) Change Summary
src/parser/mod.rs Parser now tracks imports and typedefs separately; new ItemSpans struct; updated CST builder; added TypeDef struct and related methods for typed AST; extended root node API.
tests/parser.rs Added Clippy lint for .expect(); introduced tests for parsing typedef and extern type declarations.

Sequence Diagram(s)

sequenceDiagram
    participant Source as Source Code
    participant Parser as Parser
    participant CST as CST Builder
    participant AST as Typed AST

    Source->>Parser: Provide tokens
    Parser->>Parser: Identify imports and typedefs, collect spans
    Parser->>CST: Pass tokens and ItemSpans
    CST->>CST: Build CST nodes for imports and typedefs
    CST->>AST: Wrap typedef nodes in TypeDef structs
    AST->>AST: Provide methods for introspection (name, definition, is_extern)
Loading

Poem

In the warren of code, new types now appear,
Imports and typedefs, both crystal clear.
With careful new structs and a parsing delight,
The AST rabbits hop through the night.
Extern or alias, each type in its den—
Hooray for the parser, improved once again!
🐇✨

✨ 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-typedef-parser-for-typedef-and-extern-type

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

  • Refactor the duplicated span-advancing and node-start/finish logic in build_green_tree into a common helper to reduce boilerplate for imports and typedefs.
  • Simplify TypeDef.definition() by extracting the child type syntax node and using its .text() instead of manually iterating and concatenating tokens.
  • In parse_tokens(), consider dropping the temporary Item enum and partitioning spans directly into ItemSpans for clearer, more concise span collection.
Prompt for AI Agents
Please address the comments from this code review:
## Overall Comments
- Refactor the duplicated span-advancing and node-start/finish logic in build_green_tree into a common helper to reduce boilerplate for imports and typedefs.
- Simplify TypeDef.definition() by extracting the child type syntax node and using its .text() instead of manually iterating and concatenating tokens.
- In parse_tokens(), consider dropping the temporary Item enum and partitioning spans directly into ItemSpans for clearer, more concise span collection.

## Individual Comments

### Comment 1
<location> `src/parser/mod.rs:186` </location>
<code_context>
                 break;
             }
         }
+        while let Some(next) = type_iter.peek() {
+            if span.start >= next.end {
+                type_iter.next();
+            } else {
+                break;
+            }
+        }
         // Begin an `N_IMPORT_STMT` node when this token marks the start of an
</code_context>

<issue_to_address>
Duplicated logic for advancing import_iter and type_iter could be refactored.

Consider extracting the shared logic into a helper function to minimize duplication and reduce the risk of inconsistencies.

Suggested implementation:

```rust
    let mut import_iter = items.imports.iter().peekable();
    let mut type_iter = items.typedefs.iter().peekable();

    fn advance_iter_to_span<'a, I>(iter: &mut std::iter::Peekable<I>, span_start: usize)
    where
        I: Iterator<Item = &'a _>,
        &'a _: std::ops::Deref<Target = crate::Span>, // Adjust as needed for your Span type
    {
        while let Some(next) = iter.peek() {
            if span_start >= next.end {
                iter.next();
            } else {
                break;
            }
        }
    }

    for (kind, span) in tokens {
        // Advance to the next import span if this token lies after the end of
        // the current one.  Multiple tokens can share the same span, so we need
        advance_iter_to_span(&mut import_iter, span.start);
        advance_iter_to_span(&mut type_iter, span.start);

```

- You may need to adjust the type bounds and dereferencing in the `advance_iter_to_span` function depending on the actual type of your span objects (e.g., if they are not directly accessible via `.end`).
- Remove the old duplicated iterator-advancing code for both `import_iter` and `type_iter`.
</issue_to_address>

### Comment 2
<location> `src/parser/mod.rs:235` </location>
<code_context>
             builder.finish_node();
             import_iter.next();
         }
+        if type_iter
+            .peek()
+            .is_some_and(|current| span.end >= current.end)
+        {
+            builder.finish_node();
+            type_iter.next();
+        }
     }
</code_context>

<issue_to_address>
Finishing nodes for import and typedef may overlap if spans are not disjoint.

If overlapping spans are possible, both finish_node calls could be executed for the same token. If this can't happen, please add an assertion or comment to clarify this invariant.
</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/mod.rs
@@ -21,6 +21,12 @@ pub struct Parsed {
errors: Vec<Simple<SyntaxKind>>,
}
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: Duplicated logic for advancing import_iter and type_iter could be refactored.

Consider extracting the shared logic into a helper function to minimize duplication and reduce the risk of inconsistencies.

Suggested implementation:

    let mut import_iter = items.imports.iter().peekable();
    let mut type_iter = items.typedefs.iter().peekable();

    fn advance_iter_to_span<'a, I>(iter: &mut std::iter::Peekable<I>, span_start: usize)
    where
        I: Iterator<Item = &'a _>,
        &'a _: std::ops::Deref<Target = crate::Span>, // Adjust as needed for your Span type
    {
        while let Some(next) = iter.peek() {
            if span_start >= next.end {
                iter.next();
            } else {
                break;
            }
        }
    }

    for (kind, span) in tokens {
        // Advance to the next import span if this token lies after the end of
        // the current one.  Multiple tokens can share the same span, so we need
        advance_iter_to_span(&mut import_iter, span.start);
        advance_iter_to_span(&mut type_iter, span.start);
  • You may need to adjust the type bounds and dereferencing in the advance_iter_to_span function depending on the actual type of your span objects (e.g., if they are not directly accessible via .end).
  • Remove the old duplicated iterator-advancing code for both import_iter and type_iter.

Comment thread src/parser/mod.rs
}
while let Some(next) = type_iter.peek() {
if span.start >= next.end {
type_iter.next();
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.

question (bug_risk): Finishing nodes for import and typedef may overlap if spans are not disjoint.

If overlapping spans are possible, both finish_node calls could be executed for the same token. If this can't happen, please add an assertion or comment to clarify this invariant.

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

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

186-241: Consider refactoring to reduce code duplication.

The logic for advancing iterators and starting/finishing nodes is duplicated between imports and typedefs. Consider extracting common logic.

You could extract the common pattern into a helper closure:

let mut handle_span = |iter: &mut std::iter::Peekable<_>, node_kind| {
    // Advance iterator logic
    while let Some(next) = iter.peek() {
        if span.start >= next.end {
            iter.next();
        } else {
            break;
        }
    }
    
    // Start node if at span start
    if iter.peek().is_some_and(|current| span.start == current.start) {
        builder.start_node(DdlogLanguage::kind_to_raw(node_kind));
        return true;
    }
    false
};

// Then use it for both imports and typedefs
let started_import = handle_span(&mut import_iter, SyntaxKind::N_IMPORT_STMT);
let started_typedef = handle_span(&mut type_iter, SyntaxKind::N_TYPE_DEF);
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between cb80bd1 and e60d641.

📒 Files selected for processing (2)
  • src/parser/mod.rs (9 hunks)
  • tests/parser.rs (2 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
`**/*.rs`: Document public APIs using Rustdoc comments (`///`) so documentation ...

**/*.rs: Document public APIs using Rustdoc comments (///) so documentation can be generated with cargo doc.
Every module must begin with a module level (//!) comment explaining the module's purpose and utility.
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().
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.
Use explicit version ranges in Cargo.toml and keep dependencies up-to-date.
Use rstest fixtures for shared setup.
Replace duplicated tests with #[rstest(...)] parameterised cases.
Prefer mockall for mocks/stubs.
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.

📄 Source: CodeRabbit Inference Engine (AGENTS.md)

List of files the instruction was applied to:

  • tests/parser.rs
  • src/parser/mod.rs
🧬 Code Graph Analysis (1)
src/parser/mod.rs (1)
src/language.rs (1)
  • kind_to_raw (182-187)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: build-test
🔇 Additional comments (5)
src/parser/mod.rs (3)

70-165: Well-structured parser implementation for typedef support.

The parser correctly handles both typedef aliases and extern type declarations using appropriate chumsky combinators. The recursive type parser for tuples is particularly well-implemented.


310-318: Clean implementation consistent with existing patterns.

The type_defs() method correctly mirrors the imports() method implementation.


24-28: Add documentation for the ItemSpans struct.

The struct lacks documentation comments required by the coding guidelines.

+/// Holds spans for different types of top-level items parsed from the source.
 #[derive(Default)]
 struct ItemSpans {
+    /// Spans of import statements.
     imports: Vec<Span>,
+    /// Spans of typedef declarations.
     typedefs: Vec<Span>,
 }

Likely an incorrect or invalid review comment.

tests/parser.rs (2)

7-7: Appropriate lint configuration for test code.

The expect_used lint expectation is correctly scoped and justified for test assertions.


161-197: Comprehensive test coverage for typedef parsing.

The three test cases effectively cover the main typedef scenarios: standard aliases, complex tuple types, and extern declarations. The assertions properly validate the TypeDef API methods.

Comment thread src/parser/mod.rs
Comment on lines +420 to +447
pub fn definition(&self) -> Option<String> {
if self.is_extern() {
return None;
}
let mut found_eq = false;
let mut out = String::new();
for e in self.syntax.children_with_tokens() {
match e {
rowan::NodeOrToken::Token(t) => {
if found_eq {
out.push_str(t.text());
} else if t.kind() == SyntaxKind::T_EQ {
found_eq = true;
}
}
rowan::NodeOrToken::Node(n) => {
if found_eq {
out.push_str(&n.text().to_string());
}
}
}
}
if found_eq {
Some(out.trim().to_string())
} else {
None
}
}
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Consider using iterator-based approach for better performance.

The current implementation with string concatenation in a loop could be inefficient for large type definitions.

 pub fn definition(&self) -> Option<String> {
     if self.is_extern() {
         return None;
     }
-    let mut found_eq = false;
-    let mut out = String::new();
-    for e in self.syntax.children_with_tokens() {
-        match e {
-            rowan::NodeOrToken::Token(t) => {
-                if found_eq {
-                    out.push_str(t.text());
-                } else if t.kind() == SyntaxKind::T_EQ {
-                    found_eq = true;
-                }
-            }
-            rowan::NodeOrToken::Node(n) => {
-                if found_eq {
-                    out.push_str(&n.text().to_string());
-                }
-            }
-        }
-    }
-    if found_eq {
-        Some(out.trim().to_string())
-    } else {
-        None
-    }
+    let eq_pos = self.syntax
+        .children_with_tokens()
+        .position(|e| matches!(e.kind(), SyntaxKind::T_EQ))?;
+    
+    let definition = self.syntax
+        .children_with_tokens()
+        .skip(eq_pos + 1)
+        .map(|e| match e {
+            rowan::NodeOrToken::Token(t) => t.text().to_string(),
+            rowan::NodeOrToken::Node(n) => n.text().to_string(),
+        })
+        .collect::<String>();
+    
+    Some(definition.trim().to_string())
 }

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In src/parser/mod.rs around lines 420 to 447, the definition method uses string
concatenation inside a loop, which can be inefficient for large type
definitions. Refactor this method to use an iterator-based approach by
collecting the relevant text pieces into an iterator and then joining them once
at the end, instead of appending strings repeatedly. This will improve
performance by minimizing intermediate string allocations.

Comment thread src/parser/mod.rs
Comment on lines +385 to +408
pub fn name(&self) -> Option<String> {
let mut iter = self.syntax.children_with_tokens();
for el in iter.by_ref() {
match el.kind() {
SyntaxKind::K_TYPEDEF => break,
SyntaxKind::K_EXTERN => {
// skip 'extern type'
for tok in iter.by_ref() {
if tok.kind() == SyntaxKind::K_TYPE {
break;
}
}
break;
}
_ => {}
}
}
iter.find_map(|e| match e {
rowan::NodeOrToken::Token(t) if t.kind() == SyntaxKind::T_IDENT => {
Some(t.text().to_string())
}
_ => None,
})
}
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.

🛠️ Refactor suggestion

Simplify the name() method implementation.

The current implementation with nested loops and manual iteration is hard to follow. Consider using iterator combinators for clarity.

 pub fn name(&self) -> Option<String> {
-    let mut iter = self.syntax.children_with_tokens();
-    for el in iter.by_ref() {
-        match el.kind() {
-            SyntaxKind::K_TYPEDEF => break,
-            SyntaxKind::K_EXTERN => {
-                // skip 'extern type'
-                for tok in iter.by_ref() {
-                    if tok.kind() == SyntaxKind::K_TYPE {
-                        break;
-                    }
-                }
-                break;
-            }
-            _ => {}
-        }
-    }
-    iter.find_map(|e| match e {
-        rowan::NodeOrToken::Token(t) if t.kind() == SyntaxKind::T_IDENT => {
-            Some(t.text().to_string())
-        }
-        _ => None,
-    })
+    self.syntax
+        .children_with_tokens()
+        .skip_while(|e| !matches!(e.kind(), SyntaxKind::K_TYPEDEF | SyntaxKind::K_EXTERN))
+        .skip_while(|e| e.kind() != SyntaxKind::T_IDENT)
+        .find_map(|e| match e {
+            rowan::NodeOrToken::Token(t) if t.kind() == SyntaxKind::T_IDENT => {
+                Some(t.text().to_string())
+            }
+            _ => None,
+        })
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
pub fn name(&self) -> Option<String> {
let mut iter = self.syntax.children_with_tokens();
for el in iter.by_ref() {
match el.kind() {
SyntaxKind::K_TYPEDEF => break,
SyntaxKind::K_EXTERN => {
// skip 'extern type'
for tok in iter.by_ref() {
if tok.kind() == SyntaxKind::K_TYPE {
break;
}
}
break;
}
_ => {}
}
}
iter.find_map(|e| match e {
rowan::NodeOrToken::Token(t) if t.kind() == SyntaxKind::T_IDENT => {
Some(t.text().to_string())
}
_ => None,
})
}
pub fn name(&self) -> Option<String> {
self.syntax
.children_with_tokens()
.skip_while(|e| !matches!(e.kind(), SyntaxKind::K_TYPEDEF | SyntaxKind::K_EXTERN))
.skip_while(|e| e.kind() != SyntaxKind::T_IDENT)
.find_map(|e| match e {
rowan::NodeOrToken::Token(t) if t.kind() == SyntaxKind::T_IDENT => {
Some(t.text().to_string())
}
_ => None,
})
}
🤖 Prompt for AI Agents
In src/parser/mod.rs around lines 385 to 408, the name() method uses nested
loops and manual iteration, making it hard to read. Refactor this method to use
iterator combinators like filter, skip_while, or find_map to simplify the logic
and improve clarity while preserving the existing behavior.

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