Skip to content

Commit b37f01c

Browse files
dmcppcheckclaude
andcommitted
Fix #756: ## with a prefixed literal or a raw prefix and a char literal is an error
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
1 parent 2a51846 commit b37f01c

2 files changed

Lines changed: 24 additions & 3 deletions

File tree

‎simplecpp.cpp‎

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2919,9 +2919,18 @@ namespace simplecpp {
29192919
if (isPunctuatorOperand(A) && !isValidPunctuatorPaste(A->str() + B->str()))
29202920
throw invalidHashHash::cannotCombine(loc, macroName, A, B);
29212921
// a name or number followed by a literal: only an encoding prefix such as L or u8 is valid
2922-
if ((A->name || A->number) && (isStringLiteral(B->str()) || isCharLiteral(B->str())) &&
2923-
!(A->name && isStringLiteralPrefix(A->str())))
2924-
throw invalidHashHash::cannotCombine(loc, macroName, A, B);
2922+
if (A->name || A->number) {
2923+
const std::string &b = B->str();
2924+
const std::string::size_type quote = b.find_first_of("\"\'");
2925+
if (quote == std::string::npos || b.size() < quote + 2 || b.back() != b[quote] ||
2926+
(quote > 0 && !isStringLiteralPrefix(b.substr(0, quote))))
2927+
return;
2928+
const bool isChar = b[quote] == '\'';
2929+
const bool validPrefix = A->name && quote == 0 && isStringLiteralPrefix(A->str()) &&
2930+
!(isChar && A->str().back() == 'R');
2931+
if (!validPrefix)
2932+
throw invalidHashHash::cannotCombine(loc, macroName, A, B);
2933+
}
29252934
}
29262935

29272936
/**

‎test.cpp‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2579,6 +2579,17 @@ static void hashhash_encoding_prefix()
25792579
ASSERT_EQUALS("", toString(outputList));
25802580
}
25812581

2582+
static void hashhash_invalid_prefixed_literal()
2583+
{
2584+
const char *const codes[] = {"cat(a,L\"s\")", "cat(a,u8\"s\")", "cat(L,L\"s\")", "cat(R,'c')", "cat(u8R,'c')"};
2585+
for (const char *line : codes) {
2586+
const std::string code = std::string("#define cat(a,b) a##b\n") + line + "\n";
2587+
simplecpp::OutputList outputList;
2588+
ASSERT_EQUALS("", preprocess(code.c_str(), &outputList));
2589+
ASSERT_EQUALS(true, toString(outputList).find("yields an invalid token") != std::string::npos);
2590+
}
2591+
}
2592+
25822593
static void hashhash_va_args_unexpected()
25832594
{
25842595
const char code[] =
@@ -5711,6 +5722,7 @@ static void runTests(int argc, char **argv, Input input)
57115722
TEST_CASE(hashhash_invalid_name_string);
57125723
TEST_CASE(hashhash_invalid_number_string);
57135724
TEST_CASE(hashhash_encoding_prefix);
5725+
TEST_CASE(hashhash_invalid_prefixed_literal);
57145726
TEST_CASE(hashhash_va_args_unexpected);
57155727

57165728
// C standard, 5.1.1.2, paragraph 4:

0 commit comments

Comments
 (0)