Skip to content

Commit 9db6bfd

Browse files
committed
Ignore whitespace at the end of a macro replacement list when stringifying
The last token of an expansion got whitespaceahead from the newline or comment after the replacement list. Use the whitespace after the macro call instead. 'xstr(MAJOR.MINOR)' with '#define MAJOR 1/*major*/' now gives "1.2", and 'xstr(F(a)b)' gives "ab".
1 parent 2e16061 commit 9db6bfd

2 files changed

Lines changed: 33 additions & 1 deletion

File tree

‎simplecpp.cpp‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2191,7 +2191,14 @@ namespace simplecpp {
21912191
if (!parametertokens1.empty())
21922192
parametertokens1.swap(parametertokens2);
21932193

2194-
return functionLike() ? parametertokens2.back()->next : nameTokInst->next;
2194+
const Token * const callEnd = functionLike() ? parametertokens2.back() : nameTokInst;
2195+
2196+
// Whitespace at the end of the replacement list does not count.
2197+
// The expansion is followed by the whitespace after the macro call.
2198+
if (output.back() && output.back() != output_end_1)
2199+
output.back()->whitespaceahead = callEnd->whitespaceahead;
2200+
2201+
return callEnd->next;
21952202
}
21962203

21972204
/** Returns the macro to expand when the last token of @p temp is the name of a

‎test.cpp‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1756,6 +1756,30 @@ static void hashComment()
17561756
"\"a/**/b\"", preprocess(code));
17571757
}
17581758

1759+
static void hashMacroTrailingWhitespace()
1760+
{
1761+
// whitespace at the end of a replacement list does not count
1762+
simplecpp::DUI dui;
1763+
dui.removeComments = true;
1764+
const char code[] = "#define str(x) #x\n"
1765+
"#define xstr(x) str(x)\n"
1766+
"#define MAJOR 1/*major*/\n"
1767+
"#define MINOR 2 \n"
1768+
"#define F(x) x\n"
1769+
"#define G F(a)\n"
1770+
"xstr(MAJOR.MINOR)\n"
1771+
"xstr(F(a)b)\n"
1772+
"xstr(F(a) b)\n"
1773+
"xstr(G.b)\n"
1774+
"xstr(G b)";
1775+
ASSERT_EQUALS("\n\n\n\n\n\n"
1776+
"\"1.2\"\n"
1777+
"\"ab\"\n"
1778+
"\"a b\"\n"
1779+
"\"a.b\"\n"
1780+
"\"a b\"", preprocess(code, dui));
1781+
}
1782+
17591783
static void hashEscapeTrailingBackslash()
17601784
{
17611785
// an odd number of trailing backslashes would escape the closing quote,
@@ -4862,6 +4886,7 @@ static void runTests(int argc, char **argv, Input input)
48624886
TEST_CASE(hash);
48634887
TEST_CASE(hashEscape);
48644888
TEST_CASE(hashComment);
4889+
TEST_CASE(hashMacroTrailingWhitespace);
48654890
TEST_CASE(hashEscapeTrailingBackslash);
48664891
TEST_CASE(hashhash1);
48674892
TEST_CASE(hashhash2);

0 commit comments

Comments
 (0)