Skip to content

Instantly share code, notes, and snippets.

@vijfhoek
Created May 23, 2020 11:22
Show Gist options
  • Save vijfhoek/e116f184898eb017569b6dba4e86ee9f to your computer and use it in GitHub Desktop.
Save vijfhoek/e116f184898eb017569b6dba4e86ee9f to your computer and use it in GitHub Desktop.
#include <assert.h>
#include <string.h>
#include <stdio.h>
#include <tree_sitter/api.h>
#include <tree_sitter/highlight.h>
TSLanguage *tree_sitter_c();
int main() {
// Create a parser.
TSParser *parser = ts_parser_new();
// Set the parser's language (JSON in this case).
ts_parser_set_language(parser, tree_sitter_c());
// Build a syntax tree based on source code stored in a string.
const char *source_code = "#include <assert.h>\n"
"int main(int argc, char** argv) {\n"
" int a = 3 + argc;\n"
" printf(\"%d\\n\", a);\n"
"}\n";
TSTree *tree = ts_parser_parse_string(
parser,
NULL,
source_code,
strlen(source_code)
);
// Get the root node of the syntax tree.
TSNode root_node = ts_tree_root_node(tree);
char *string = ts_node_string(root_node);
printf("# Syntax tree:\n%s\n\n", string);
free(string);
printf("# Source:\n%s\n", source_code);
char highlights_query[4096] = {0};
FILE* f = fopen("tree-sitter-c/queries/highlights.scm", "r");
fread(highlights_query, sizeof(char), sizeof(highlights_query), f);
fclose(f);
uint32_t error_offset;
TSQueryError error_type;
const TSQuery* query = ts_query_new(
tree_sitter_c(),
highlights_query,
strlen(highlights_query),
&error_offset,
&error_type
);
if (query == NULL) {
printf("error at %d: %d\n", error_offset, error_type);
return 1;
}
TSQueryCursor* cursor = ts_query_cursor_new();
ts_query_cursor_exec(cursor, query, root_node);
TSQueryMatch match;
while (ts_query_cursor_next_match(cursor, &match)) {
printf("[%3d] index=%d: ", match.id, match.pattern_index);
for (int i = 0; i < match.capture_count; i++) {
TSQueryCapture capture = match.captures[i];
char* string = ts_node_string(capture.node);
TSPoint start = ts_node_start_point(capture.node);
TSPoint end = ts_node_end_point(capture.node);
printf("[%2d:%-2d - %2d:%-2d] %s ", start.row, start.column, end.row, end.column, string);
free(string);
}
puts("");
}
ts_tree_delete(tree);
ts_parser_delete(parser);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment