fix(lib): properly account for aliased root nodes and root nodes with

children in `ts_subtree_string`
This commit is contained in:
Amaan Qureshi 2024-03-18 02:50:01 -04:00
parent ab485da756
commit 24a68697ac
3 changed files with 21 additions and 6 deletions

View file

@ -439,7 +439,14 @@ const char *ts_node_grammar_type(TSNode self) {
}
char *ts_node_string(TSNode self) {
return ts_subtree_string(ts_node__subtree(self), self.tree->language, false);
TSSymbol alias_symbol = ts_node__alias(&self);
return ts_subtree_string(
ts_node__subtree(self),
alias_symbol,
ts_language_symbol_metadata(self.tree->language, alias_symbol).visible,
self.tree->language,
false
);
}
bool ts_node_eq(TSNode self, TSNode other) {

View file

@ -890,9 +890,15 @@ static size_t ts_subtree__write_to_string(
}
}
} else if (is_root) {
TSSymbol symbol = ts_subtree_symbol(self);
TSSymbol symbol = alias_symbol ? alias_symbol : ts_subtree_symbol(self);
const char *symbol_name = ts_language_symbol_name(language, symbol);
cursor += snprintf(*writer, limit, "(\"%s\")", symbol_name);
if (ts_subtree_child_count(self) > 0) {
cursor += snprintf(*writer, limit, "(%s", symbol_name);
} else if (ts_subtree_named(self)) {
cursor += snprintf(*writer, limit, "(%s)", symbol_name);
} else {
cursor += snprintf(*writer, limit, "(\"%s\")", symbol_name);
}
}
if (ts_subtree_child_count(self)) {
@ -947,6 +953,8 @@ static size_t ts_subtree__write_to_string(
char *ts_subtree_string(
Subtree self,
TSSymbol alias_symbol,
bool alias_is_named,
const TSLanguage *language,
bool include_all
) {
@ -954,13 +962,13 @@ char *ts_subtree_string(
size_t size = ts_subtree__write_to_string(
self, scratch_string, 1,
language, include_all,
0, false, ROOT_FIELD
alias_symbol, alias_is_named, ROOT_FIELD
) + 1;
char *result = ts_malloc(size * sizeof(char));
ts_subtree__write_to_string(
self, result, size,
language, include_all,
0, false, ROOT_FIELD
alias_symbol, alias_is_named, ROOT_FIELD
);
return result;
}

View file

@ -206,7 +206,7 @@ void ts_subtree_summarize(MutableSubtree, const Subtree *, uint32_t, const TSLan
void ts_subtree_summarize_children(MutableSubtree, const TSLanguage *);
void ts_subtree_balance(Subtree, SubtreePool *, const TSLanguage *);
Subtree ts_subtree_edit(Subtree, const TSInputEdit *edit, SubtreePool *);
char *ts_subtree_string(Subtree, const TSLanguage *, bool include_all);
char *ts_subtree_string(Subtree, TSSymbol, bool, const TSLanguage *, bool include_all);
void ts_subtree_print_dot_graph(Subtree, const TSLanguage *, FILE *);
Subtree ts_subtree_last_external_token(Subtree);
const ExternalScannerState *ts_subtree_external_scanner_state(Subtree self);