Building a Semantic Code Search Tool With Tree-Sitter and AST Queries
Build a semantic code search tool with Tree-Sitter and AST queries. Parse code, write S-expression queries, index symbols in Python and update incrementally.
By Galactic News Editorial · Published 2026-11-26T19:43:30+00:00 · Updated 2026-11-26T19:43:30+00:00
Building a Semantic Code Search Tool With Tree-Sitter and AST Queries
Text search finds words. It cannot tell a function definition from a comment that mentions the same word. A semantic code search tool fixes that. It parses code into an abstract syntax tree, then searches the tree. Tree-Sitter is the parser for the job. It is a parser generator and an incremental parsing library. This tutorial builds a working semantic search tool in eight steps, using Tree-Sitter and its query language.
Semantic code search Tree-Sitter: why the parser matters
Tree-Sitter builds a concrete syntax tree for a source file. It updates the tree efficiently as the file is edited. That incremental parsing is the key feature. A search index can stay fresh without re-parsing the whole codebase on every keystroke.
Tree-Sitter supports many languages. Each language has its own grammar repository, named tree-sitter followed by the language. The grammar lives in a file called grammar.js. The four main objects are languages, parsers, syntax trees, and syntax nodes. In C they are called TSLanguage, TSParser, TSTree, and TSNode. Bindings exist for Python, Rust, Go, JavaScript, Java, Kotlin, C#, Haskell, and Zig.
Queries are the second half. A Tree-Sitter query is an S-expression pattern. It matches nodes in the tree and captures them by name. That is how the search tool finds every function definition, every call site, and every class, instead of every matching string.
Step 1: Install the CLI and a grammar
Install the Tree-Sitter CLI. The simplest route is Cargo:
cargo install tree-sitter-cli --locked
You can also install it through npm or download a binary from the latest GitHub release. The CLI needs a JavaScript runtime, such as Node.js, and a C compiler. Tree-Sitter grammars are written in JavaScript. The generated parsers are written in C.
Next, clone a grammar. This tutorial uses Python:
git clone https://github.com/tree-sitter/tree-sitter-python.git
cd tree-sitter-python
tree-sitter generate
The generate command builds the parser in src/parser.c. Run tree-sitter init-config once to find the config file. It lists the parse-directories where the CLI looks for grammars.
Step 2: Parse a file and read the tree
Take a small Python file:
def sum(x: int, y: int) -> int:
return x + y
sum(1, 2)
Parse it with the CLI. The output shows the tree as nested S-expressions:
(module [0, 0] - [5, 0]
(function_definition [0, 0] - [1, 16]
name: (identifier [0, 4] - [0, 7])
parameters: (parameters [0, 7] - [0, 23]
...)
body: (block [1, 4] - [1, 16]
(return_statement ...)))
Each node carries a range. The format is [row, column] to [row, column]. Rows and columns start at 0. The end is exclusive. That range is what lets the search tool jump to the exact location of a match.
Step 3: Write your first AST query
Queries use S-expression syntax. A pattern names the node type. A capture binds the match to a name with @. This query finds every Python function definition and captures it:
(function_definition) @func
Fields narrow the match. This query finds functions with a return type annotation:
(function_definition
return_type: (type)) @has_return_type_func
An exclamation mark excludes a field. This query finds functions without a return type:
(function_definition
!return_type) @no_return_type_func
Anonymous nodes match by literal text. This query finds additions:
(binary_operator
operator: "+") @add_op
Quantifiers work like regex. The pattern below extracts every integer in a list, however many there are:
((integer) ("," (integer))*) @int_list
Predicates add conditions. This query matches the last element of a list only when it is the string "90":
(list (string) @last_str (#eq? @last_str "\"90\"") .)
The node-types.json file in each grammar is the authoritative reference for node types and fields. Read it before writing queries for a new language.
Step 4: Run queries from Python
The CLI is good for testing queries. A real tool needs a library. Install the Python binding and the Python grammar:
pip install tree-sitter
pip install tree-sitter-python
Parse code and run a query. This example extracts function arguments with their type hints:
import tree_sitter_python as tspython
from tree_sitter import Language, Parser, Query, QueryCursor
PY_LANGUAGE = Language(tspython.language())
code = """def sum(x: int, y: int) -> int:
return x + y
"""
parser = Parser(PY_LANGUAGE)
tree = parser.parse(bytes(code, encoding="utf8"))
query = Query(
PY_LANGUAGE,
"""(typed_parameter
(identifier) @name
type: (type (identifier) @val))""",
)
captures = QueryCursor(query).captures(tree.root_node)
for arg_name, arg_type in zip(captures["name"], captures["val"]):
print(f"{str(arg_name.text)}: {str(arg_type.text)}")
The root node type for a Python file is module. Each captured node has start_point and end_point properties. Those give the row and column for the search result.
Step 5: Build the index
Walk the repository. Parse each file with the grammar for its language. Run a small set of queries per language. Store one record per symbol.
Each record needs six fields: symbol name, symbol kind, file path, start row, start column, and the signature or enclosing scope. Function definitions, class definitions, method definitions, and call sites are the four queries that cover most searches.
Keep the index in a simple store first. A SQLite table works. One row per symbol is enough for a codebase of a few thousand files. Add a full-text index on the name column for prefix search.
Step 6: Add ranking and search
Semantic search still needs ranking. Score exact name matches first. Then prefix matches. Then matches in the same file or module as the query context. Then matches by call frequency, if you indexed call sites.
Keep the query interface simple. A search for sum should return the function definition, its file and line, and its signature. A search for a class name should return the class and its methods. The user picks the result. The tool opens the file at the right line.
Step 7: Handle edits incrementally
Re-parsing everything on every change is slow. Tree-Sitter supports incremental parsing. When a file changes, pass the old tree and the edit to the parser. It reuses the unchanged parts of the tree. Then re-run the queries for that file only and update its index rows.
This is the step that makes the tool feel instant. A full re-index runs once at startup. After that, only changed files are re-parsed. Watch the file system for changes and update the index in the background.
Step 8: Test, measure, and extend
Test the queries against real code before you trust them. Each grammar has quirks. A node type that exists in Python may not exist in JavaScript. Check node-types.json for every language you add.
Measure two things. Index build time for the whole repository. Query latency for a single search. Both should stay under a second for a small codebase. If the index build is slow, parse files in parallel. If queries are slow, narrow the query set per language.
Extensions come after the core works. Add a second language by adding its grammar and its query set. Add call-graph search by indexing call nodes with their function field. Add a language server protocol front end if you want editor integration.
Bottom line
Tree-Sitter turns code into a queryable tree. The query language turns the tree into search results. Eight steps get you there: install the CLI, parse a file, write queries, run them from Python, index the symbols, rank the results, handle edits incrementally, and test. Start with one language and four queries. Add languages only after the first one works end to end.