Introduction
Code analysis often requires finding specific patterns in source code. Tree-sitter provides a simple yet powerful pattern-matching language for this purpose, similar to what’s used in its unit test system. This allows you to express and search for code structures without writing complex parsing logic.Creating a Query
Create a query by specifying a string containing one or more patterns:const TSLanguage*
required
The language that the query is for
const char*
required
A string containing one or more S-expression patterns
uint32_t
required
The length of the source string in bytes
uint32_t*
If there’s an error, this will be set to the byte offset of the error
TSQueryError*
If there’s an error, this will be set to the error type
Error Types
Query Syntax Basics
Queries are written using S-expressions that match the structure of syntax trees:Simple Pattern
Pattern with Fields
Pattern with Predicates
Executing Queries
Creating a Query Cursor
TheTSQuery value is immutable and can be safely shared between threads. To execute the query, create a TSQueryCursor, which carries the state needed for processing:
Executing the Query
Execute the query on a given syntax node:Iterating Over Matches
false when there are no more matches. Otherwise, it populates the match with data about which pattern matched and which nodes were captured.
Complete Example
Iterating Over Captures
Instead of iterating over complete matches, you can iterate over individual captures in order:Setting Query Ranges
You can limit the range in which queries execute:The query cursor will return matches that intersect with the given range. A match may be returned even if some of its captures fall outside the specified range, as long as at least part of the match overlaps with the range.
Query Properties and Predicates
Queries support predicates for filtering matches:Text Predicates
Property Settings
Getting Predicate Information
Advanced Query Features
Query Introspection
Disabling Patterns and Captures
Match Limits
Next Steps
Query Syntax
Learn the complete query syntax
Query Predicates
Master predicates and directives
Static Node Types
Generate type information for queries