Skip to content

Commit

Permalink
Make comment removal a single pass
Browse files Browse the repository at this point in the history
  • Loading branch information
Blake-Madden committed Nov 30, 2023
1 parent 5887ac2 commit 6d8d958
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 21 deletions.
31 changes: 31 additions & 0 deletions tests/tetests.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2420,6 +2420,37 @@ COMBIN(15,
3)
)");

tep.compile((
R"(//
//Combination
COMBIN(15,
//
3)
//)"));
CHECK(455 == tep.evaluate());
CHECK(tep.get_expression() ==
R"(
COMBIN(15,
3)
)");

// stray '/' at the end, bounds check
tep.compile((
R"(//Combination
COMBIN(15,
//The first argument
3)
/)"));
CHECK(std::isnan(tep.evaluate()));
CHECK(tep.get_expression() ==
R"(
COMBIN(15,
3)
/)");
}
}

Expand Down
44 changes: 23 additions & 21 deletions tinyexpr.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1323,36 +1323,38 @@ bool te_parser::compile(const std::string_view expression)
if (m_expression.length() && m_expression.front() == '=')
{ m_expression.erase(0, 1); }

// remove multi-line comments
size_t commentStart{ 0 };
while (commentStart != std::string::npos)
{
commentStart = m_expression.find("/*", commentStart);
if (commentStart == std::string::npos)
commentStart = m_expression.find('/', commentStart);
if (commentStart == std::string::npos ||
commentStart == m_expression.length() - 1)
{ break; }
auto commentEnd = m_expression.find("*/", commentStart);
if (commentEnd == std::string::npos)
// remove multi-line comments
if (m_expression[commentStart + 1] == '*')
{
m_errorPos = commentStart;
return te_nan;
auto commentEnd = m_expression.find("*/", commentStart);
if (commentEnd == std::string::npos)
{
m_errorPos = commentStart;
return te_nan;
}
m_expression.erase(commentStart, (commentEnd + 2) - commentStart);
}
m_expression.erase(commentStart, (commentEnd + 2) - commentStart);
}
// remove single-line comments
commentStart = 0;
while (commentStart != std::string::npos)
{
commentStart = m_expression.find("//", commentStart);
if (commentStart == std::string::npos)
{ break; }
auto commentEnd = m_expression.find_first_of("\n\r", commentStart);
if (commentEnd == std::string::npos)
// remove single-line comments
else if (m_expression[commentStart + 1] == '/')
{
m_expression.erase(commentStart);
break;
auto commentEnd = m_expression.find_first_of("\n\r", commentStart);
if (commentEnd == std::string::npos)
{
m_expression.erase(commentStart);
break;
}
else
{ m_expression.erase(commentStart, commentEnd - commentStart); }
}
else
{ m_expression.erase(commentStart, commentEnd - commentStart); }
{ break; }
}

try
Expand Down

0 comments on commit 6d8d958

Please sign in to comment.