tree-sitter / tree-sitter/node-tree-sitter
[question] How to check whether two SyntaxNodes are the same?
Nobody has claimed this yet.
- Dominant language
- JavaScript
- Stars
- 876
- Forks
- 172
- PR merge metrics
- No merged PRs in 30d
Description
I'm attempting to extract attributes of a certain type from a webpage, then reconstruct a JS object showing where they appeared in the original tree.
For example, I want to go from this input:
<div data-test='a'>
<div data-test='b'></div>
<div data-test='c'>
<div data-test='d'></div>
</div>
</div>
to
{
a: {
b: null,
c: {
d: null
}
}
}
The language in question is https://github.com/phoenixframework/tree-sitter-heex and I'm using this query:
const query = new Parser.Query(PhoenixHeexParser, `(
(attribute
(attribute_name) @attribute-name
(quoted_attribute_value
(attribute_value) @attribute-value
)
)
(#eq? @attribute-name "data-test")
)`);
const captures = query.captures(tree.rootNode)
.filter((match) => match.name === 'attribute-value');
console.log(captures.map(c => tree.getText(c.node)));
This correctly outputs the ['a', 'b', 'c', 'd'], but there doesn't appear to be any obvious way to gather their relative positions to each other.
What I've been trying to do is look at each matching capture's node and repeatedly use .parent and attempt to find a parent of one match that is the node from another match. But I can't figure out how to verify I've found the right node. And I suspect there's a better way... but documentation on tree-sitter is very sparse, especially on this node implementation. Comparing the text doesn't work, since the node text will have extraneous information (and it isn't guaranteed to be unique)
It might even be possible to do this with the original query itself, but I didn't see anything in the documentation that suggested this would be possible.
Contributor guide
No contributing guide indexed for this repository
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by reviewing the SyntaxNode API and the query.captures, tree.rootNode, and parent entry points described in the report. Determine how node identity and ancestry should be compared without relying on text, then document the supported approach with an example matching the reported nested data-test structure.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- javascript, node.js
- Domain
- tooling
- Issue type
- Documentation
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Needs clarification
- Newbie friendliness
- 25/100