Skip to content

feat(napi): Expose node id via SgNode#1629

Merged
HerringtonDarkholme merged 2 commits intoast-grep:mainfrom
mohebifar:napi/expose-node-id
Nov 29, 2024
Merged

feat(napi): Expose node id via SgNode#1629
HerringtonDarkholme merged 2 commits intoast-grep:mainfrom
mohebifar:napi/expose-node-id

Conversation

@mohebifar
Copy link
Copy Markdown
Member

@mohebifar mohebifar commented Nov 29, 2024

This PR exposes node_id via SgNode. It's useful to check whether the results of two separate find operations are identical when using the NAPI API.

Summary by CodeRabbit

  • New Features
    • Introduced a new method id() for the SgNode class, allowing users to retrieve the unique identifier of each node.
  • Enhancements
    • Improved functionality for tracking and referencing nodes within the abstract syntax tree (AST).
  • Tests
    • Added a new test case to verify the consistency of node IDs across different querying methods.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Nov 29, 2024

Walkthrough

The changes introduce a new method, id(), to the SgNode class in TypeScript and the corresponding SgNode struct in Rust. This method retrieves the unique identifier of a node, returning it as a number in TypeScript and as a Result<u32> in Rust. Additionally, a new test case is added to verify the functionality of the id() method, ensuring consistency in node identification. The existing functionality of the SgNode class and struct remains unchanged, with no modifications to other methods or interfaces.

Changes

File Path Change Summary
crates/napi/index.d.ts Added method id(): number in class SgNode.
crates/napi/src/sg_node.rs Added method pub fn id(&self) -> Result<u32> in struct SgNode.
crates/napi/test/index.spec.ts Added test get node id to verify node ID retrieval.

Poem

In the forest where nodes do play,
A new ID hops along the way.
With a number to call its own,
Each node can now be known! 🐇✨
So let us cheer, both near and far,
For the magic of the id() star!


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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 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.

@HerringtonDarkholme
Copy link
Copy Markdown
Member

Can you add a test case for this?

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

🧹 Outside diff range and nitpick comments (2)
crates/napi/src/sg_node.rs (1)

165-169: LGTM! Consider enhancing the documentation.

The implementation looks good and aligns with the PR objective of exposing node IDs for comparison. Consider enhancing the documentation to explain the purpose and usage:

-  /// Returns the node's id
+  /// Returns the node's unique identifier.
+  /// This can be used to efficiently compare two nodes for identity.
crates/napi/index.d.ts (1)

130-131: Consider enhancing the method documentation.

The current documentation "Returns the node's id" could be more descriptive about the method's intended use case for node comparison and any guarantees about id uniqueness.

Consider updating the JSDoc comment to:

-  /** Returns the node's id */
+  /**
+   * Returns a unique identifier for the node.
+   * Can be used to efficiently compare two nodes for identity.
+   * @returns A unique numeric identifier
+   */
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 29da2bf and edacc29.

📒 Files selected for processing (2)
  • crates/napi/index.d.ts (1 hunks)
  • crates/napi/src/sg_node.rs (1 hunks)
🔇 Additional comments (2)
crates/napi/src/sg_node.rs (1)

168-168: Verify the safety of usize to u32 casting

The cast from usize to u32 could potentially truncate on 64-bit systems. While node IDs are typically small sequential numbers, we should verify this assumption.

✅ Verification successful

Based on the search results, I can now generate the final response:

The usize to u32 cast for node_id is safe

The node_id implementation in crates/core/src/node.rs shows that IDs are derived from the tree-sitter node IDs, which are sequential and start from 0. Tree-sitter's implementation ensures node IDs are well within u32 range as they represent positions in a single syntax tree. The cast is safe for all practical purposes.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Search for node_id implementation to verify the ID generation logic
# and ensure it can't exceed u32::MAX

# Look for node_id implementation
ast-grep --pattern 'fn node_id($$$) { $$$}'

# Look for places where node IDs are generated/assigned
rg -A 5 'node_id'

Length of output: 5114

crates/napi/index.d.ts (1)

130-131: LGTM! Implementation aligns with PR objectives.

The addition of the id() method to SgNode class with a number return type correctly maps to the Rust implementation, enabling node comparison functionality as intended.

@codecov
Copy link
Copy Markdown

codecov bot commented Nov 29, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 87.03%. Comparing base (29da2bf) to head (1a945c1).
Report is 2 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main    #1629   +/-   ##
=======================================
  Coverage   87.03%   87.03%           
=======================================
  Files          95       95           
  Lines       15277    15277           
=======================================
  Hits        13296    13296           
  Misses       1981     1981           

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

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

🧹 Outside diff range and nitpick comments (1)
crates/napi/__test__/index.spec.ts (1)

222-227: Consider adding test cases for negative scenarios.

While the current test verifies that the same node returns the same ID, it would be valuable to add test cases that verify:

  1. Different nodes return different IDs
  2. Node IDs remain stable across multiple parses of the same code
  3. Edge cases like empty nodes or invalid patterns

Example addition:

 test('get node id', async t => {
   const sg = parse('console.log(123)')
   const nodeWithPattern = sg.root().find('console.log($$$)')
   const nodeWithKind = sg.root().find(kind('call_expression'))
   t.is(nodeWithPattern!.id(), nodeWithKind!.id())
+  // Verify different nodes have different IDs
+  const differentNode = sg.root().find('console')
+  t.not(nodeWithPattern!.id(), differentNode!.id())
+  
+  // Verify ID stability across parses
+  const sg2 = parse('console.log(123)')
+  const sameNodeDifferentParse = sg2.root().find('console.log($$$)')
+  t.is(nodeWithPattern!.id(), sameNodeDifferentParse!.id())
 })
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between edacc29 and 1a945c1.

📒 Files selected for processing (1)
  • crates/napi/__test__/index.spec.ts (2 hunks)
🔇 Additional comments (1)
crates/napi/__test__/index.spec.ts (1)

222-227: LGTM! The test case effectively verifies node ID comparison.

The test successfully validates that the same node can be identified consistently using different query methods.

@mohebifar
Copy link
Copy Markdown
Member Author

mohebifar commented Nov 29, 2024

Can you add a test case for this?

Added one test. But LMK if more tests are needed. I could add one to check for different ids for different nodes.

@HerringtonDarkholme HerringtonDarkholme added this pull request to the merge queue Nov 29, 2024
@HerringtonDarkholme
Copy link
Copy Markdown
Member

thanks

Merged via the queue into ast-grep:main with commit 625a1eb Nov 29, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants