diff --git a/clang/lib/Format/UnwrappedLineParser.cpp b/clang/lib/Format/UnwrappedLineParser.cpp index 5f1a88d4bcd72..506386526bd15 100644 --- a/clang/lib/Format/UnwrappedLineParser.cpp +++ b/clang/lib/Format/UnwrappedLineParser.cpp @@ -3992,6 +3992,9 @@ void UnwrappedLineParser::parseRecord(bool ParseAsExpr) { auto IsNonMacroIdentifier = [](const FormatToken *Tok) { return Tok->is(tok::identifier) && Tok->TokenText != Tok->TokenText.upper(); }; + // JavaScript/TypeScript supports anonymous classes like: + // a = class extends foo { } + bool JSPastExtendsOrImplements = false; // The actual identifier can be a nested name specifier, and in macros // it is often token-pasted. // An [[attribute]] can be before the identifier. @@ -4002,6 +4005,7 @@ void UnwrappedLineParser::parseRecord(bool ParseAsExpr) { FormatTok->isOneOf(tok::period, tok::comma))) { if (Style.isJavaScript() && FormatTok->isOneOf(Keywords.kw_extends, Keywords.kw_implements)) { + JSPastExtendsOrImplements = true; // JavaScript/TypeScript supports inline object types in // extends/implements positions: // class Foo implements {bar: number} { } @@ -4027,8 +4031,8 @@ void UnwrappedLineParser::parseRecord(bool ParseAsExpr) { case tok::coloncolon: break; default: - if (!ClassName && Previous->is(tok::identifier) && - Previous->isNot(TT_AttributeMacro)) { + if (!JSPastExtendsOrImplements && !ClassName && + Previous->is(tok::identifier) && Previous->isNot(TT_AttributeMacro)) { ClassName = Previous; } } diff --git a/clang/unittests/Format/FormatTestJS.cpp b/clang/unittests/Format/FormatTestJS.cpp index b910ce620de7a..4b29ba720f682 100644 --- a/clang/unittests/Format/FormatTestJS.cpp +++ b/clang/unittests/Format/FormatTestJS.cpp @@ -579,6 +579,14 @@ TEST_F(FormatTestJS, GoogScopes) { "});"); } +TEST_F(FormatTestJS, GoogAnonymousClass) { + verifyFormat("a = class extends goog.structs.a {\n" + " a() {\n" + " return 0;\n" + " }\n" + "};"); +} + TEST_F(FormatTestJS, IIFEs) { // Internal calling parens; no semi. verifyFormat("(function() {\n" diff --git a/clang/unittests/Format/TokenAnnotatorTest.cpp b/clang/unittests/Format/TokenAnnotatorTest.cpp index db44d418a8448..12c5b03a6f8d0 100644 --- a/clang/unittests/Format/TokenAnnotatorTest.cpp +++ b/clang/unittests/Format/TokenAnnotatorTest.cpp @@ -3238,6 +3238,12 @@ TEST_F(TokenAnnotatorTest, BraceKind) { EXPECT_BRACE_KIND(Tokens[8], BK_BracedInit); EXPECT_BRACE_KIND(Tokens[11], BK_BracedInit); EXPECT_BRACE_KIND(Tokens[13], BK_Block); + + Tokens = annotate("a = class extends goog.a {};", + getGoogleStyle(FormatStyle::LK_JavaScript)); + ASSERT_EQ(Tokens.size(), 11u) << Tokens; + EXPECT_TOKEN(Tokens[7], tok::l_brace, TT_ClassLBrace); + EXPECT_BRACE_KIND(Tokens[7], BK_Block); } TEST_F(TokenAnnotatorTest, UnderstandsElaboratedTypeSpecifier) {