Skip to content

Commit ef7712e

Browse files
rikardfalkeborndanmar
authored andcommitted
Fix cppcheck-opensource#120 (handle multiline character literals) (cppcheck-opensource#180)
Make simplecpp accept the following code: const char*ptr="\\ \n"; Output from simplecpp: const char * ptr = "\\n" ; Output from gcc -E: const char* ptr = "\\n"; Do this by extending the special casing for backslashes to read all consecutive backslashes before continuing.
1 parent 4fb271d commit ef7712e

2 files changed

Lines changed: 22 additions & 6 deletions

File tree

simplecpp.cpp

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1133,12 +1133,20 @@ std::string simplecpp::TokenList::readUntil(std::istream &istr, const Location &
11331133
backslash = false;
11341134
ret += ch;
11351135
if (ch == '\\') {
1136-
const char next = readChar(istr, bom);
1137-
if (next == '\r' || next == '\n') {
1138-
ret.erase(ret.size()-1U);
1139-
backslash = (next == '\r');
1140-
}
1141-
ret += next;
1136+
bool update_ch = false;
1137+
char next = 0;
1138+
do {
1139+
next = readChar(istr, bom);
1140+
if (next == '\r' || next == '\n') {
1141+
ret.erase(ret.size()-1U);
1142+
backslash = (next == '\r');
1143+
update_ch = false;
1144+
} else if (next == '\\')
1145+
update_ch = !update_ch;
1146+
ret += next;
1147+
} while (next == '\\');
1148+
if (update_ch)
1149+
ch = next;
11421150
}
11431151
}
11441152

test.cpp

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1229,6 +1229,13 @@ static void multiline9() // multiline prefix string in macro
12291229
ASSERT_EQUALS("\n\nu8\"a b\" ;", preprocess(code));
12301230
}
12311231

1232+
static void multiline10() // multiline string literal
1233+
{
1234+
const char code[] = "const char *ptr = \"\\\\\n"
1235+
"\\n\";";
1236+
ASSERT_EQUALS("const char * ptr = \"\\\\n\"\n;", preprocess(code));
1237+
}
1238+
12321239
static void nullDirective1()
12331240
{
12341241
const char code[] = "#\n"
@@ -1947,6 +1954,7 @@ int main(int argc, char **argv)
19471954
TEST_CASE(multiline7); // multiline string in macro
19481955
TEST_CASE(multiline8); // multiline prefix string in macro
19491956
TEST_CASE(multiline9); // multiline prefix string in macro
1957+
TEST_CASE(multiline10);
19501958

19511959
TEST_CASE(readfile_nullbyte);
19521960
TEST_CASE(readfile_char);

0 commit comments

Comments
 (0)