aboutsummaryrefslogtreecommitdiffstats
path: root/app/tree_sitter.c
blob: d0f9fa8dd39217e5c4e662d34d49cdd6992aeee8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#include "string.h"
#include "tree_sitter/api.h"

typedef struct Node {
  TSPoint start_point;
  TSPoint end_point;
  uint32_t start_byte;
  uint32_t end_byte;
} Node;

void extract_comments(
  TSLanguage* language,
  char* input,
  Node** out,
  uint32_t* out_len
) {
  TSParser* parser = ts_parser_new();
  ts_parser_set_language(parser, language);
  TSTree* tree = ts_parser_parse_string(parser, NULL, input, strlen(input));
  TSNode root_node = ts_tree_root_node(tree);

  char* pattern = "(comment) @comment";
  uint32_t error_offset;
  TSQueryError error_type;
  TSQuery* query = ts_query_new(language, pattern, strlen(pattern), &error_offset, &error_type);
  TSQueryCursor* query_cursor = ts_query_cursor_new();
  ts_query_cursor_exec(query_cursor, query, root_node);

  TSQueryMatch query_match;
  uint32_t n_max = 1024;
  *out = malloc(sizeof(Node) * n_max);
  Node* node = *out;
  uint32_t n = 0;
  while (ts_query_cursor_next_match(query_cursor, &query_match)) {
    if (n >= n_max) {
      n_max *= 2;
      *out = realloc(*out, sizeof(Node) * n_max);
      node = *out + n;
    }
    TSNode captured_node = query_match.captures[0].node;
    node->start_byte = ts_node_start_byte(captured_node);
    node->end_byte = ts_node_end_byte(captured_node);
    node->start_point = ts_node_start_point(captured_node);
    node->end_point = ts_node_end_point(captured_node);
    node++; n++;
  }
  *out_len = n;

  ts_query_cursor_delete(query_cursor);
  ts_query_delete(query);
  ts_tree_delete(tree);
  ts_parser_delete(parser);
}

void ts_tree_root_node_p(TSTree *tree, TSNode *node) {
  (*node) = ts_tree_root_node(tree);
}

uint32_t ts_node_named_child_count_p(TSNode *node) {
  return ts_node_named_child_count(*node);
}

uint32_t ts_node_start_byte_p(TSNode *node) {
  return ts_node_start_byte(*node);
}

uint32_t ts_node_end_byte_p(TSNode *node) {
  return ts_node_end_byte(*node);
}

uint32_t ts_node_start_point_p(TSNode *node, TSPoint *point) {
  (*point) = ts_node_start_point(*node);
}

uint32_t ts_node_end_point_p(TSNode *node, TSPoint *point) {
  (*point) = ts_node_end_point(*node);
}

const char* ts_node_type_p(TSNode *node) {
  return ts_node_type(*node);
}

void ts_node_named_child_p(TSNode* self, uint32_t child_index, TSNode* node) {
  (*node) = ts_node_named_child(*self, child_index);
}