Created
May 28, 2024 20:24
-
-
Save garlic0x1/5601aac58b1ded96ad2d4f90547983e6 to your computer and use it in GitHub Desktop.
Performing a query in tree-sitter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdint.h> | |
#include <stdio.h> | |
#include <tree_sitter/api.h> | |
#include <tree_sitter/tree-sitter-c.h> | |
int main() { | |
// Create a Tree-sitter parser | |
const TSLanguage *language = tree_sitter_c(); | |
TSParser *parser = ts_parser_new(); | |
ts_parser_set_language(parser, language); | |
// Parse some code | |
TSTree *tree = ts_parser_parse_string(parser, NULL, "int x = 5;", 10); | |
TSNode root_node = ts_tree_root_node(tree); | |
// Create a query | |
uint32_t error_offset = 0; | |
TSQueryError error_type = 0; | |
TSQuery *query = ts_query_new | |
(language, | |
"(declaration) @declarations", | |
27, | |
&error_offset, | |
&error_type); | |
// Run the query | |
TSQueryCursor *cursor = ts_query_cursor_new(); | |
ts_query_cursor_exec(cursor, query, root_node); | |
printf("error_offset: %d, error_type: %d\n", error_offset, error_type); | |
// Iterate over the results | |
TSQueryMatch match = (TSQueryMatch) {}; | |
while (ts_query_cursor_next_match(cursor, &match)) { | |
for (int i = 0; i < match.capture_count; i++) { | |
TSQueryCapture capture = match.captures[i]; | |
printf("match: %s\n", ts_node_string(capture.node)); | |
} | |
} | |
printf("done\n"); | |
// Clean up | |
ts_query_cursor_delete(cursor); | |
ts_query_delete(query); | |
ts_parser_delete(parser); | |
ts_language_delete(language); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment