From dffee22736ef89f606f0d02241f0dcb754890edf Mon Sep 17 00:00:00 2001 From: Niranjan Hasabnis Date: Sat, 15 May 2021 00:18:32 +0000 Subject: [PATCH] Adding API to get field name of a TSNode This PR adds an API to get name of the field of TSNode's child. It uses same set of arguments as that of ts_node_child, but returns field name if it is found, otherwise it returns NULL. This API is useful to implement custom printing of S-expressions such as following: "(binary_expression (binary_expression_left (identifier)) (binary_expression_operator ("+")) (binary_expression_right (identifier) )" Currently, ts_node_string does not allow any customization for printing. --- lib/include/tree_sitter/api.h | 6 ++++++ lib/src/node.c | 17 +++++++++++++++++ 2 files changed, 23 insertions(+) diff --git a/lib/include/tree_sitter/api.h b/lib/include/tree_sitter/api.h index 22837035..4633d069 100644 --- a/lib/include/tree_sitter/api.h +++ b/lib/include/tree_sitter/api.h @@ -487,6 +487,12 @@ TSNode ts_node_parent(TSNode); */ TSNode ts_node_child(TSNode, uint32_t); +/** + * Get the field_name for node's child at the given index, where zero represents + * the first child. Returns NULL, if no field is found. + */ +const char *ts_node_child_field_name(TSNode, uint32_t); + /** * Get the node's number of children. */ diff --git a/lib/src/node.c b/lib/src/node.c index 8498f9c5..faf02536 100644 --- a/lib/src/node.c +++ b/lib/src/node.c @@ -578,6 +578,23 @@ recur: return ts_node__null(); } +const char *ts_node_child_field_name(TSNode self, uint32_t child_index) { + const TSFieldMapEntry *field_map, *field_map_end; + ts_language_field_map( + self.tree->language, + ts_node__subtree(self).ptr->production_id, + &field_map, + &field_map_end + ); + + for (const TSFieldMapEntry *i = field_map; i < field_map_end; i++) { + if (i->child_index == child_index) { + return self.tree->language->field_names[i->field_id]; + } + } + return NULL; +} + TSNode ts_node_child_by_field_name( TSNode self, const char *name,