Skip to main content

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

Matches all function declarations.

Pattern with Fields

Matches function declarations and captures the name and body with labels.

Pattern with Predicates

Matches identifiers that look like constants (all uppercase).

Executing Queries

Creating a Query Cursor

The TSQuery value is immutable and can be safely shared between threads. To execute the query, create a TSQueryCursor, which carries the state needed for processing:
The query cursor should not be shared between threads, but can be reused for many query executions.

Executing the Query

Execute the query on a given syntax node:

Iterating Over Matches

This function returns 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:
This is useful when you don’t care about which pattern matched and just want a single ordered sequence of captures.

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

This prevents patterns or captures from matching and reduces resource usage.

Match Limits

Set a maximum number of in-progress matches to prevent excessive memory usage.

Next Steps

Query Syntax

Learn the complete query syntax

Query Predicates

Master predicates and directives

Static Node Types

Generate type information for queries