https://github.com/owenca created https://github.com/llvm/llvm-project/pull/186848
Fixes #176321 >From 6b6db2ce365120aabdc9a2063a3f12ecfa7feac4 Mon Sep 17 00:00:00 2001 From: Owen Pan <[email protected]> Date: Mon, 16 Mar 2026 10:48:07 -0700 Subject: [PATCH] [clang-format] Identify include guard #endif followed by comments Fixes #176321 --- clang/lib/Format/UnwrappedLineParser.cpp | 16 ++++++++++------ clang/unittests/Format/FormatTest.cpp | 7 +++++++ 2 files changed, 17 insertions(+), 6 deletions(-) diff --git a/clang/lib/Format/UnwrappedLineParser.cpp b/clang/lib/Format/UnwrappedLineParser.cpp index 9cefe9408f0ab..08c962dd34bbb 100644 --- a/clang/lib/Format/UnwrappedLineParser.cpp +++ b/clang/lib/Format/UnwrappedLineParser.cpp @@ -1147,12 +1147,6 @@ void UnwrappedLineParser::parsePPElse() { void UnwrappedLineParser::parsePPEndIf() { conditionalCompilationEnd(); parsePPUnknown(); - // If the #endif of a potential include guard is the last thing in the file, - // then we found an include guard. - if (IncludeGuard == IG_Defined && PPBranchLevel == -1 && Tokens->isEOF() && - getIncludeGuardState(Style.IndentPPDirectives) == IG_Inited) { - IncludeGuard = IG_Found; - } } void UnwrappedLineParser::parsePPDefine() { @@ -4952,10 +4946,20 @@ void UnwrappedLineParser::readToken(int LevelDifference) { assert(Line->Level >= Line->UnbracedBodyLevel); Line->Level -= Line->UnbracedBodyLevel; flushComments(isOnNewLine(*FormatTok)); + const bool IsEndIf = Tokens->peekNextToken()->is(tok::pp_endif); parsePPDirective(); PreviousWasComment = FormatTok->is(tok::comment); FirstNonCommentOnLine = IsFirstNonCommentOnLine( FirstNonCommentOnLine, *FormatTok, PreviousWasComment); + // If the #endif of a potential include guard is the last thing in the + // file, then we found an include guard. + if (IsEndIf && IncludeGuard == IG_Defined && PPBranchLevel == -1 && + getIncludeGuardState(Style.IndentPPDirectives) == IG_Inited && + (eof() || + (PreviousWasComment && + Tokens->peekNextToken(/*SkipComment=*/true)->is(tok::eof)))) { + IncludeGuard = IG_Found; + } } if (!PPStack.empty() && (PPStack.back().Kind == PP_Unreachable) && diff --git a/clang/unittests/Format/FormatTest.cpp b/clang/unittests/Format/FormatTest.cpp index 56985abf12559..77676184f0d6a 100644 --- a/clang/unittests/Format/FormatTest.cpp +++ b/clang/unittests/Format/FormatTest.cpp @@ -6701,6 +6701,13 @@ TEST_F(FormatTest, IndentPreprocessorDirectives) { "\n" "#define FGHIJK", Style); + + verifyFormat("#ifndef FOO_H\n" + "#define FOO_H\n" + "#include <iostream>\n" + "#endif\n" + "// comment", + Style); } TEST_F(FormatTest, FormatAlignInsidePreprocessorElseBlock) { _______________________________________________ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
