Skip to content

Commit ab23e4a

Browse files
authored
Fix #720 (#if: wrong macro usage for macros defined before the #if) (#721)
1 parent 768e6c3 commit ab23e4a

2 files changed

Lines changed: 32 additions & 5 deletions

File tree

‎simplecpp.cpp‎

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3935,14 +3935,15 @@ void simplecpp::preprocess(simplecpp::TokenList &output, const simplecpp::TokenL
39353935
const bool par = (tok && tok->op == '(');
39363936
if (par)
39373937
tok = tok->next;
3938-
maybeUsedMacros[rawtok->next->str()].emplace_back(rawtok->next->location);
39393938
if (tok) {
3940-
if (macros.find(tok->str()) != macros.end())
3939+
if (macros.find(tok->str()) != macros.end()) {
3940+
maybeUsedMacros[tok->str()].emplace_back(tok->location);
39413941
expr.push_back(new Token("1", tok->location));
3942-
else if (hasInclude && tok->str() == HAS_INCLUDE)
3942+
} else if (hasInclude && tok->str() == HAS_INCLUDE) {
39433943
expr.push_back(new Token("1", tok->location));
3944-
else
3944+
} else {
39453945
expr.push_back(new Token("0", tok->location));
3946+
}
39463947
}
39473948
if (par)
39483949
tok = tok ? tok->next : nullptr;
@@ -4004,7 +4005,9 @@ void simplecpp::preprocess(simplecpp::TokenList &output, const simplecpp::TokenL
40044005
continue;
40054006
}
40064007

4007-
maybeUsedMacros[rawtok->next->str()].emplace_back(rawtok->next->location);
4008+
// usage of defined macros is recorded when they are expanded
4009+
if (macros.find(tok->str()) == macros.end())
4010+
maybeUsedMacros[tok->str()].emplace_back(tok->location);
40084011

40094012
const Token *tmp = tok;
40104013
if (!preprocessToken(expr, tmp, macros, files, outputList, dui)) {

‎test.cpp‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4697,6 +4697,30 @@ static void macroUsage()
46974697
ASSERT_EQUALS(2, it->useLocation.line);
46984698
ASSERT_EQUALS(8, it->useLocation.col);
46994699
}
4700+
{
4701+
const char code[] = "#define X 1\n"
4702+
"#if defined(X)\n"
4703+
"#endif\n";
4704+
std::list<simplecpp::MacroUsage> macroUsage;
4705+
ASSERT_EQUALS("", preprocess(code, &macroUsage));
4706+
ASSERT_EQUALS(1, macroUsage.size());
4707+
auto it = macroUsage.cbegin();
4708+
ASSERT_EQUALS("X", it->macroName);
4709+
ASSERT_EQUALS(2, it->useLocation.line);
4710+
ASSERT_EQUALS(13, it->useLocation.col);
4711+
}
4712+
{
4713+
const char code[] = "#define X 1\n"
4714+
"#if X\n"
4715+
"#endif\n";
4716+
std::list<simplecpp::MacroUsage> macroUsage;
4717+
ASSERT_EQUALS("", preprocess(code, &macroUsage));
4718+
ASSERT_EQUALS(1, macroUsage.size());
4719+
auto it = macroUsage.cbegin();
4720+
ASSERT_EQUALS("X", it->macroName);
4721+
ASSERT_EQUALS(2, it->useLocation.line);
4722+
ASSERT_EQUALS(5, it->useLocation.col);
4723+
}
47004724
}
47014725

47024726
static void isAbsolutePath() {

0 commit comments

Comments
 (0)