tree-sitter icon indicating copy to clipboard operation
tree-sitter copied to clipboard

`parent` of 0width node is `previousSibling`

Open RedCMD opened this issue 3 years ago • 2 comments

running node.parent on a 0width node returns the previous sibling instead of the parent

0width node: node.text == '' node is named

alias(
    token.immediate(
        repeat(
            choice(
                /\\./,
                /[^\\"\r\n]+/,
            ),
        ),
    ),
    $.value
),

RedCMD avatar Sep 16 '22 09:09 RedCMD

This also affects MISSING nodes, as they too are 0width

workaround is to create a function that detects 0width nodes and use .parent twice

/**
 * TreeSitter bug
 * Using `.parent` on a 0width node returns the `previousSilbing` rather than the `parent`
 * https://github.com/tree-sitter/tree-sitter/issues/1872
 */
export function trueParent(node: Parser.SyntaxNode): Parser.SyntaxNode {
	return node.text ? node.parent : node.parent?.parent;
}

EDIT: even this doesn't work correctly if the previous sibling has nested nodes, the parent of the bottom most nested node will be choosen

RedCMD avatar Jan 20 '24 02:01 RedCMD

related https://github.com/tree-sitter/tree-sitter/issues/3271 (C-Library)

RedCMD avatar Apr 20 '24 08:04 RedCMD