From 1535ebd21caf616566f2f03989086f4fc93c0a3b Mon Sep 17 00:00:00 2001 From: Max Brunsfeld Date: Mon, 25 Aug 2014 11:28:09 -0700 Subject: [PATCH] Handle null parent in {next,prev}_sibling --- spec/runtime/node_spec.cc | 9 +++++++++ src/runtime/node.c | 10 ++++++++-- 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/spec/runtime/node_spec.cc b/spec/runtime/node_spec.cc index 24f389a6..f003caa0 100644 --- a/spec/runtime/node_spec.cc +++ b/spec/runtime/node_spec.cc @@ -73,6 +73,10 @@ describe("Node", []() { ts_node_release(array); ts_node_release(number); }); + + it("returns null if the node has no parent", [&]() { + AssertThat(ts_node_parent(root), Equals(nullptr)); + }); }); describe("next_sibling and prev_sibling", [&]() { @@ -90,6 +94,11 @@ describe("Node", []() { ts_node_release(number2); ts_node_release(number3); }); + + it("returns null when the node has no parent", [&]() { + AssertThat(ts_node_next_sibling(root), Equals(nullptr)); + AssertThat(ts_node_prev_sibling(root), Equals(nullptr)); + }); }); describe("find_for_range", [&]() { diff --git a/src/runtime/node.c b/src/runtime/node.c index b6b94117..c42de7d6 100644 --- a/src/runtime/node.c +++ b/src/runtime/node.c @@ -53,11 +53,17 @@ const char *ts_node_string(const TSNode *node) { TSNode *ts_node_parent(TSNode *child) { return child->parent; } TSNode *ts_node_prev_sibling(TSNode *child) { - return ts_node_child(child->parent, child->index - 1); + if (child->parent) + return ts_node_child(child->parent, child->index - 1); + else + return NULL; } TSNode *ts_node_next_sibling(TSNode *child) { - return ts_node_child(child->parent, child->index + 1); + if (child->parent) + return ts_node_child(child->parent, child->index + 1); + else + return NULL; } size_t ts_node_child_count(const TSNode *parent) {