Tree class represents the syntactic structure of a source code file. It is returned by the Parser.parse() method and provides access to the root node of the syntax tree.
Properties
rootNode
Get the root node of the syntax tree.
language
The language that was used to parse the syntax tree.
Methods
copy()
Create a shallow copy of the syntax tree. This is very fast.
Tree instance that shares the same internal data
Example:
Copying a tree is useful when you need to keep multiple versions around for comparison or to preserve a tree before editing.
delete()
Delete the syntax tree and free its resources.
edit(edit)
Edit the syntax tree to keep it in sync with source code that has been edited.
edit- AnEditobject describing the change in both byte offsets and row/column coordinates
After calling
edit(), you should pass the tree to parser.parse() as the second argument. This allows the parser to reuse parts of the old tree, making parsing much faster.walk()
Create a new TreeCursor starting from the root of the tree.
TreeCursor positioned at the root node
Example:
Using a cursor is more efficient than recursively accessing nodes via properties, especially for deep traversals.
rootNodeWithOffset(offsetBytes, offsetExtent)
Get the root node with its position shifted forward by the given offset.
offsetBytes- The byte offset to addoffsetExtent- The position offset to add
Node representing the root, but with adjusted positions
Example:
This is useful when parsing embedded languages or when you need to map tree positions to different offsets in a larger document.
getChangedRanges(other)
Compare this edited syntax tree to a new syntax tree representing the same document, returning the ranges whose syntactic structure has changed.
other- The new tree to compare against
Range objects representing the changed regions
Example:
For this to work correctly, you must call
tree.edit() on the old tree before re-parsing. The ranges returned represent the minimal set of changes needed to update any cached information based on the tree.getIncludedRanges()
Get the ranges of text that were included when parsing the syntax tree.
Range objects that were used during parsing
Example:
Edit Class
TheEdit class represents an edit operation and provides helper methods for editing points and ranges.
Constructor
Properties
Methods
editPoint(point, index)
Edit a point and index to keep them in sync with an edit operation.
editRange(range)
Edit a range to keep it in sync with an edit operation.
Usage Patterns
Incremental Parsing
The most common use of tree editing is for incremental parsing:Preserving Trees
Usecopy() when you need to keep multiple versions:
See Also
- Parser class - Creating and using parsers
- Node class - Working with tree nodes
- Query API - Querying syntax trees