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

Query: Querying until node... "is not equal" #79

Closed caioliberali closed 3 years ago

caioliberali commented 3 years ago

Is it possible to query until node "is not equal", for example? I'm trying to query only the public fields in a C++ file.

Example: Tree-Sitter Playground

class MyClass
{
public:
    /** 1 Comment */
    int One;

    /** 2 Comment */
    int Two;

    int Three;
    int Four;

protected:
    /** Bool 1 Comment */
    bool bOne;
    /** Bool 2 Comment */
    bool bTwo;

    bool bThree;
    bool bFour;
};

Query:

(class_specifier name: (type_identifier) @className
        (field_declaration_list
            (access_specifier) @accessSpecifier
            (#eq? @accessSpecifier "public:")
            (
                ((comment)? @fieldComment .)?
                (field_declaration declarator: (field_identifier) @fieldName) 
            )
        )
    )

I doesn't return "protected:" accessor but still return its variables, but if I use another query, it starts from "protected:" accessor:

(class_specifier name: (type_identifier) @className
        (field_declaration_list
            (access_specifier) @accessSpecifier
            (#eq? @accessSpecifier "protected:")
            (
                ((comment)? @fieldComment .)?
                (field_declaration declarator: (field_identifier) @fieldName) 
            )
        )
    )

How could I solve this? Thank you.

ahlinc commented 3 years ago

@caioliberali It's not possible with the current implementation of this node binding to the tree-sitter C library cause this binding doesn't expose control for underling tree-sitter query cursor, it buffers all captures before return them to the JS code. If there would be such cursor control it would be possible to implement such stopping programmatically by capturing protected: specifier and stop to consume the cursor production.

ahlinc commented 3 years ago

@caioliberali I was partially wrong due to missing declarations in tree-sitter.d.ts file. There is a Query.captures(rootNode: SyntaxNode, startPosition?: Point, endPosition?: Point): QueryCapture[]; method so you can try to find position of the protected: specifier by another query and pass its position in your query to stop it.

caioliberali commented 3 years ago

Thank you very much @ahlinc !!