2014-02-18 09:07:00 -08:00
|
|
|
#include "tree_sitter/runtime.h"
|
2014-02-19 18:58:28 -08:00
|
|
|
#include <string>
|
2014-01-07 21:50:32 -08:00
|
|
|
#include <string.h>
|
2013-12-17 13:14:41 -08:00
|
|
|
|
2014-02-19 18:58:28 -08:00
|
|
|
using std::string;
|
|
|
|
|
|
2014-02-20 13:30:43 -08:00
|
|
|
ts_tree * ts_tree_make(ts_symbol value, size_t child_count, ts_tree **children) {
|
|
|
|
|
ts_tree *result = new ts_tree();
|
2014-01-07 21:50:32 -08:00
|
|
|
result->value = value;
|
|
|
|
|
result->child_count = child_count;
|
|
|
|
|
result->children = children;
|
2014-02-19 18:58:28 -08:00
|
|
|
result->ref_count = 0;
|
2014-01-07 21:50:32 -08:00
|
|
|
for (int i = 0; i < child_count; i++)
|
2014-02-20 13:30:43 -08:00
|
|
|
ts_tree_retain(children[i]);
|
2013-12-17 13:14:41 -08:00
|
|
|
return result;
|
2014-01-07 21:50:32 -08:00
|
|
|
}
|
|
|
|
|
|
2014-02-20 13:30:43 -08:00
|
|
|
void ts_tree_retain(ts_tree *tree) {
|
2014-01-07 21:50:32 -08:00
|
|
|
tree->ref_count++;
|
|
|
|
|
}
|
|
|
|
|
|
2014-02-20 13:30:43 -08:00
|
|
|
void ts_tree_release(ts_tree *tree) {
|
2014-01-07 21:50:32 -08:00
|
|
|
tree->ref_count--;
|
|
|
|
|
if (tree->ref_count == 0) {
|
|
|
|
|
for (int i = 0; i < tree->child_count; i++)
|
2014-02-20 13:30:43 -08:00
|
|
|
ts_tree_release(tree->children[i]);
|
2014-01-07 21:50:32 -08:00
|
|
|
free(tree);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2014-02-20 13:30:43 -08:00
|
|
|
int ts_tree_equals(const ts_tree *node1, const ts_tree *node2) {
|
2014-01-07 21:50:32 -08:00
|
|
|
if (node1->value != node2->value) return 0;
|
|
|
|
|
if (node1->child_count != node2->child_count) return 0;
|
|
|
|
|
for (int i = 0; i < node1->child_count; i++) {
|
2014-02-20 13:30:43 -08:00
|
|
|
ts_tree *child1 = node1->children[i];
|
|
|
|
|
ts_tree *child2 = node2->children[i];
|
|
|
|
|
if (!ts_tree_equals(child1, child2)) return 0;
|
2014-01-07 21:50:32 -08:00
|
|
|
}
|
|
|
|
|
return 1;
|
|
|
|
|
}
|
|
|
|
|
|
2014-02-20 13:30:43 -08:00
|
|
|
static string __tree_to_string(const ts_tree *tree, const char **symbol_names) {
|
2014-02-19 18:58:28 -08:00
|
|
|
if (!tree) return "#<null-tree>";
|
|
|
|
|
string result = string("(") + symbol_names[tree->value];
|
|
|
|
|
for (int i = 0; i < tree->child_count; i++)
|
|
|
|
|
result += " " + __tree_to_string(tree->children[i], symbol_names);
|
|
|
|
|
return result + ")";
|
2014-01-07 21:50:32 -08:00
|
|
|
}
|
|
|
|
|
|
2014-02-20 13:30:43 -08:00
|
|
|
char * ts_tree_string(const ts_tree *tree, const char **symbol_names) {
|
2014-02-19 18:58:28 -08:00
|
|
|
string value(__tree_to_string(tree, symbol_names));
|
|
|
|
|
char *result = (char *)malloc(value.size());
|
|
|
|
|
strcpy(result, value.c_str());
|
|
|
|
|
return result;
|
2014-01-07 21:50:32 -08:00
|
|
|
}
|