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,