tree-sitter / node-tree-sitter

Node.js bindings for tree-sitter
https://www.npmjs.com/package/tree-sitter
MIT License
649 stars 114 forks source link

Help: How to edit a single AST? #77

Closed Himujjal closed 3 years ago

Himujjal commented 3 years ago

In a certain use case, I need to edit the AST to enclose a for-loop in a statment_block for tree-sitter-javascript:

Before:

// ...preceding blocks
for(let i = 0; i < 10; i++) {
  // ...for body
}
// ...succeeding blocks

After:

// ...preceding blocks
{ for(let i = 0; i < 10; i++) {
  // ...for body
} }
// ...succeeding blocks

Is it possible to edit the AST this way using tree-sitter-node? If yes. How do I do it? Currently, the only way I see is to create a new StatementBlockNode object and then attach it to the tree. In the after case, I don't care about the row and column numbers.

ahlinc commented 3 years ago

@Himujjal It's not possible to edit tree-sitter's AST cause it runs counter to tree-sitter abilities like cheap syntax tree edits, recovering after errors and precise nodes position tracking. There only one way is to edit grammar.js file so the tree-sitter would build a different syntax tree by itself.

Himujjal commented 3 years ago

Cool no problem. I anyways got the problem solved. Thanks for your help. We can close this issue.