From: Krasimir Georgiev Date: Mon, 4 Feb 2019 09:56:16 +0000 (+0000) Subject: [clang-format] Fix breaking of qualified operator X-Git-Url: https://granicus.if.org/sourcecode?a=commitdiff_plain;h=8070ca12f87e66f76db528c107e9d291f4a91498;p=clang [clang-format] Fix breaking of qualified operator Summary: From https://bugs.llvm.org/show_bug.cgi?id=40516 ``` $ cat a.cpp const NamespaceName::VeryLongClassName &NamespaceName::VeryLongClassName::myFunction() { // do stuff } const NamespaceName::VeryLongClassName &NamespaceName::VeryLongClassName::operator++() { // do stuff } $ ~/ll/build/opt/bin/clang-format -style=LLVM a.cpp const NamespaceName::VeryLongClassName & NamespaceName::VeryLongClassName::myFunction() { // do stuff } const NamespaceName::VeryLongClassName &NamespaceName::VeryLongClassName:: operator++() { // do stuff } ``` What was happening is that the split penalty before `operator` was being set to a smaller value by a prior if block. Moved checks around to fix this and added a regression test. Reviewers: djasper Reviewed By: djasper Tags: #clang Differential Revision: https://reviews.llvm.org/D57604 git-svn-id: https://llvm.org/svn/llvm-project/cfe/trunk@353033 91177308-0d34-0410-b5e6-96231b3b80d8 --- diff --git a/lib/Format/TokenAnnotator.cpp b/lib/Format/TokenAnnotator.cpp index 1c93c8c6cc..45896d86ad 100644 --- a/lib/Format/TokenAnnotator.cpp +++ b/lib/Format/TokenAnnotator.cpp @@ -2249,6 +2249,9 @@ unsigned TokenAnnotator::splitPenalty(const AnnotatedLine &Line, return 500; } + if (Left.is(tok::coloncolon) || + (Right.is(tok::period) && Style.Language == FormatStyle::LK_Proto)) + return 500; if (Right.isOneOf(TT_StartOfName, TT_FunctionDeclarationName) || Right.is(tok::kw_operator)) { if (Line.startsWith(tok::kw_for) && Right.PartOfMultiVariableDeclStmt) @@ -2267,9 +2270,6 @@ unsigned TokenAnnotator::splitPenalty(const AnnotatedLine &Line, return 160; if (Left.is(TT_CastRParen)) return 100; - if (Left.is(tok::coloncolon) || - (Right.is(tok::period) && Style.Language == FormatStyle::LK_Proto)) - return 500; if (Left.isOneOf(tok::kw_class, tok::kw_struct)) return 5000; if (Left.is(tok::comment)) diff --git a/unittests/Format/FormatTest.cpp b/unittests/Format/FormatTest.cpp index 99b2beadc4..2b0ef9a9dd 100644 --- a/unittests/Format/FormatTest.cpp +++ b/unittests/Format/FormatTest.cpp @@ -4183,6 +4183,18 @@ TEST_F(FormatTest, BreaksFunctionDeclarations) { Style); } +TEST_F(FormatTest, DontBreakBeforeQualifiedOperator) { + // Regression test for https://bugs.llvm.org/show_bug.cgi?id=40516: + // Prefer keeping `::` followed by `operator` together. + EXPECT_EQ("const aaaa::bbbbbbb &\n" + "ccccccccc::operator++() {\n" + " stuff();\n" + "}", + format("const aaaa::bbbbbbb\n" + "&ccccccccc::operator++() { stuff(); }", + getLLVMStyleWithColumns(40))); +} + TEST_F(FormatTest, TrailingReturnType) { verifyFormat("auto foo() -> int;\n"); verifyFormat("struct S {\n"