Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 9 additions & 2 deletions clang/lib/Format/UnwrappedLineParser.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1102,11 +1102,18 @@ void UnwrappedLineParser::parsePPIf(bool IfDef) {
conditionalCompilationStart(Unreachable);
FormatToken *IfCondition = FormatTok;
// If there's a #ifndef on the first line, and the only lines before it are
// comments, it could be an include guard.
// comments or #pragma once, it could be an include guard.
bool MaybeIncludeGuard = IfNDef;
if (IncludeGuard == IG_Inited && MaybeIncludeGuard) {
for (auto &Line : Lines) {
if (Line.Tokens.front().Tok->isNot(tok::comment)) {
bool LineIsComment = Line.Tokens.front().Tok->is(tok::comment);
auto TokenIterator = Line.Tokens.begin();
bool LineIsPragmaOnce = Line.Tokens.size() >= 3 &&
TokenIterator->Tok->is(tok::hash) &&
(++TokenIterator)->Tok->is(tok::pp_pragma) &&
(++TokenIterator)->Tok->TokenText == "once";

if (!LineIsComment && !LineIsPragmaOnce) {
MaybeIncludeGuard = false;
IncludeGuard = IG_Rejected;
break;
Expand Down
12 changes: 11 additions & 1 deletion clang/unittests/Format/FormatTest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -6223,6 +6223,16 @@ TEST_F(FormatTest, IndentPreprocessorDirectives) {
"int z;\n"
"#endif",
Style);
// Treat #pragma once as part of an include guard.
verifyFormat("#pragma once\n"
"#ifndef HEADER_H\n"
"#define HEADER_H\n"
"#ifdef NOT_GUARD\n"
"# define NOT_GUARD\n"
"#endif\n"
"code();\n"
"#endif",
Style);
// FIXME: This doesn't handle the case where there's code between the
// #ifndef and #define but all other conditions hold. This is because when
// the #define line is parsed, UnwrappedLineParser::Lines doesn't hold the
Expand All @@ -6239,7 +6249,7 @@ TEST_F(FormatTest, IndentPreprocessorDirectives) {
"#endif",
Style);
// FIXME: This doesn't handle cases where legitimate preprocessor lines may
// be outside an include guard. Examples are #pragma once and
// be outside an include guard. Examples include
// #pragma GCC diagnostic, or anything else that does not change the meaning
// of the file if it's included multiple times.
verifyFormat("#ifdef WIN32\n"
Expand Down