Code analysis often requires finding specific patterns in source code. Tree-sitter provides a simple 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.Documentation Index
Fetch the complete documentation index at: https://mintlify.com/tree-sitter/tree-sitter/llms.txt
Use this file to discover all available pages before exploring further.
What are Queries?
A query consists of one or more patterns, where each pattern is an S-expression that matches a certain set of nodes in a syntax tree. Queries enable you to:- Find specific code patterns across large codebases
- Extract information from syntax trees
- Power features like syntax highlighting, code navigation, and refactoring
- Identify code smells or potential bugs
Queries are used extensively in Tree-sitter’s unit testing system, making them a battle-tested tool for pattern matching.
Basic Query Structure
The expression to match a given node consists of a pair of parentheses containing:- The node’s type
- Optionally, a series of other S-expressions that match the node’s children
binary_expression node whose children are both number_literal nodes:
Query Components
Tree-sitter queries support several powerful features:Syntax
Learn the basic syntax for writing patterns, including fields, anonymous nodes, and special nodes
Operators
Discover operators for capturing nodes, quantification, grouping, and anchoring
Predicates
Add conditions and metadata to patterns using predicates and directives
API Reference
Reference for the C API to create and execute queries programmatically
Use Cases
Queries are the foundation for many Tree-sitter-powered features:- Syntax Highlighting: Match language constructs to apply appropriate colors
- Code Navigation: Find definitions, references, and symbols
- Refactoring: Identify and transform code patterns
- Linting: Detect problematic code patterns
- Code Search: Find complex structural patterns beyond text search
Getting Started
To start writing queries, you’ll need:- A Tree-sitter parser for your target language
- Understanding of the grammar’s node types and structure
- Knowledge of query syntax and operators
Next Steps
Learn Query Syntax
Start with the Query Syntax page to understand how to write basic patterns
Master Operators
Explore Query Operators to capture nodes and create complex patterns
Add Conditions
Use Predicates to filter matches and add metadata
Integrate Queries
Reference the Query API to execute queries in your application