Skip to content

Commit

Permalink
Fix findAstAncestry when position is at eof
Browse files Browse the repository at this point in the history
  • Loading branch information
JohnnyMorganz committed May 18, 2022
1 parent f2191b9 commit 2a1849f
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 2 deletions.
20 changes: 18 additions & 2 deletions Analysis/src/AstQuery.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -71,9 +71,11 @@ struct FindFullAncestry final : public AstVisitor
{
std::vector<AstNode*> nodes;
Position pos;
Position documentEnd;

explicit FindFullAncestry(Position pos)
explicit FindFullAncestry(Position pos, Position documentEnd)
: pos(pos)
, documentEnd(documentEnd)
{
}

Expand All @@ -84,6 +86,16 @@ struct FindFullAncestry final : public AstVisitor
nodes.push_back(node);
return true;
}

// Edge case: If we ask for the node at the position that is the very end of the document
// return the innermost AST element that ends at that position.

if (node->location.end == documentEnd && pos >= documentEnd)
{
nodes.push_back(node);
return true;
}

return false;
}
};
Expand All @@ -92,7 +104,11 @@ struct FindFullAncestry final : public AstVisitor

std::vector<AstNode*> findAstAncestryOfPosition(const SourceModule& source, Position pos)
{
FindFullAncestry finder(pos);
const Position end = source.root->location.end;
if (pos > end)
pos = end;

FindFullAncestry finder(pos, end);
source.root->visit(&finder);
return std::move(finder.nodes);
}
Expand Down
13 changes: 13 additions & 0 deletions tests/AstQuery.test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -92,4 +92,17 @@ bar(foo())
CHECK_EQ("number", toString(*expectedOty));
}

TEST_CASE_FIXTURE(Fixture, "ast_ancestry_at_eof")
{
check(R"(
if true then
)");

std::vector<AstNode*> ancestry = findAstAncestryOfPosition(*getMainSourceModule(), Position(2, 3));
REQUIRE_GE(ancestry.size(), 2);
AstStat* parentStat = ancestry[ancestry.size() - 2]->asStat();
REQUIRE(bool(parentStat));
REQUIRE(parentStat->is<AstStatIf>());
}

TEST_SUITE_END();

0 comments on commit 2a1849f

Please sign in to comment.