Skip to content

Instantly share code, notes, and snippets.

@casouri
Created December 31, 2021 01:57
Show Gist options
  • Save casouri/14ef96fb201eff28993b1e44f73de926 to your computer and use it in GitHub Desktop.
Save casouri/14ef96fb201eff28993b1e44f73de926 to your computer and use it in GitHub Desktop.
#include <string.h>
#include <stdio.h>
#include <tree_sitter/api.h>
#include <stdlib.h>
TSLanguage *tree_sitter_c();
struct buffer {
char *buf;
long len;
};
const char *read_file(void *payload, uint32_t byte_index,
TSPoint position, uint32_t *bytes_read) {
long len = ((struct buffer *) payload)->len;
if (byte_index >= len) {
*bytes_read = 0;
return (char *) "";
} else {
*bytes_read = len - byte_index;
return (char *) (((struct buffer *) payload)->buf) + byte_index;
}
}
int main() {
ts_set_allocator(malloc, calloc, realloc, free);
TSParser *parser = ts_parser_new();
ts_parser_set_language(parser, tree_sitter_c());
/* Copy the file into BUFFER. */
FILE *file = fopen("xdisp.c", "rb");
fseek(file, 0, SEEK_END);
long length = ftell (file);
fseek(file, 0, SEEK_SET);
char *buffer = malloc (length);
fread(buffer, 1, length, file);
fclose (file);
struct buffer buf = {buffer, length};
TSInput input = {&buf, read_file, TSInputEncodingUTF8};
TSTree *tree = ts_parser_parse(parser, NULL, input);
TSTree *new_tree = ts_parser_parse(parser, tree, input);
free(buffer);
ts_tree_delete(tree);
ts_tree_delete(new_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