getSnippetUpTo: Return optional

This makes it possible to certain discern failures from empty
snippets, which I think is an ok review comment.

Maybe it should do so for swapped column indexes too, but I'm not
sure.

I don't think it matters in the grand scheme. We don't even have
a real use case for `nullopt` now anyway.

Since we don't have a use case, I'm not applying this logic to
higher level functions yet.
This commit is contained in:
Robert Hensing 2024-07-15 20:08:41 +02:00
parent 03d33703ef
commit 61a4d3d45c
4 changed files with 10 additions and 8 deletions

View file

@ -646,7 +646,7 @@ size_t SymbolTable::totalSize() const
std::string DocComment::getInnerText(const PosTable & positions) const {
auto beginPos = positions[begin];
auto endPos = positions[end];
auto docCommentStr = beginPos.getSnippetUpTo(endPos);
auto docCommentStr = beginPos.getSnippetUpTo(endPos).value_or("");
// Strip "/**" and "*/"
constexpr size_t prefixLen = 3;

View file

@ -110,11 +110,11 @@ void Pos::LinesIterator::bump(bool atFirst)
input.remove_prefix(eol);
}
std::string Pos::getSnippetUpTo(const Pos & end) const {
std::optional<std::string> Pos::getSnippetUpTo(const Pos & end) const {
assert(this->origin == end.origin);
if (end.line < this->line)
return "";
return std::nullopt;
if (auto source = getSource()) {
@ -152,7 +152,7 @@ std::string Pos::getSnippetUpTo(const Pos & end) const {
}
return result;
}
return "";
return std::nullopt;
}

View file

@ -64,7 +64,7 @@ struct Pos
bool operator==(const Pos & rhs) const = default;
auto operator<=>(const Pos & rhs) const = default;
std::string getSnippetUpTo(const Pos & end) const;
std::optional<std::string> getSnippetUpTo(const Pos & end) const;
/**
* Get the SourcePath, if the source was loaded from a file.

View file

@ -25,7 +25,7 @@ TEST(Position, getSnippetUpTo_1)
ASSERT_EQ(start.getSnippetUpTo(start), "");
ASSERT_EQ(start.getSnippetUpTo(end), "x");
ASSERT_EQ(end.getSnippetUpTo(end), "");
ASSERT_EQ(end.getSnippetUpTo(start), "");
ASSERT_EQ(end.getSnippetUpTo(start), std::nullopt);
}
{
// NOTE: line and column are actually 1-based indexes
@ -37,7 +37,7 @@ TEST(Position, getSnippetUpTo_1)
ASSERT_EQ(start.getSnippetUpTo(end), "");
ASSERT_EQ(end.getSnippetUpTo(end), "");
ASSERT_EQ(end.getSnippetUpTo(start), "");
ASSERT_EQ(end.getSnippetUpTo(start), std::nullopt);
}
{
Pos start(1, 1, o);
@ -53,7 +53,7 @@ TEST(Position, getSnippetUpTo_1)
ASSERT_EQ(start.getSnippetUpTo(start), "");
ASSERT_EQ(start.getSnippetUpTo(end), "x");
ASSERT_EQ(end.getSnippetUpTo(end), "");
ASSERT_EQ(end.getSnippetUpTo(start), "");
ASSERT_EQ(end.getSnippetUpTo(start), std::nullopt);
}
}
TEST(Position, getSnippetUpTo_2)
@ -65,6 +65,8 @@ TEST(Position, getSnippetUpTo_2)
ASSERT_EQ(start.getSnippetUpTo(start), "");
ASSERT_EQ(start.getSnippetUpTo(end), "a");
ASSERT_EQ(end.getSnippetUpTo(end), "");
// nullopt? I feel like changing the column handling would just make it more fragile
ASSERT_EQ(end.getSnippetUpTo(start), "");
}
{