1 //===--- UnwrappedLineParser.cpp - Format C++ code ------------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
10 /// This file contains the implementation of the UnwrappedLineParser,
11 /// which turns a stream of tokens into UnwrappedLines.
13 //===----------------------------------------------------------------------===//
15 #include "UnwrappedLineParser.h"
16 #include "FormatToken.h"
17 #include "FormatTokenLexer.h"
18 #include "FormatTokenSource.h"
20 #include "TokenAnnotator.h"
21 #include "clang/Basic/TokenKinds.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/StringRef.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Support/raw_os_ostream.h"
26 #include "llvm/Support/raw_ostream.h"
31 #define DEBUG_TYPE "format-parser"
38 void printLine(llvm::raw_ostream &OS, const UnwrappedLine &Line,
39 StringRef Prefix = "", bool PrintText = false) {
40 OS << Prefix << "Line(" << Line.Level << ", FSC=" << Line.FirstStartColumn
41 << ")" << (Line.InPPDirective ? " MACRO" : "") << ": ";
43 for (std::list<UnwrappedLineNode>::const_iterator I = Line.Tokens.begin(),
44 E = Line.Tokens.end();
50 OS << I->Tok->Tok.getName() << "["
51 << "T=" << (unsigned)I->Tok->getType()
52 << ", OC=" << I->Tok->OriginalColumn << ", \"" << I->Tok->TokenText
54 for (SmallVectorImpl<UnwrappedLine>::const_iterator
55 CI = I->Children.begin(),
56 CE = I->Children.end();
59 printLine(OS, *CI, (Prefix + " ").str());
67 LLVM_ATTRIBUTE_UNUSED static void printDebugInfo(const UnwrappedLine &Line) {
68 printLine(llvm::dbgs(), Line);
71 class ScopedDeclarationState {
73 ScopedDeclarationState(UnwrappedLine &Line, llvm::BitVector &Stack,
74 bool MustBeDeclaration)
75 : Line(Line), Stack(Stack) {
76 Line.MustBeDeclaration = MustBeDeclaration;
77 Stack.push_back(MustBeDeclaration);
79 ~ScopedDeclarationState() {
82 Line.MustBeDeclaration = Stack.back();
84 Line.MustBeDeclaration = true;
89 llvm::BitVector &Stack;
92 } // end anonymous namespace
94 class ScopedLineState {
96 ScopedLineState(UnwrappedLineParser &Parser,
97 bool SwitchToPreprocessorLines = false)
98 : Parser(Parser), OriginalLines(Parser.CurrentLines) {
99 if (SwitchToPreprocessorLines)
100 Parser.CurrentLines = &Parser.PreprocessorDirectives;
101 else if (!Parser.Line->Tokens.empty())
102 Parser.CurrentLines = &Parser.Line->Tokens.back().Children;
103 PreBlockLine = std::move(Parser.Line);
104 Parser.Line = std::make_unique<UnwrappedLine>();
105 Parser.Line->Level = PreBlockLine->Level;
106 Parser.Line->PPLevel = PreBlockLine->PPLevel;
107 Parser.Line->InPPDirective = PreBlockLine->InPPDirective;
108 Parser.Line->InMacroBody = PreBlockLine->InMacroBody;
112 if (!Parser.Line->Tokens.empty())
113 Parser.addUnwrappedLine();
114 assert(Parser.Line->Tokens.empty());
115 Parser.Line = std::move(PreBlockLine);
116 if (Parser.CurrentLines == &Parser.PreprocessorDirectives)
117 Parser.MustBreakBeforeNextToken = true;
118 Parser.CurrentLines = OriginalLines;
122 UnwrappedLineParser &Parser;
124 std::unique_ptr<UnwrappedLine> PreBlockLine;
125 SmallVectorImpl<UnwrappedLine> *OriginalLines;
128 class CompoundStatementIndenter {
130 CompoundStatementIndenter(UnwrappedLineParser *Parser,
131 const FormatStyle &Style, unsigned &LineLevel)
132 : CompoundStatementIndenter(Parser, LineLevel,
133 Style.BraceWrapping.AfterControlStatement,
134 Style.BraceWrapping.IndentBraces) {}
135 CompoundStatementIndenter(UnwrappedLineParser *Parser, unsigned &LineLevel,
136 bool WrapBrace, bool IndentBrace)
137 : LineLevel(LineLevel), OldLineLevel(LineLevel) {
139 Parser->addUnwrappedLine();
143 ~CompoundStatementIndenter() { LineLevel = OldLineLevel; }
147 unsigned OldLineLevel;
150 UnwrappedLineParser::UnwrappedLineParser(
151 SourceManager &SourceMgr, const FormatStyle &Style,
152 const AdditionalKeywords &Keywords, unsigned FirstStartColumn,
153 ArrayRef<FormatToken *> Tokens, UnwrappedLineConsumer &Callback,
154 llvm::SpecificBumpPtrAllocator<FormatToken> &Allocator,
155 IdentifierTable &IdentTable)
156 : Line(new UnwrappedLine), MustBreakBeforeNextToken(false),
157 CurrentLines(&Lines), Style(Style), Keywords(Keywords),
158 CommentPragmasRegex(Style.CommentPragmas), Tokens(nullptr),
159 Callback(Callback), AllTokens(Tokens), PPBranchLevel(-1),
160 IncludeGuard(Style.IndentPPDirectives == FormatStyle::PPDIS_None
163 IncludeGuardToken(nullptr), FirstStartColumn(FirstStartColumn),
164 Macros(Style.Macros, SourceMgr, Style, Allocator, IdentTable) {}
166 void UnwrappedLineParser::reset() {
168 IncludeGuard = Style.IndentPPDirectives == FormatStyle::PPDIS_None
171 IncludeGuardToken = nullptr;
172 Line.reset(new UnwrappedLine);
173 CommentsBeforeNextToken.clear();
175 MustBreakBeforeNextToken = false;
176 PreprocessorDirectives.clear();
177 CurrentLines = &Lines;
178 DeclarationScopeStack.clear();
179 NestedTooDeep.clear();
181 Line->FirstStartColumn = FirstStartColumn;
183 if (!Unexpanded.empty())
184 for (FormatToken *Token : AllTokens)
185 Token->MacroCtx.reset();
186 CurrentExpandedLines.clear();
187 ExpandedLines.clear();
193 void UnwrappedLineParser::parse() {
194 IndexedTokenSource TokenSource(AllTokens);
195 Line->FirstStartColumn = FirstStartColumn;
197 LLVM_DEBUG(llvm::dbgs() << "----\n");
199 Tokens = &TokenSource;
205 // If we found an include guard then all preprocessor directives (other than
206 // the guard) are over-indented by one.
207 if (IncludeGuard == IG_Found) {
208 for (auto &Line : Lines)
209 if (Line.InPPDirective && Line.Level > 0)
213 // Create line with eof token.
214 assert(FormatTok->is(tok::eof));
215 pushToken(FormatTok);
218 // In a first run, format everything with the lines containing macro calls
219 // replaced by the expansion.
220 if (!ExpandedLines.empty()) {
221 LLVM_DEBUG(llvm::dbgs() << "Expanded lines:\n");
222 for (const auto &Line : Lines) {
223 if (!Line.Tokens.empty()) {
224 auto it = ExpandedLines.find(Line.Tokens.begin()->Tok);
225 if (it != ExpandedLines.end()) {
226 for (const auto &Expanded : it->second) {
227 LLVM_DEBUG(printDebugInfo(Expanded));
228 Callback.consumeUnwrappedLine(Expanded);
233 LLVM_DEBUG(printDebugInfo(Line));
234 Callback.consumeUnwrappedLine(Line);
236 Callback.finishRun();
239 LLVM_DEBUG(llvm::dbgs() << "Unwrapped lines:\n");
240 for (const UnwrappedLine &Line : Lines) {
241 LLVM_DEBUG(printDebugInfo(Line));
242 Callback.consumeUnwrappedLine(Line);
244 Callback.finishRun();
246 while (!PPLevelBranchIndex.empty() &&
247 PPLevelBranchIndex.back() + 1 >= PPLevelBranchCount.back()) {
248 PPLevelBranchIndex.resize(PPLevelBranchIndex.size() - 1);
249 PPLevelBranchCount.resize(PPLevelBranchCount.size() - 1);
251 if (!PPLevelBranchIndex.empty()) {
252 ++PPLevelBranchIndex.back();
253 assert(PPLevelBranchIndex.size() == PPLevelBranchCount.size());
254 assert(PPLevelBranchIndex.back() <= PPLevelBranchCount.back());
256 } while (!PPLevelBranchIndex.empty());
259 void UnwrappedLineParser::parseFile() {
260 // The top-level context in a file always has declarations, except for pre-
261 // processor directives and JavaScript files.
262 bool MustBeDeclaration = !Line->InPPDirective && !Style.isJavaScript();
263 ScopedDeclarationState DeclarationState(*Line, DeclarationScopeStack,
265 if (Style.Language == FormatStyle::LK_TextProto)
269 // Make sure to format the remaining tokens.
271 // LK_TextProto is special since its top-level is parsed as the body of a
272 // braced list, which does not necessarily have natural line separators such
273 // as a semicolon. Comments after the last entry that have been determined to
274 // not belong to that line, as in:
276 // // endfile comment
277 // do not have a chance to be put on a line of their own until this point.
278 // Here we add this newline before end-of-file comments.
279 if (Style.Language == FormatStyle::LK_TextProto &&
280 !CommentsBeforeNextToken.empty()) {
287 void UnwrappedLineParser::parseCSharpGenericTypeConstraint() {
289 switch (FormatTok->Tok.getKind()) {
293 if (FormatTok->is(Keywords.kw_where)) {
296 parseCSharpGenericTypeConstraint();
305 void UnwrappedLineParser::parseCSharpAttribute() {
306 int UnpairedSquareBrackets = 1;
308 switch (FormatTok->Tok.getKind()) {
311 --UnpairedSquareBrackets;
312 if (UnpairedSquareBrackets == 0) {
318 ++UnpairedSquareBrackets;
328 bool UnwrappedLineParser::precededByCommentOrPPDirective() const {
329 if (!Lines.empty() && Lines.back().InPPDirective)
332 const FormatToken *Previous = Tokens->getPreviousToken();
333 return Previous && Previous->is(tok::comment) &&
334 (Previous->IsMultiline || Previous->NewlinesBefore > 0);
337 /// \brief Parses a level, that is ???.
338 /// \param OpeningBrace Opening brace (\p nullptr if absent) of that level
339 /// \param CanContainBracedList If the content can contain (at any level) a
341 /// \param NextLBracesType The type for left brace found in this level.
342 /// \param IfKind The \p if statement kind in the level.
343 /// \param IfLeftBrace The left brace of the \p if block in the level.
344 /// \returns true if a simple block of if/else/for/while, or false otherwise.
345 /// (A simple block has a single statement.)
346 bool UnwrappedLineParser::parseLevel(const FormatToken *OpeningBrace,
347 bool CanContainBracedList,
348 TokenType NextLBracesType,
350 FormatToken **IfLeftBrace) {
351 auto NextLevelLBracesType = NextLBracesType == TT_CompoundRequirementLBrace
352 ? TT_BracedListLBrace
354 const bool IsPrecededByCommentOrPPDirective =
355 !Style.RemoveBracesLLVM || precededByCommentOrPPDirective();
356 FormatToken *IfLBrace = nullptr;
357 bool HasDoWhile = false;
358 bool HasLabel = false;
359 unsigned StatementCount = 0;
360 bool SwitchLabelEncountered = false;
363 if (FormatTok->getType() == TT_AttributeMacro) {
367 tok::TokenKind kind = FormatTok->Tok.getKind();
368 if (FormatTok->getType() == TT_MacroBlockBegin)
370 else if (FormatTok->getType() == TT_MacroBlockEnd)
373 auto ParseDefault = [this, OpeningBrace, NextLevelLBracesType, IfKind,
374 &IfLBrace, &HasDoWhile, &HasLabel, &StatementCount] {
375 parseStructuralElement(!OpeningBrace, NextLevelLBracesType, IfKind,
376 &IfLBrace, HasDoWhile ? nullptr : &HasDoWhile,
377 HasLabel ? nullptr : &HasLabel);
379 assert(StatementCount > 0 && "StatementCount overflow!");
388 if (NextLBracesType != TT_Unknown) {
389 FormatTok->setFinalizedType(NextLBracesType);
390 } else if (FormatTok->Previous &&
391 FormatTok->Previous->ClosesRequiresClause) {
392 // We need the 'default' case here to correctly parse a function
397 if (CanContainBracedList && !FormatTok->is(TT_MacroBlockBegin) &&
398 tryToParseBracedList()) {
401 parseBlock(/*MustBeDeclaration=*/false, /*AddLevels=*/1u,
402 /*MunchSemi=*/true, /*KeepBraces=*/true, /*IfKind=*/nullptr,
403 /*UnindentWhitesmithsBraces=*/false, CanContainBracedList,
406 assert(StatementCount > 0 && "StatementCount overflow!");
411 if (!Style.RemoveBracesLLVM || Line->InPPDirective ||
412 !OpeningBrace->isOneOf(TT_ControlStatementLBrace, TT_ElseLBrace)) {
415 if (FormatTok->isNot(tok::r_brace) || StatementCount != 1 || HasLabel ||
416 HasDoWhile || IsPrecededByCommentOrPPDirective ||
417 precededByCommentOrPPDirective()) {
420 const FormatToken *Next = Tokens->peekNextToken();
421 if (Next->is(tok::comment) && Next->NewlinesBefore == 0)
424 *IfLeftBrace = IfLBrace;
430 case tok::kw_default: {
431 unsigned StoredPosition = Tokens->getPosition();
434 Next = Tokens->getNextToken();
436 } while (Next->is(tok::comment));
437 FormatTok = Tokens->setPosition(StoredPosition);
438 if (Next->isNot(tok::colon)) {
439 // default not followed by ':' is not a case label; treat it like
441 parseStructuralElement();
444 // Else, if it is 'default:', fall through to the case handling.
448 if (Style.isProto() || Style.isVerilog() ||
449 (Style.isJavaScript() && Line->MustBeDeclaration)) {
450 // Proto: there are no switch/case statements
451 // Verilog: Case labels don't have this word. We handle case
452 // labels including default in TokenAnnotator.
453 // JavaScript: A 'case: string' style field declaration.
457 if (!SwitchLabelEncountered &&
458 (Style.IndentCaseLabels ||
459 (Line->InPPDirective && Line->Level == 1))) {
462 SwitchLabelEncountered = true;
463 parseStructuralElement();
466 if (Style.isCSharp()) {
468 parseCSharpAttribute();
471 if (handleCppAttributes())
483 void UnwrappedLineParser::calculateBraceTypes(bool ExpectClassBody) {
484 // We'll parse forward through the tokens until we hit
485 // a closing brace or eof - note that getNextToken() will
486 // parse macros, so this will magically work inside macro
488 unsigned StoredPosition = Tokens->getPosition();
489 FormatToken *Tok = FormatTok;
490 const FormatToken *PrevTok = Tok->Previous;
491 // Keep a stack of positions of lbrace tokens. We will
492 // update information about whether an lbrace starts a
493 // braced init list or a different block during the loop.
496 const FormatToken *PrevTok;
498 SmallVector<StackEntry, 8> LBraceStack;
499 assert(Tok->is(tok::l_brace));
501 // Get next non-comment token.
502 FormatToken *NextTok;
504 NextTok = Tokens->getNextToken();
505 } while (NextTok->is(tok::comment));
507 switch (Tok->Tok.getKind()) {
509 if (Style.isJavaScript() && PrevTok) {
510 if (PrevTok->isOneOf(tok::colon, tok::less)) {
511 // A ':' indicates this code is in a type, or a braced list
512 // following a label in an object literal ({a: {b: 1}}).
513 // A '<' could be an object used in a comparison, but that is nonsense
514 // code (can never return true), so more likely it is a generic type
515 // argument (`X<{a: string; b: number}>`).
516 // The code below could be confused by semicolons between the
517 // individual members in a type member list, which would normally
518 // trigger BK_Block. In both cases, this must be parsed as an inline
520 Tok->setBlockKind(BK_BracedInit);
521 } else if (PrevTok->is(tok::r_paren)) {
522 // `) { }` can only occur in function or method declarations in JS.
523 Tok->setBlockKind(BK_Block);
526 Tok->setBlockKind(BK_Unknown);
528 LBraceStack.push_back({Tok, PrevTok});
531 if (LBraceStack.empty())
533 if (LBraceStack.back().Tok->is(BK_Unknown)) {
534 bool ProbablyBracedList = false;
535 if (Style.Language == FormatStyle::LK_Proto) {
536 ProbablyBracedList = NextTok->isOneOf(tok::comma, tok::r_square);
538 // Skip NextTok over preprocessor lines, otherwise we may not
539 // properly diagnose the block as a braced intializer
540 // if the comma separator appears after the pp directive.
541 while (NextTok->is(tok::hash)) {
542 ScopedMacroState MacroState(*Line, Tokens, NextTok);
544 NextTok = Tokens->getNextToken();
545 } while (NextTok->isNot(tok::eof));
548 // Using OriginalColumn to distinguish between ObjC methods and
549 // binary operators is a bit hacky.
550 bool NextIsObjCMethod = NextTok->isOneOf(tok::plus, tok::minus) &&
551 NextTok->OriginalColumn == 0;
553 // Try to detect a braced list. Note that regardless how we mark inner
554 // braces here, we will overwrite the BlockKind later if we parse a
555 // braced list (where all blocks inside are by default braced lists),
556 // or when we explicitly detect blocks (for example while parsing
559 // If we already marked the opening brace as braced list, the closing
560 // must also be part of it.
561 ProbablyBracedList = LBraceStack.back().Tok->is(TT_BracedListLBrace);
563 ProbablyBracedList = ProbablyBracedList ||
564 (Style.isJavaScript() &&
565 NextTok->isOneOf(Keywords.kw_of, Keywords.kw_in,
567 ProbablyBracedList = ProbablyBracedList ||
568 (Style.isCpp() && NextTok->is(tok::l_paren));
570 // If there is a comma, semicolon or right paren after the closing
571 // brace, we assume this is a braced initializer list.
572 // FIXME: Some of these do not apply to JS, e.g. "} {" can never be a
573 // braced list in JS.
575 ProbablyBracedList ||
576 NextTok->isOneOf(tok::comma, tok::period, tok::colon,
577 tok::r_paren, tok::r_square, tok::ellipsis);
579 // Distinguish between braced list in a constructor initializer list
580 // followed by constructor body, or just adjacent blocks.
582 ProbablyBracedList ||
583 (NextTok->is(tok::l_brace) && LBraceStack.back().PrevTok &&
584 LBraceStack.back().PrevTok->is(tok::identifier));
587 ProbablyBracedList ||
588 (NextTok->is(tok::identifier) &&
589 !PrevTok->isOneOf(tok::semi, tok::r_brace, tok::l_brace));
591 ProbablyBracedList = ProbablyBracedList ||
592 (NextTok->is(tok::semi) &&
593 (!ExpectClassBody || LBraceStack.size() != 1));
596 ProbablyBracedList ||
597 (NextTok->isBinaryOperator() && !NextIsObjCMethod);
599 if (!Style.isCSharp() && NextTok->is(tok::l_square)) {
600 // We can have an array subscript after a braced init
601 // list, but C++11 attributes are expected after blocks.
602 NextTok = Tokens->getNextToken();
603 ProbablyBracedList = NextTok->isNot(tok::l_square);
606 if (ProbablyBracedList) {
607 Tok->setBlockKind(BK_BracedInit);
608 LBraceStack.back().Tok->setBlockKind(BK_BracedInit);
610 Tok->setBlockKind(BK_Block);
611 LBraceStack.back().Tok->setBlockKind(BK_Block);
614 LBraceStack.pop_back();
616 case tok::identifier:
617 if (!Tok->is(TT_StatementMacro))
628 if (!LBraceStack.empty() && LBraceStack.back().Tok->is(BK_Unknown))
629 LBraceStack.back().Tok->setBlockKind(BK_Block);
636 } while (Tok->isNot(tok::eof) && !LBraceStack.empty());
638 // Assume other blocks for all unclosed opening braces.
639 for (const auto &Entry : LBraceStack)
640 if (Entry.Tok->is(BK_Unknown))
641 Entry.Tok->setBlockKind(BK_Block);
643 FormatTok = Tokens->setPosition(StoredPosition);
647 static inline void hash_combine(std::size_t &seed, const T &v) {
649 seed ^= hasher(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
652 size_t UnwrappedLineParser::computePPHash() const {
654 for (const auto &i : PPStack) {
655 hash_combine(h, size_t(i.Kind));
656 hash_combine(h, i.Line);
661 // Checks whether \p ParsedLine might fit on a single line. If \p OpeningBrace
662 // is not null, subtracts its length (plus the preceding space) when computing
663 // the length of \p ParsedLine. We must clone the tokens of \p ParsedLine before
664 // running the token annotator on it so that we can restore them afterward.
665 bool UnwrappedLineParser::mightFitOnOneLine(
666 UnwrappedLine &ParsedLine, const FormatToken *OpeningBrace) const {
667 const auto ColumnLimit = Style.ColumnLimit;
668 if (ColumnLimit == 0)
671 auto &Tokens = ParsedLine.Tokens;
672 assert(!Tokens.empty());
674 const auto *LastToken = Tokens.back().Tok;
677 SmallVector<UnwrappedLineNode> SavedTokens(Tokens.size());
680 for (const auto &Token : Tokens) {
682 auto &SavedToken = SavedTokens[Index++];
683 SavedToken.Tok = new FormatToken;
684 SavedToken.Tok->copyFrom(*Token.Tok);
685 SavedToken.Children = std::move(Token.Children);
688 AnnotatedLine Line(ParsedLine);
689 assert(Line.Last == LastToken);
691 TokenAnnotator Annotator(Style, Keywords);
692 Annotator.annotate(Line);
693 Annotator.calculateFormattingInformation(Line);
695 auto Length = LastToken->TotalLength;
697 assert(OpeningBrace != Tokens.front().Tok);
698 if (auto Prev = OpeningBrace->Previous;
699 Prev && Prev->TotalLength + ColumnLimit == OpeningBrace->TotalLength) {
700 Length -= ColumnLimit;
702 Length -= OpeningBrace->TokenText.size() + 1;
705 if (const auto *FirstToken = Line.First; FirstToken->is(tok::r_brace)) {
706 assert(!OpeningBrace || OpeningBrace->is(TT_ControlStatementLBrace));
707 Length -= FirstToken->TokenText.size() + 1;
711 for (auto &Token : Tokens) {
712 const auto &SavedToken = SavedTokens[Index++];
713 Token.Tok->copyFrom(*SavedToken.Tok);
714 Token.Children = std::move(SavedToken.Children);
715 delete SavedToken.Tok;
718 // If these change PPLevel needs to be used for get correct indentation.
719 assert(!Line.InMacroBody);
720 assert(!Line.InPPDirective);
721 return Line.Level * Style.IndentWidth + Length <= ColumnLimit;
724 FormatToken *UnwrappedLineParser::parseBlock(
725 bool MustBeDeclaration, unsigned AddLevels, bool MunchSemi, bool KeepBraces,
726 IfStmtKind *IfKind, bool UnindentWhitesmithsBraces,
727 bool CanContainBracedList, TokenType NextLBracesType) {
728 auto HandleVerilogBlockLabel = [this]() {
730 if (Style.isVerilog() && FormatTok->is(tok::colon)) {
732 if (Keywords.isVerilogIdentifier(*FormatTok))
737 // Whether this is a Verilog-specific block that has a special header like a
739 const bool VerilogHierarchy =
740 Style.isVerilog() && Keywords.isVerilogHierarchy(*FormatTok);
741 assert((FormatTok->isOneOf(tok::l_brace, TT_MacroBlockBegin) ||
742 (Style.isVerilog() &&
743 (Keywords.isVerilogBegin(*FormatTok) || VerilogHierarchy))) &&
744 "'{' or macro block token expected");
745 FormatToken *Tok = FormatTok;
746 const bool FollowedByComment = Tokens->peekNextToken()->is(tok::comment);
747 auto Index = CurrentLines->size();
748 const bool MacroBlock = FormatTok->is(TT_MacroBlockBegin);
749 FormatTok->setBlockKind(BK_Block);
751 // For Whitesmiths mode, jump to the next level prior to skipping over the
753 if (!VerilogHierarchy && AddLevels > 0 &&
754 Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths) {
758 size_t PPStartHash = computePPHash();
760 const unsigned InitialLevel = Line->Level;
761 if (VerilogHierarchy) {
762 AddLevels += parseVerilogHierarchyHeader();
764 nextToken(/*LevelDifference=*/AddLevels);
765 HandleVerilogBlockLabel();
768 // Bail out if there are too many levels. Otherwise, the stack might overflow.
769 if (Line->Level > 300)
772 if (MacroBlock && FormatTok->is(tok::l_paren))
775 size_t NbPreprocessorDirectives =
776 !parsingPPDirective() ? PreprocessorDirectives.size() : 0;
778 size_t OpeningLineIndex =
779 CurrentLines->empty()
780 ? (UnwrappedLine::kInvalidIndex)
781 : (CurrentLines->size() - 1 - NbPreprocessorDirectives);
783 // Whitesmiths is weird here. The brace needs to be indented for the namespace
784 // block, but the block itself may not be indented depending on the style
785 // settings. This allows the format to back up one level in those cases.
786 if (UnindentWhitesmithsBraces)
789 ScopedDeclarationState DeclarationState(*Line, DeclarationScopeStack,
791 if (AddLevels > 0u && Style.BreakBeforeBraces != FormatStyle::BS_Whitesmiths)
792 Line->Level += AddLevels;
794 FormatToken *IfLBrace = nullptr;
795 const bool SimpleBlock =
796 parseLevel(Tok, CanContainBracedList, NextLBracesType, IfKind, &IfLBrace);
801 if (MacroBlock ? !FormatTok->is(TT_MacroBlockEnd)
802 : !FormatTok->is(tok::r_brace)) {
803 Line->Level = InitialLevel;
804 FormatTok->setBlockKind(BK_Block);
808 const bool IsFunctionRBrace =
809 FormatTok->is(tok::r_brace) && Tok->is(TT_FunctionLBrace);
811 auto RemoveBraces = [=]() mutable {
814 assert(Tok->isOneOf(TT_ControlStatementLBrace, TT_ElseLBrace));
815 assert(FormatTok->is(tok::r_brace));
816 const bool WrappedOpeningBrace = !Tok->Previous;
817 if (WrappedOpeningBrace && FollowedByComment)
819 const bool HasRequiredIfBraces = IfLBrace && !IfLBrace->Optional;
820 if (KeepBraces && !HasRequiredIfBraces)
822 if (Tok->isNot(TT_ElseLBrace) || !HasRequiredIfBraces) {
823 const FormatToken *Previous = Tokens->getPreviousToken();
825 if (Previous->is(tok::r_brace) && !Previous->Optional)
828 assert(!CurrentLines->empty());
829 auto &LastLine = CurrentLines->back();
830 if (LastLine.Level == InitialLevel + 1 && !mightFitOnOneLine(LastLine))
832 if (Tok->is(TT_ElseLBrace))
834 if (WrappedOpeningBrace) {
836 --Index; // The line above the wrapped l_brace.
839 return mightFitOnOneLine((*CurrentLines)[Index], Tok);
841 if (RemoveBraces()) {
842 Tok->MatchingParen = FormatTok;
843 FormatTok->MatchingParen = Tok;
846 size_t PPEndHash = computePPHash();
848 // Munch the closing brace.
849 nextToken(/*LevelDifference=*/-AddLevels);
851 // When this is a function block and there is an unnecessary semicolon
852 // afterwards then mark it as optional (so the RemoveSemi pass can get rid of
854 if (Style.RemoveSemicolon && IsFunctionRBrace) {
855 while (FormatTok->is(tok::semi)) {
856 FormatTok->Optional = true;
861 HandleVerilogBlockLabel();
863 if (MacroBlock && FormatTok->is(tok::l_paren))
866 Line->Level = InitialLevel;
868 if (FormatTok->is(tok::kw_noexcept)) {
869 // A noexcept in a requires expression.
873 if (FormatTok->is(tok::arrow)) {
874 // Following the } or noexcept we can find a trailing return type arrow
875 // as part of an implicit conversion constraint.
877 parseStructuralElement();
880 if (MunchSemi && FormatTok->is(tok::semi))
883 if (PPStartHash == PPEndHash) {
884 Line->MatchingOpeningBlockLineIndex = OpeningLineIndex;
885 if (OpeningLineIndex != UnwrappedLine::kInvalidIndex) {
886 // Update the opening line to add the forward reference as well
887 (*CurrentLines)[OpeningLineIndex].MatchingClosingBlockLineIndex =
888 CurrentLines->size() - 1;
895 static bool isGoogScope(const UnwrappedLine &Line) {
896 // FIXME: Closure-library specific stuff should not be hard-coded but be
898 if (Line.Tokens.size() < 4)
900 auto I = Line.Tokens.begin();
901 if (I->Tok->TokenText != "goog")
904 if (I->Tok->isNot(tok::period))
907 if (I->Tok->TokenText != "scope")
910 return I->Tok->is(tok::l_paren);
913 static bool isIIFE(const UnwrappedLine &Line,
914 const AdditionalKeywords &Keywords) {
915 // Look for the start of an immediately invoked anonymous function.
916 // https://en.wikipedia.org/wiki/Immediately-invoked_function_expression
917 // This is commonly done in JavaScript to create a new, anonymous scope.
918 // Example: (function() { ... })()
919 if (Line.Tokens.size() < 3)
921 auto I = Line.Tokens.begin();
922 if (I->Tok->isNot(tok::l_paren))
925 if (I->Tok->isNot(Keywords.kw_function))
928 return I->Tok->is(tok::l_paren);
931 static bool ShouldBreakBeforeBrace(const FormatStyle &Style,
932 const FormatToken &InitialToken) {
933 tok::TokenKind Kind = InitialToken.Tok.getKind();
934 if (InitialToken.is(TT_NamespaceMacro))
935 Kind = tok::kw_namespace;
938 case tok::kw_namespace:
939 return Style.BraceWrapping.AfterNamespace;
941 return Style.BraceWrapping.AfterClass;
943 return Style.BraceWrapping.AfterUnion;
945 return Style.BraceWrapping.AfterStruct;
947 return Style.BraceWrapping.AfterEnum;
953 void UnwrappedLineParser::parseChildBlock(
954 bool CanContainBracedList, clang::format::TokenType NextLBracesType) {
955 assert(FormatTok->is(tok::l_brace));
956 FormatTok->setBlockKind(BK_Block);
957 const FormatToken *OpeningBrace = FormatTok;
960 bool SkipIndent = (Style.isJavaScript() &&
961 (isGoogScope(*Line) || isIIFE(*Line, Keywords)));
962 ScopedLineState LineState(*this);
963 ScopedDeclarationState DeclarationState(*Line, DeclarationScopeStack,
964 /*MustBeDeclaration=*/false);
965 Line->Level += SkipIndent ? 0 : 1;
966 parseLevel(OpeningBrace, CanContainBracedList, NextLBracesType);
967 flushComments(isOnNewLine(*FormatTok));
968 Line->Level -= SkipIndent ? 0 : 1;
973 void UnwrappedLineParser::parsePPDirective() {
974 assert(FormatTok->is(tok::hash) && "'#' expected");
975 ScopedMacroState MacroState(*Line, Tokens, FormatTok);
979 if (!FormatTok->Tok.getIdentifierInfo()) {
984 switch (FormatTok->Tok.getIdentifierInfo()->getPPKeywordID()) {
989 parsePPIf(/*IfDef=*/false);
993 parsePPIf(/*IfDef=*/true);
996 case tok::pp_elifdef:
997 case tok::pp_elifndef:
1004 case tok::pp_pragma:
1013 void UnwrappedLineParser::conditionalCompilationCondition(bool Unreachable) {
1014 size_t Line = CurrentLines->size();
1015 if (CurrentLines == &PreprocessorDirectives)
1016 Line += Lines.size();
1019 (!PPStack.empty() && PPStack.back().Kind == PP_Unreachable)) {
1020 PPStack.push_back({PP_Unreachable, Line});
1022 PPStack.push_back({PP_Conditional, Line});
1026 void UnwrappedLineParser::conditionalCompilationStart(bool Unreachable) {
1028 assert(PPBranchLevel >= 0 && PPBranchLevel <= (int)PPLevelBranchIndex.size());
1029 if (PPBranchLevel == (int)PPLevelBranchIndex.size()) {
1030 PPLevelBranchIndex.push_back(0);
1031 PPLevelBranchCount.push_back(0);
1033 PPChainBranchIndex.push(Unreachable ? -1 : 0);
1034 bool Skip = PPLevelBranchIndex[PPBranchLevel] > 0;
1035 conditionalCompilationCondition(Unreachable || Skip);
1038 void UnwrappedLineParser::conditionalCompilationAlternative() {
1039 if (!PPStack.empty())
1041 assert(PPBranchLevel < (int)PPLevelBranchIndex.size());
1042 if (!PPChainBranchIndex.empty())
1043 ++PPChainBranchIndex.top();
1044 conditionalCompilationCondition(
1045 PPBranchLevel >= 0 && !PPChainBranchIndex.empty() &&
1046 PPLevelBranchIndex[PPBranchLevel] != PPChainBranchIndex.top());
1049 void UnwrappedLineParser::conditionalCompilationEnd() {
1050 assert(PPBranchLevel < (int)PPLevelBranchIndex.size());
1051 if (PPBranchLevel >= 0 && !PPChainBranchIndex.empty()) {
1052 if (PPChainBranchIndex.top() + 1 > PPLevelBranchCount[PPBranchLevel])
1053 PPLevelBranchCount[PPBranchLevel] = PPChainBranchIndex.top() + 1;
1055 // Guard against #endif's without #if.
1056 if (PPBranchLevel > -1)
1058 if (!PPChainBranchIndex.empty())
1059 PPChainBranchIndex.pop();
1060 if (!PPStack.empty())
1064 void UnwrappedLineParser::parsePPIf(bool IfDef) {
1065 bool IfNDef = FormatTok->is(tok::pp_ifndef);
1067 bool Unreachable = false;
1068 if (!IfDef && (FormatTok->is(tok::kw_false) || FormatTok->TokenText == "0"))
1070 if (IfDef && !IfNDef && FormatTok->TokenText == "SWIG")
1072 conditionalCompilationStart(Unreachable);
1073 FormatToken *IfCondition = FormatTok;
1074 // If there's a #ifndef on the first line, and the only lines before it are
1075 // comments, it could be an include guard.
1076 bool MaybeIncludeGuard = IfNDef;
1077 if (IncludeGuard == IG_Inited && MaybeIncludeGuard) {
1078 for (auto &Line : Lines) {
1079 if (!Line.Tokens.front().Tok->is(tok::comment)) {
1080 MaybeIncludeGuard = false;
1081 IncludeGuard = IG_Rejected;
1089 if (IncludeGuard == IG_Inited && MaybeIncludeGuard) {
1090 IncludeGuard = IG_IfNdefed;
1091 IncludeGuardToken = IfCondition;
1095 void UnwrappedLineParser::parsePPElse() {
1096 // If a potential include guard has an #else, it's not an include guard.
1097 if (IncludeGuard == IG_Defined && PPBranchLevel == 0)
1098 IncludeGuard = IG_Rejected;
1099 // Don't crash when there is an #else without an #if.
1100 assert(PPBranchLevel >= -1);
1101 if (PPBranchLevel == -1)
1102 conditionalCompilationStart(/*Unreachable=*/true);
1103 conditionalCompilationAlternative();
1109 void UnwrappedLineParser::parsePPEndIf() {
1110 conditionalCompilationEnd();
1112 // If the #endif of a potential include guard is the last thing in the file,
1113 // then we found an include guard.
1114 if (IncludeGuard == IG_Defined && PPBranchLevel == -1 && Tokens->isEOF() &&
1115 Style.IndentPPDirectives != FormatStyle::PPDIS_None) {
1116 IncludeGuard = IG_Found;
1120 void UnwrappedLineParser::parsePPDefine() {
1123 if (!FormatTok->Tok.getIdentifierInfo()) {
1124 IncludeGuard = IG_Rejected;
1125 IncludeGuardToken = nullptr;
1130 if (IncludeGuard == IG_IfNdefed &&
1131 IncludeGuardToken->TokenText == FormatTok->TokenText) {
1132 IncludeGuard = IG_Defined;
1133 IncludeGuardToken = nullptr;
1134 for (auto &Line : Lines) {
1135 if (!Line.Tokens.front().Tok->isOneOf(tok::comment, tok::hash)) {
1136 IncludeGuard = IG_Rejected;
1142 // In the context of a define, even keywords should be treated as normal
1143 // identifiers. Setting the kind to identifier is not enough, because we need
1144 // to treat additional keywords like __except as well, which are already
1145 // identifiers. Setting the identifier info to null interferes with include
1146 // guard processing above, and changes preprocessing nesting.
1147 FormatTok->Tok.setKind(tok::identifier);
1148 FormatTok->Tok.setIdentifierInfo(Keywords.kw_internal_ident_after_define);
1150 if (FormatTok->Tok.getKind() == tok::l_paren &&
1151 !FormatTok->hasWhitespaceBefore()) {
1154 if (Style.IndentPPDirectives != FormatStyle::PPDIS_None)
1155 Line->Level += PPBranchLevel + 1;
1159 Line->PPLevel = PPBranchLevel + (IncludeGuard == IG_Defined ? 0 : 1);
1160 assert((int)Line->PPLevel >= 0);
1161 Line->InMacroBody = true;
1163 // Errors during a preprocessor directive can only affect the layout of the
1164 // preprocessor directive, and thus we ignore them. An alternative approach
1165 // would be to use the same approach we use on the file level (no
1166 // re-indentation if there was a structural error) within the macro
1171 void UnwrappedLineParser::parsePPPragma() {
1172 Line->InPragmaDirective = true;
1176 void UnwrappedLineParser::parsePPUnknown() {
1180 if (Style.IndentPPDirectives != FormatStyle::PPDIS_None)
1181 Line->Level += PPBranchLevel + 1;
1185 // Here we exclude certain tokens that are not usually the first token in an
1186 // unwrapped line. This is used in attempt to distinguish macro calls without
1187 // trailing semicolons from other constructs split to several lines.
1188 static bool tokenCanStartNewLine(const FormatToken &Tok) {
1189 // Semicolon can be a null-statement, l_square can be a start of a macro or
1190 // a C++11 attribute, but this doesn't seem to be common.
1191 return Tok.isNot(tok::semi) && Tok.isNot(tok::l_brace) &&
1192 Tok.isNot(TT_AttributeSquare) &&
1193 // Tokens that can only be used as binary operators and a part of
1194 // overloaded operator names.
1195 Tok.isNot(tok::period) && Tok.isNot(tok::periodstar) &&
1196 Tok.isNot(tok::arrow) && Tok.isNot(tok::arrowstar) &&
1197 Tok.isNot(tok::less) && Tok.isNot(tok::greater) &&
1198 Tok.isNot(tok::slash) && Tok.isNot(tok::percent) &&
1199 Tok.isNot(tok::lessless) && Tok.isNot(tok::greatergreater) &&
1200 Tok.isNot(tok::equal) && Tok.isNot(tok::plusequal) &&
1201 Tok.isNot(tok::minusequal) && Tok.isNot(tok::starequal) &&
1202 Tok.isNot(tok::slashequal) && Tok.isNot(tok::percentequal) &&
1203 Tok.isNot(tok::ampequal) && Tok.isNot(tok::pipeequal) &&
1204 Tok.isNot(tok::caretequal) && Tok.isNot(tok::greatergreaterequal) &&
1205 Tok.isNot(tok::lesslessequal) &&
1206 // Colon is used in labels, base class lists, initializer lists,
1207 // range-based for loops, ternary operator, but should never be the
1208 // first token in an unwrapped line.
1209 Tok.isNot(tok::colon) &&
1210 // 'noexcept' is a trailing annotation.
1211 Tok.isNot(tok::kw_noexcept);
1214 static bool mustBeJSIdent(const AdditionalKeywords &Keywords,
1215 const FormatToken *FormatTok) {
1216 // FIXME: This returns true for C/C++ keywords like 'struct'.
1217 return FormatTok->is(tok::identifier) &&
1218 (!FormatTok->Tok.getIdentifierInfo() ||
1219 !FormatTok->isOneOf(
1220 Keywords.kw_in, Keywords.kw_of, Keywords.kw_as, Keywords.kw_async,
1221 Keywords.kw_await, Keywords.kw_yield, Keywords.kw_finally,
1222 Keywords.kw_function, Keywords.kw_import, Keywords.kw_is,
1223 Keywords.kw_let, Keywords.kw_var, tok::kw_const,
1224 Keywords.kw_abstract, Keywords.kw_extends, Keywords.kw_implements,
1225 Keywords.kw_instanceof, Keywords.kw_interface,
1226 Keywords.kw_override, Keywords.kw_throws, Keywords.kw_from));
1229 static bool mustBeJSIdentOrValue(const AdditionalKeywords &Keywords,
1230 const FormatToken *FormatTok) {
1231 return FormatTok->Tok.isLiteral() ||
1232 FormatTok->isOneOf(tok::kw_true, tok::kw_false) ||
1233 mustBeJSIdent(Keywords, FormatTok);
1236 // isJSDeclOrStmt returns true if |FormatTok| starts a declaration or statement
1237 // when encountered after a value (see mustBeJSIdentOrValue).
1238 static bool isJSDeclOrStmt(const AdditionalKeywords &Keywords,
1239 const FormatToken *FormatTok) {
1240 return FormatTok->isOneOf(
1241 tok::kw_return, Keywords.kw_yield,
1243 tok::kw_if, tok::kw_else,
1245 tok::kw_for, tok::kw_while, tok::kw_do, tok::kw_continue, tok::kw_break,
1247 tok::kw_switch, tok::kw_case,
1249 tok::kw_throw, tok::kw_try, tok::kw_catch, Keywords.kw_finally,
1251 tok::kw_const, tok::kw_class, Keywords.kw_var, Keywords.kw_let,
1252 Keywords.kw_async, Keywords.kw_function,
1254 Keywords.kw_import, tok::kw_export);
1257 // Checks whether a token is a type in K&R C (aka C78).
1258 static bool isC78Type(const FormatToken &Tok) {
1259 return Tok.isOneOf(tok::kw_char, tok::kw_short, tok::kw_int, tok::kw_long,
1260 tok::kw_unsigned, tok::kw_float, tok::kw_double,
1264 // This function checks whether a token starts the first parameter declaration
1265 // in a K&R C (aka C78) function definition, e.g.:
1271 static bool isC78ParameterDecl(const FormatToken *Tok, const FormatToken *Next,
1272 const FormatToken *FuncName) {
1277 if (FuncName->isNot(tok::identifier))
1280 const FormatToken *Prev = FuncName->Previous;
1281 if (!Prev || (Prev->isNot(tok::star) && !isC78Type(*Prev)))
1284 if (!isC78Type(*Tok) &&
1285 !Tok->isOneOf(tok::kw_register, tok::kw_struct, tok::kw_union)) {
1289 if (Next->isNot(tok::star) && !Next->Tok.getIdentifierInfo())
1292 Tok = Tok->Previous;
1293 if (!Tok || Tok->isNot(tok::r_paren))
1296 Tok = Tok->Previous;
1297 if (!Tok || Tok->isNot(tok::identifier))
1300 return Tok->Previous && Tok->Previous->isOneOf(tok::l_paren, tok::comma);
1303 bool UnwrappedLineParser::parseModuleImport() {
1304 assert(FormatTok->is(Keywords.kw_import) && "'import' expected");
1306 if (auto Token = Tokens->peekNextToken(/*SkipComment=*/true);
1307 !Token->Tok.getIdentifierInfo() &&
1308 !Token->isOneOf(tok::colon, tok::less, tok::string_literal)) {
1314 if (FormatTok->is(tok::colon)) {
1315 FormatTok->setFinalizedType(TT_ModulePartitionColon);
1317 // Handle import <foo/bar.h> as we would an include statement.
1318 else if (FormatTok->is(tok::less)) {
1320 while (!FormatTok->isOneOf(tok::semi, tok::greater, tok::eof)) {
1321 // Mark tokens up to the trailing line comments as implicit string
1323 if (FormatTok->isNot(tok::comment) &&
1324 !FormatTok->TokenText.startswith("//")) {
1325 FormatTok->setFinalizedType(TT_ImplicitStringLiteral);
1330 if (FormatTok->is(tok::semi)) {
1341 // readTokenWithJavaScriptASI reads the next token and terminates the current
1342 // line if JavaScript Automatic Semicolon Insertion must
1343 // happen between the current token and the next token.
1345 // This method is conservative - it cannot cover all edge cases of JavaScript,
1346 // but only aims to correctly handle certain well known cases. It *must not*
1347 // return true in speculative cases.
1348 void UnwrappedLineParser::readTokenWithJavaScriptASI() {
1349 FormatToken *Previous = FormatTok;
1351 FormatToken *Next = FormatTok;
1354 CommentsBeforeNextToken.empty()
1355 ? Next->NewlinesBefore == 0
1356 : CommentsBeforeNextToken.front()->NewlinesBefore == 0;
1360 bool PreviousMustBeValue = mustBeJSIdentOrValue(Keywords, Previous);
1361 bool PreviousStartsTemplateExpr =
1362 Previous->is(TT_TemplateString) && Previous->TokenText.endswith("${");
1363 if (PreviousMustBeValue || Previous->is(tok::r_paren)) {
1364 // If the line contains an '@' sign, the previous token might be an
1365 // annotation, which can precede another identifier/value.
1366 bool HasAt = llvm::any_of(Line->Tokens, [](UnwrappedLineNode &LineNode) {
1367 return LineNode.Tok->is(tok::at);
1372 if (Next->is(tok::exclaim) && PreviousMustBeValue)
1373 return addUnwrappedLine();
1374 bool NextMustBeValue = mustBeJSIdentOrValue(Keywords, Next);
1375 bool NextEndsTemplateExpr =
1376 Next->is(TT_TemplateString) && Next->TokenText.startswith("}");
1377 if (NextMustBeValue && !NextEndsTemplateExpr && !PreviousStartsTemplateExpr &&
1378 (PreviousMustBeValue ||
1379 Previous->isOneOf(tok::r_square, tok::r_paren, tok::plusplus,
1380 tok::minusminus))) {
1381 return addUnwrappedLine();
1383 if ((PreviousMustBeValue || Previous->is(tok::r_paren)) &&
1384 isJSDeclOrStmt(Keywords, Next)) {
1385 return addUnwrappedLine();
1389 void UnwrappedLineParser::parseStructuralElement(
1390 bool IsTopLevel, TokenType NextLBracesType, IfStmtKind *IfKind,
1391 FormatToken **IfLeftBrace, bool *HasDoWhile, bool *HasLabel) {
1392 if (Style.Language == FormatStyle::LK_TableGen &&
1393 FormatTok->is(tok::pp_include)) {
1395 if (FormatTok->is(tok::string_literal))
1401 if (Style.isVerilog()) {
1402 if (Keywords.isVerilogStructuredProcedure(*FormatTok)) {
1403 parseForOrWhileLoop(/*HasParens=*/false);
1406 if (FormatTok->isOneOf(Keywords.kw_foreach, Keywords.kw_repeat)) {
1407 parseForOrWhileLoop();
1410 if (FormatTok->isOneOf(tok::kw_restrict, Keywords.kw_assert,
1411 Keywords.kw_assume, Keywords.kw_cover)) {
1412 parseIfThenElse(IfKind, /*KeepBraces=*/false, /*IsVerilogAssert=*/true);
1416 // Skip things that can exist before keywords like 'if' and 'case'.
1418 if (FormatTok->isOneOf(Keywords.kw_priority, Keywords.kw_unique,
1419 Keywords.kw_unique0)) {
1421 } else if (FormatTok->is(tok::l_paren) &&
1422 Tokens->peekNextToken()->is(tok::star)) {
1430 // Tokens that only make sense at the beginning of a line.
1431 switch (FormatTok->Tok.getKind()) {
1434 if (FormatTok->is(tok::l_brace)) {
1435 FormatTok->setFinalizedType(TT_InlineASMBrace);
1437 while (FormatTok && !eof()) {
1438 if (FormatTok->is(tok::r_brace)) {
1439 FormatTok->setFinalizedType(TT_InlineASMBrace);
1444 FormatTok->Finalized = true;
1449 case tok::kw_namespace:
1452 case tok::kw_public:
1453 case tok::kw_protected:
1454 case tok::kw_private:
1455 if (Style.Language == FormatStyle::LK_Java || Style.isJavaScript() ||
1459 parseAccessSpecifier();
1463 if (Style.isJavaScript() && Line->MustBeDeclaration) {
1464 // field/method declaration.
1467 FormatToken *Tok = parseIfThenElse(IfKind);
1474 if (Style.isJavaScript() && Line->MustBeDeclaration) {
1475 // field/method declaration.
1478 parseForOrWhileLoop();
1481 if (Style.isJavaScript() && Line->MustBeDeclaration) {
1482 // field/method declaration.
1489 case tok::kw_switch:
1490 if (Style.isJavaScript() && Line->MustBeDeclaration) {
1491 // 'switch: string' field declaration.
1496 case tok::kw_default:
1497 // In Verilog default along with other labels are handled in the next loop.
1498 if (Style.isVerilog())
1500 if (Style.isJavaScript() && Line->MustBeDeclaration) {
1501 // 'default: string' field declaration.
1505 if (FormatTok->is(tok::colon)) {
1506 FormatTok->setFinalizedType(TT_CaseLabelColon);
1510 // e.g. "default void f() {}" in a Java interface.
1513 // Proto: there are no switch/case statements.
1514 if (Style.isProto()) {
1518 if (Style.isVerilog()) {
1523 if (Style.isJavaScript() && Line->MustBeDeclaration) {
1524 // 'case: string' field declaration.
1532 if (Style.isJavaScript() && Line->MustBeDeclaration) {
1533 // field/method declaration.
1538 case tok::kw_extern:
1540 if (Style.isVerilog()) {
1541 // In Verilog and extern module declaration looks like a start of module.
1542 // But there is no body and endmodule. So we handle it separately.
1543 if (Keywords.isVerilogHierarchy(*FormatTok)) {
1544 parseVerilogHierarchyHeader();
1547 } else if (FormatTok->is(tok::string_literal)) {
1549 if (FormatTok->is(tok::l_brace)) {
1550 if (Style.BraceWrapping.AfterExternBlock)
1552 // Either we indent or for backwards compatibility we follow the
1553 // AfterExternBlock style.
1554 unsigned AddLevels =
1555 (Style.IndentExternBlock == FormatStyle::IEBS_Indent) ||
1556 (Style.BraceWrapping.AfterExternBlock &&
1557 Style.IndentExternBlock ==
1558 FormatStyle::IEBS_AfterExternBlock)
1561 parseBlock(/*MustBeDeclaration=*/true, AddLevels);
1567 case tok::kw_export:
1568 if (Style.isJavaScript()) {
1569 parseJavaScriptEs6ImportExport();
1572 if (Style.isCpp()) {
1574 if (FormatTok->is(tok::kw_namespace)) {
1578 if (FormatTok->is(Keywords.kw_import) && parseModuleImport())
1582 case tok::kw_inline:
1584 if (FormatTok->is(tok::kw_namespace)) {
1589 case tok::identifier:
1590 if (FormatTok->is(TT_ForEachMacro)) {
1591 parseForOrWhileLoop();
1594 if (FormatTok->is(TT_MacroBlockBegin)) {
1595 parseBlock(/*MustBeDeclaration=*/false, /*AddLevels=*/1u,
1596 /*MunchSemi=*/false);
1599 if (FormatTok->is(Keywords.kw_import)) {
1600 if (Style.isJavaScript()) {
1601 parseJavaScriptEs6ImportExport();
1604 if (Style.Language == FormatStyle::LK_Proto) {
1606 if (FormatTok->is(tok::kw_public))
1608 if (!FormatTok->is(tok::string_literal))
1611 if (FormatTok->is(tok::semi))
1616 if (Style.isCpp() && parseModuleImport())
1619 if (Style.isCpp() &&
1620 FormatTok->isOneOf(Keywords.kw_signals, Keywords.kw_qsignals,
1621 Keywords.kw_slots, Keywords.kw_qslots)) {
1623 if (FormatTok->is(tok::colon)) {
1629 if (Style.isCpp() && FormatTok->is(TT_StatementMacro)) {
1630 parseStatementMacro();
1633 if (Style.isCpp() && FormatTok->is(TT_NamespaceMacro)) {
1637 // In all other cases, parse the declaration.
1643 const FormatToken *Previous = FormatTok->Previous;
1644 switch (FormatTok->Tok.getKind()) {
1647 if (FormatTok->is(tok::l_brace)) {
1651 } else if (Style.Language == FormatStyle::LK_Java &&
1652 FormatTok->is(Keywords.kw_interface)) {
1656 switch (FormatTok->Tok.getObjCKeywordID()) {
1657 case tok::objc_public:
1658 case tok::objc_protected:
1659 case tok::objc_package:
1660 case tok::objc_private:
1661 return parseAccessSpecifier();
1662 case tok::objc_interface:
1663 case tok::objc_implementation:
1664 return parseObjCInterfaceOrImplementation();
1665 case tok::objc_protocol:
1666 if (parseObjCProtocol())
1670 return; // Handled by the caller.
1671 case tok::objc_optional:
1672 case tok::objc_required:
1676 case tok::objc_autoreleasepool:
1678 if (FormatTok->is(tok::l_brace)) {
1679 if (Style.BraceWrapping.AfterControlStatement ==
1680 FormatStyle::BWACS_Always) {
1687 case tok::objc_synchronized:
1689 if (FormatTok->is(tok::l_paren)) {
1690 // Skip synchronization object
1693 if (FormatTok->is(tok::l_brace)) {
1694 if (Style.BraceWrapping.AfterControlStatement ==
1695 FormatStyle::BWACS_Always) {
1703 // This branch isn't strictly necessary (the kw_try case below would
1704 // do this too after the tok::at is parsed above). But be explicit.
1711 case tok::kw_requires: {
1712 if (Style.isCpp()) {
1713 bool ParsedClause = parseRequires();
1722 // Ignore if this is part of "template <enum ...".
1723 if (Previous && Previous->is(tok::less)) {
1728 // parseEnum falls through and does not yet add an unwrapped line as an
1729 // enum definition can start a structural element.
1732 // This only applies to C++ and Verilog.
1733 if (!Style.isCpp() && !Style.isVerilog()) {
1738 case tok::kw_typedef:
1740 if (FormatTok->isOneOf(Keywords.kw_NS_ENUM, Keywords.kw_NS_OPTIONS,
1741 Keywords.kw_CF_ENUM, Keywords.kw_CF_OPTIONS,
1742 Keywords.kw_CF_CLOSED_ENUM,
1743 Keywords.kw_NS_CLOSED_ENUM)) {
1748 if (Style.isVerilog()) {
1754 case tok::kw_struct:
1756 if (parseStructLike())
1761 // In Java, classes have an implicit static member "class".
1762 if (Style.Language == FormatStyle::LK_Java && FormatTok &&
1763 FormatTok->is(tok::kw_class)) {
1766 if (Style.isJavaScript() && FormatTok &&
1767 FormatTok->Tok.getIdentifierInfo()) {
1768 // JavaScript only has pseudo keywords, all keywords are allowed to
1769 // appear in "IdentifierName" positions. See http://es5.github.io/#x7.6
1780 case tok::l_paren: {
1782 // Break the unwrapped line if a K&R C function definition has a parameter
1784 if (!IsTopLevel || !Style.isCpp() || !Previous || eof())
1786 if (isC78ParameterDecl(FormatTok,
1787 Tokens->peekNextToken(/*SkipComment=*/true),
1794 case tok::kw_operator:
1796 if (FormatTok->isBinaryOperator())
1801 // Block return type.
1802 if (FormatTok->Tok.isAnyIdentifier() ||
1803 FormatTok->isSimpleTypeSpecifier()) {
1805 // Return types: pointers are ok too.
1806 while (FormatTok->is(tok::star))
1809 // Block argument list.
1810 if (FormatTok->is(tok::l_paren))
1813 if (FormatTok->is(tok::l_brace))
1817 if (NextLBracesType != TT_Unknown)
1818 FormatTok->setFinalizedType(NextLBracesType);
1819 if (!tryToParsePropertyAccessor() && !tryToParseBracedList()) {
1820 // A block outside of parentheses must be the last part of a
1821 // structural element.
1822 // FIXME: Figure out cases where this is not true, and add projections
1823 // for them (the one we know is missing are lambdas).
1824 if (Style.Language == FormatStyle::LK_Java &&
1825 Line->Tokens.front().Tok->is(Keywords.kw_synchronized)) {
1826 // If necessary, we could set the type to something different than
1827 // TT_FunctionLBrace.
1828 if (Style.BraceWrapping.AfterControlStatement ==
1829 FormatStyle::BWACS_Always) {
1832 } else if (Style.BraceWrapping.AfterFunction) {
1835 FormatTok->setFinalizedType(TT_FunctionLBrace);
1840 // Otherwise this was a braced init list, and the structural
1841 // element continues.
1844 if (Style.isJavaScript() && Line->MustBeDeclaration) {
1845 // field/method declaration.
1849 // We arrive here when parsing function-try blocks.
1850 if (Style.BraceWrapping.AfterFunction)
1854 case tok::identifier: {
1855 if (Style.isCSharp() && FormatTok->is(Keywords.kw_where) &&
1856 Line->MustBeDeclaration) {
1858 parseCSharpGenericTypeConstraint();
1861 if (FormatTok->is(TT_MacroBlockEnd)) {
1866 // Function declarations (as opposed to function expressions) are parsed
1867 // on their own unwrapped line by continuing this loop. Function
1868 // expressions (functions that are not on their own line) must not create
1869 // a new unwrapped line, so they are special cased below.
1870 size_t TokenCount = Line->Tokens.size();
1871 if (Style.isJavaScript() && FormatTok->is(Keywords.kw_function) &&
1872 (TokenCount > 1 || (TokenCount == 1 && !Line->Tokens.front().Tok->is(
1873 Keywords.kw_async)))) {
1874 tryToParseJSFunction();
1877 if ((Style.isJavaScript() || Style.Language == FormatStyle::LK_Java) &&
1878 FormatTok->is(Keywords.kw_interface)) {
1879 if (Style.isJavaScript()) {
1880 // In JavaScript/TypeScript, "interface" can be used as a standalone
1881 // identifier, e.g. in `var interface = 1;`. If "interface" is
1882 // followed by another identifier, it is very like to be an actual
1883 // interface declaration.
1884 unsigned StoredPosition = Tokens->getPosition();
1885 FormatToken *Next = Tokens->getNextToken();
1886 FormatTok = Tokens->setPosition(StoredPosition);
1887 if (!mustBeJSIdent(Keywords, Next)) {
1897 if (Style.isVerilog()) {
1898 if (FormatTok->is(Keywords.kw_table)) {
1899 parseVerilogTable();
1902 if (Keywords.isVerilogBegin(*FormatTok) ||
1903 Keywords.isVerilogHierarchy(*FormatTok)) {
1910 if (!Style.isCpp() && FormatTok->is(Keywords.kw_interface)) {
1911 if (parseStructLike())
1916 if (Style.isCpp() && FormatTok->is(TT_StatementMacro)) {
1917 parseStatementMacro();
1921 // See if the following token should start a new unwrapped line.
1922 StringRef Text = FormatTok->TokenText;
1924 FormatToken *PreviousToken = FormatTok;
1927 // JS doesn't have macros, and within classes colons indicate fields, not
1929 if (Style.isJavaScript())
1932 auto OneTokenSoFar = [&]() {
1933 auto I = Line->Tokens.begin(), E = Line->Tokens.end();
1934 while (I != E && I->Tok->is(tok::comment))
1936 while (I != E && Style.isVerilog() && I->Tok->is(tok::hash))
1938 return I != E && (++I == E);
1940 if (OneTokenSoFar()) {
1941 // In Verilog labels can be any expression, so we don't do them here.
1942 if (!Style.isVerilog() && FormatTok->is(tok::colon) &&
1943 !Line->MustBeDeclaration) {
1944 Line->Tokens.begin()->Tok->MustBreakBefore = true;
1945 FormatTok->setFinalizedType(TT_GotoLabelColon);
1946 parseLabel(!Style.IndentGotoLabels);
1951 // Recognize function-like macro usages without trailing semicolon as
1952 // well as free-standing macros like Q_OBJECT.
1953 bool FunctionLike = FormatTok->is(tok::l_paren);
1957 bool FollowedByNewline =
1958 CommentsBeforeNextToken.empty()
1959 ? FormatTok->NewlinesBefore > 0
1960 : CommentsBeforeNextToken.front()->NewlinesBefore > 0;
1962 if (FollowedByNewline && (Text.size() >= 5 || FunctionLike) &&
1963 tokenCanStartNewLine(*FormatTok) && Text == Text.upper()) {
1964 if (PreviousToken->isNot(TT_UntouchableMacroFunc))
1965 PreviousToken->setFinalizedType(TT_FunctionLikeOrFreestandingMacro);
1973 if ((Style.isJavaScript() || Style.isCSharp()) &&
1974 FormatTok->is(TT_FatArrow)) {
1975 tryToParseChildBlock();
1980 if (FormatTok->is(tok::l_brace)) {
1981 // Block kind should probably be set to BK_BracedInit for any language.
1982 // C# needs this change to ensure that array initialisers and object
1983 // initialisers are indented the same way.
1984 if (Style.isCSharp())
1985 FormatTok->setBlockKind(BK_BracedInit);
1988 } else if (Style.Language == FormatStyle::LK_Proto &&
1989 FormatTok->is(tok::less)) {
1991 parseBracedList(/*ContinueOnSemicolons=*/false, /*IsEnum=*/false,
1992 /*ClosingBraceKind=*/tok::greater);
2002 // Proto: there are no switch/case statements.
2003 if (Style.isProto()) {
2007 // In Verilog switch is called case.
2008 if (Style.isVerilog()) {
2013 if (Style.isJavaScript() && Line->MustBeDeclaration) {
2014 // 'case: string' field declaration.
2020 case tok::kw_default:
2022 if (Style.isVerilog()) {
2023 if (FormatTok->is(tok::colon)) {
2024 // The label will be handled in the next iteration.
2027 if (FormatTok->is(Keywords.kw_clocking)) {
2028 // A default clocking block.
2033 parseVerilogCaseLabel();
2039 if (Style.isVerilog()) {
2040 parseVerilogCaseLabel();
2051 bool UnwrappedLineParser::tryToParsePropertyAccessor() {
2052 assert(FormatTok->is(tok::l_brace));
2053 if (!Style.isCSharp())
2055 // See if it's a property accessor.
2056 if (FormatTok->Previous->isNot(tok::identifier))
2059 // See if we are inside a property accessor.
2061 // Record the current tokenPosition so that we can advance and
2062 // reset the current token. `Next` is not set yet so we need
2063 // another way to advance along the token stream.
2064 unsigned int StoredPosition = Tokens->getPosition();
2065 FormatToken *Tok = Tokens->getNextToken();
2067 // A trivial property accessor is of the form:
2068 // { [ACCESS_SPECIFIER] [get]; [ACCESS_SPECIFIER] [set|init] }
2069 // Track these as they do not require line breaks to be introduced.
2070 bool HasSpecialAccessor = false;
2071 bool IsTrivialPropertyAccessor = true;
2073 if (Tok->isOneOf(tok::semi, tok::kw_public, tok::kw_private,
2074 tok::kw_protected, Keywords.kw_internal, Keywords.kw_get,
2075 Keywords.kw_init, Keywords.kw_set)) {
2076 if (Tok->isOneOf(Keywords.kw_get, Keywords.kw_init, Keywords.kw_set))
2077 HasSpecialAccessor = true;
2078 Tok = Tokens->getNextToken();
2081 if (Tok->isNot(tok::r_brace))
2082 IsTrivialPropertyAccessor = false;
2086 if (!HasSpecialAccessor) {
2087 Tokens->setPosition(StoredPosition);
2091 // Try to parse the property accessor:
2092 // https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/properties
2093 Tokens->setPosition(StoredPosition);
2094 if (!IsTrivialPropertyAccessor && Style.BraceWrapping.AfterFunction)
2098 switch (FormatTok->Tok.getKind()) {
2101 if (FormatTok->is(tok::equal)) {
2102 while (!eof() && FormatTok->isNot(tok::semi))
2110 parseBlock(/*MustBeDeclaration=*/true);
2115 if (FormatTok->is(TT_FatArrow)) {
2119 } while (!eof() && FormatTok->isNot(tok::semi));
2128 if (FormatTok->isOneOf(Keywords.kw_get, Keywords.kw_init,
2130 !IsTrivialPropertyAccessor) {
2131 // Non-trivial get/set needs to be on its own line.
2138 // Unreachable for well-formed code (paired '{' and '}').
2142 bool UnwrappedLineParser::tryToParseLambda() {
2143 assert(FormatTok->is(tok::l_square));
2144 if (!Style.isCpp()) {
2148 FormatToken &LSquare = *FormatTok;
2149 if (!tryToParseLambdaIntroducer())
2152 bool SeenArrow = false;
2153 bool InTemplateParameterList = false;
2155 while (FormatTok->isNot(tok::l_brace)) {
2156 if (FormatTok->isSimpleTypeSpecifier()) {
2160 switch (FormatTok->Tok.getKind()) {
2164 parseParens(/*AmpAmpTokenType=*/TT_PointerOrReference);
2170 assert(FormatTok->Previous);
2171 if (FormatTok->Previous->is(tok::r_square))
2172 InTemplateParameterList = true;
2177 case tok::kw_template:
2178 case tok::kw_typename:
2182 case tok::kw_constexpr:
2183 case tok::kw_consteval:
2186 case tok::identifier:
2187 case tok::numeric_constant:
2188 case tok::coloncolon:
2189 case tok::kw_mutable:
2190 case tok::kw_noexcept:
2191 case tok::kw_static:
2194 // Specialization of a template with an integer parameter can contain
2195 // arithmetic, logical, comparison and ternary operators.
2197 // FIXME: This also accepts sequences of operators that are not in the scope
2198 // of a template argument list.
2200 // In a C++ lambda a template type can only occur after an arrow. We use
2201 // this as an heuristic to distinguish between Objective-C expressions
2202 // followed by an `a->b` expression, such as:
2203 // ([obj func:arg] + a->b)
2204 // Otherwise the code below would parse as a lambda.
2206 // FIXME: This heuristic is incorrect for C++20 generic lambdas with
2207 // explicit template lists: []<bool b = true && false>(U &&u){}
2219 case tok::equalequal:
2220 case tok::exclaimequal:
2221 case tok::greaterequal:
2222 case tok::lessequal:
2228 if (SeenArrow || InTemplateParameterList) {
2234 // This might or might not actually be a lambda arrow (this could be an
2235 // ObjC method invocation followed by a dereferencing arrow). We might
2236 // reset this back to TT_Unknown in TokenAnnotator.
2237 FormatTok->setFinalizedType(TT_LambdaArrow);
2241 case tok::kw_requires: {
2242 auto *RequiresToken = FormatTok;
2244 parseRequiresClause(RequiresToken);
2251 FormatTok->setFinalizedType(TT_LambdaLBrace);
2252 LSquare.setFinalizedType(TT_LambdaLSquare);
2257 bool UnwrappedLineParser::tryToParseLambdaIntroducer() {
2258 const FormatToken *Previous = FormatTok->Previous;
2259 const FormatToken *LeftSquare = FormatTok;
2261 if ((Previous && ((Previous->Tok.getIdentifierInfo() &&
2262 !Previous->isOneOf(tok::kw_return, tok::kw_co_await,
2263 tok::kw_co_yield, tok::kw_co_return)) ||
2264 Previous->closesScope())) ||
2265 LeftSquare->isCppStructuredBinding(Style)) {
2268 if (FormatTok->is(tok::l_square))
2270 if (FormatTok->is(tok::r_square)) {
2271 const FormatToken *Next = Tokens->peekNextToken(/*SkipComment=*/true);
2272 if (Next->is(tok::greater))
2275 parseSquare(/*LambdaIntroducer=*/true);
2279 void UnwrappedLineParser::tryToParseJSFunction() {
2280 assert(FormatTok->is(Keywords.kw_function) ||
2281 FormatTok->startsSequence(Keywords.kw_async, Keywords.kw_function));
2282 if (FormatTok->is(Keywords.kw_async))
2284 // Consume "function".
2287 // Consume * (generator function). Treat it like C++'s overloaded operators.
2288 if (FormatTok->is(tok::star)) {
2289 FormatTok->setFinalizedType(TT_OverloadedOperator);
2293 // Consume function name.
2294 if (FormatTok->is(tok::identifier))
2297 if (FormatTok->isNot(tok::l_paren))
2300 // Parse formal parameter list.
2303 if (FormatTok->is(tok::colon)) {
2304 // Parse a type definition.
2307 // Eat the type declaration. For braced inline object types, balance braces,
2308 // otherwise just parse until finding an l_brace for the function body.
2309 if (FormatTok->is(tok::l_brace))
2310 tryToParseBracedList();
2312 while (!FormatTok->isOneOf(tok::l_brace, tok::semi) && !eof())
2316 if (FormatTok->is(tok::semi))
2322 bool UnwrappedLineParser::tryToParseBracedList() {
2323 if (FormatTok->is(BK_Unknown))
2324 calculateBraceTypes();
2325 assert(FormatTok->isNot(BK_Unknown));
2326 if (FormatTok->is(BK_Block))
2333 bool UnwrappedLineParser::tryToParseChildBlock() {
2334 assert(Style.isJavaScript() || Style.isCSharp());
2335 assert(FormatTok->is(TT_FatArrow));
2336 // Fat arrows (=>) have tok::TokenKind tok::equal but TokenType TT_FatArrow.
2337 // They always start an expression or a child block if followed by a curly
2340 if (FormatTok->isNot(tok::l_brace))
2346 bool UnwrappedLineParser::parseBracedList(bool ContinueOnSemicolons,
2348 tok::TokenKind ClosingBraceKind) {
2349 bool HasError = false;
2351 // FIXME: Once we have an expression parser in the UnwrappedLineParser,
2352 // replace this by using parseAssignmentExpression() inside.
2354 if (Style.isCSharp() && FormatTok->is(TT_FatArrow) &&
2355 tryToParseChildBlock()) {
2358 if (Style.isJavaScript()) {
2359 if (FormatTok->is(Keywords.kw_function) ||
2360 FormatTok->startsSequence(Keywords.kw_async, Keywords.kw_function)) {
2361 tryToParseJSFunction();
2364 if (FormatTok->is(tok::l_brace)) {
2365 // Could be a method inside of a braced list `{a() { return 1; }}`.
2366 if (tryToParseBracedList())
2371 if (FormatTok->Tok.getKind() == ClosingBraceKind) {
2372 if (IsEnum && !Style.AllowShortEnumsOnASingleLine)
2377 switch (FormatTok->Tok.getKind()) {
2379 if (Style.isCSharp())
2386 // JavaScript can just have free standing methods and getters/setters in
2387 // object literals. Detect them by a "{" following ")".
2388 if (Style.isJavaScript()) {
2389 if (FormatTok->is(tok::l_brace))
2395 // Assume there are no blocks inside a braced init list apart
2396 // from the ones we explicitly parse out (like lambdas).
2397 FormatTok->setBlockKind(BK_BracedInit);
2402 if (Style.Language == FormatStyle::LK_Proto ||
2403 ClosingBraceKind == tok::greater) {
2405 parseBracedList(/*ContinueOnSemicolons=*/false, /*IsEnum=*/false,
2406 /*ClosingBraceKind=*/tok::greater);
2412 // JavaScript (or more precisely TypeScript) can have semicolons in braced
2413 // lists (in so-called TypeMemberLists). Thus, the semicolon cannot be
2414 // used for error recovery if we have otherwise determined that this is
2416 if (Style.isJavaScript()) {
2421 if (!ContinueOnSemicolons)
2427 if (IsEnum && !Style.AllowShortEnumsOnASingleLine)
2438 /// \brief Parses a pair of parentheses (and everything between them).
2439 /// \param AmpAmpTokenType If different than TT_Unknown sets this type for all
2440 /// double ampersands. This applies for all nested scopes as well.
2442 /// Returns whether there is a `=` token between the parentheses.
2443 bool UnwrappedLineParser::parseParens(TokenType AmpAmpTokenType) {
2444 assert(FormatTok->is(tok::l_paren) && "'(' expected.");
2445 auto *LeftParen = FormatTok;
2446 bool SeenEqual = false;
2447 const bool MightBeStmtExpr = Tokens->peekNextToken()->is(tok::l_brace);
2450 switch (FormatTok->Tok.getKind()) {
2452 if (parseParens(AmpAmpTokenType))
2454 if (Style.Language == FormatStyle::LK_Java && FormatTok->is(tok::l_brace))
2458 if (!MightBeStmtExpr &&
2459 Style.RemoveParentheses > FormatStyle::RPS_Leave) {
2460 const auto *Prev = LeftParen->Previous;
2461 const auto *Next = Tokens->peekNextToken();
2462 const bool DoubleParens =
2463 Prev && Prev->is(tok::l_paren) && Next && Next->is(tok::r_paren);
2464 const auto *PrevPrev = Prev ? Prev->getPreviousNonComment() : nullptr;
2465 const bool Blacklisted =
2467 (PrevPrev->is(tok::kw___attribute) ||
2469 (PrevPrev->isOneOf(tok::kw_if, tok::kw_while) ||
2470 PrevPrev->endsSequence(tok::kw_constexpr, tok::kw_if))));
2471 const bool ReturnParens =
2472 Style.RemoveParentheses == FormatStyle::RPS_ReturnStatement &&
2473 Prev && Prev->isOneOf(tok::kw_return, tok::kw_co_return) && Next &&
2474 Next->is(tok::semi);
2475 if ((DoubleParens && !Blacklisted) || ReturnParens) {
2476 LeftParen->Optional = true;
2477 FormatTok->Optional = true;
2483 // A "}" inside parenthesis is an error if there wasn't a matching "{".
2489 if (!tryToParseBracedList())
2494 if (FormatTok->is(tok::l_brace)) {
2501 if (Style.isCSharp() && FormatTok->is(TT_FatArrow))
2502 tryToParseChildBlock();
2507 if (Style.isJavaScript())
2508 parseRecord(/*ParseAsExpr=*/true);
2512 case tok::identifier:
2513 if (Style.isJavaScript() &&
2514 (FormatTok->is(Keywords.kw_function) ||
2515 FormatTok->startsSequence(Keywords.kw_async,
2516 Keywords.kw_function))) {
2517 tryToParseJSFunction();
2522 case tok::kw_requires: {
2523 auto RequiresToken = FormatTok;
2525 parseRequiresExpression(RequiresToken);
2529 if (AmpAmpTokenType != TT_Unknown)
2530 FormatTok->setFinalizedType(AmpAmpTokenType);
2540 void UnwrappedLineParser::parseSquare(bool LambdaIntroducer) {
2541 if (!LambdaIntroducer) {
2542 assert(FormatTok->is(tok::l_square) && "'[' expected.");
2543 if (tryToParseLambda())
2547 switch (FormatTok->Tok.getKind()) {
2555 // A "}" inside parenthesis is an error if there wasn't a matching "{".
2560 case tok::l_brace: {
2561 if (!tryToParseBracedList())
2567 if (FormatTok->is(tok::l_brace)) {
2579 void UnwrappedLineParser::keepAncestorBraces() {
2580 if (!Style.RemoveBracesLLVM)
2583 const int MaxNestingLevels = 2;
2584 const int Size = NestedTooDeep.size();
2585 if (Size >= MaxNestingLevels)
2586 NestedTooDeep[Size - MaxNestingLevels] = true;
2587 NestedTooDeep.push_back(false);
2590 static FormatToken *getLastNonComment(const UnwrappedLine &Line) {
2591 for (const auto &Token : llvm::reverse(Line.Tokens))
2592 if (Token.Tok->isNot(tok::comment))
2598 void UnwrappedLineParser::parseUnbracedBody(bool CheckEOF) {
2599 FormatToken *Tok = nullptr;
2601 if (Style.InsertBraces && !Line->InPPDirective && !Line->Tokens.empty() &&
2602 PreprocessorDirectives.empty() && FormatTok->isNot(tok::semi)) {
2603 Tok = Style.BraceWrapping.AfterControlStatement == FormatStyle::BWACS_Never
2604 ? getLastNonComment(*Line)
2605 : Line->Tokens.back().Tok;
2607 if (Tok->BraceCount < 0) {
2608 assert(Tok->BraceCount == -1);
2611 Tok->BraceCount = -1;
2617 parseStructuralElement();
2620 assert(!Line->InPPDirective);
2622 for (const auto &L : llvm::reverse(*CurrentLines)) {
2623 if (!L.InPPDirective && getLastNonComment(L)) {
2624 Tok = L.Tokens.back().Tok;
2632 if (CheckEOF && eof())
2638 static void markOptionalBraces(FormatToken *LeftBrace) {
2642 assert(LeftBrace->is(tok::l_brace));
2644 FormatToken *RightBrace = LeftBrace->MatchingParen;
2646 assert(!LeftBrace->Optional);
2650 assert(RightBrace->is(tok::r_brace));
2651 assert(RightBrace->MatchingParen == LeftBrace);
2652 assert(LeftBrace->Optional == RightBrace->Optional);
2654 LeftBrace->Optional = true;
2655 RightBrace->Optional = true;
2658 void UnwrappedLineParser::handleAttributes() {
2659 // Handle AttributeMacro, e.g. `if (x) UNLIKELY`.
2660 if (FormatTok->is(TT_AttributeMacro))
2662 if (FormatTok->is(tok::l_square))
2663 handleCppAttributes();
2666 bool UnwrappedLineParser::handleCppAttributes() {
2667 // Handle [[likely]] / [[unlikely]] attributes.
2668 assert(FormatTok->is(tok::l_square));
2669 if (!tryToParseSimpleAttribute())
2675 /// Returns whether \c Tok begins a block.
2676 bool UnwrappedLineParser::isBlockBegin(const FormatToken &Tok) const {
2677 // FIXME: rename the function or make
2678 // Tok.isOneOf(tok::l_brace, TT_MacroBlockBegin) work.
2679 return Style.isVerilog() ? Keywords.isVerilogBegin(Tok)
2680 : Tok.is(tok::l_brace);
2683 FormatToken *UnwrappedLineParser::parseIfThenElse(IfStmtKind *IfKind,
2685 bool IsVerilogAssert) {
2686 assert((FormatTok->is(tok::kw_if) ||
2687 (Style.isVerilog() &&
2688 FormatTok->isOneOf(tok::kw_restrict, Keywords.kw_assert,
2689 Keywords.kw_assume, Keywords.kw_cover))) &&
2693 if (IsVerilogAssert) {
2694 // Handle `assert #0` and `assert final`.
2695 if (FormatTok->is(Keywords.kw_verilogHash)) {
2697 if (FormatTok->is(tok::numeric_constant))
2699 } else if (FormatTok->isOneOf(Keywords.kw_final, Keywords.kw_property,
2700 Keywords.kw_sequence)) {
2705 // Handle `if !consteval`.
2706 if (FormatTok->is(tok::exclaim))
2709 bool KeepIfBraces = true;
2710 if (FormatTok->is(tok::kw_consteval)) {
2713 KeepIfBraces = !Style.RemoveBracesLLVM || KeepBraces;
2714 if (FormatTok->isOneOf(tok::kw_constexpr, tok::identifier))
2716 if (FormatTok->is(tok::l_paren)) {
2717 FormatTok->setFinalizedType(TT_ConditionLParen);
2722 // The then action is optional in Verilog assert statements.
2723 if (IsVerilogAssert && FormatTok->is(tok::semi)) {
2729 bool NeedsUnwrappedLine = false;
2730 keepAncestorBraces();
2732 FormatToken *IfLeftBrace = nullptr;
2733 IfStmtKind IfBlockKind = IfStmtKind::NotIf;
2735 if (isBlockBegin(*FormatTok)) {
2736 FormatTok->setFinalizedType(TT_ControlStatementLBrace);
2737 IfLeftBrace = FormatTok;
2738 CompoundStatementIndenter Indenter(this, Style, Line->Level);
2739 parseBlock(/*MustBeDeclaration=*/false, /*AddLevels=*/1u,
2740 /*MunchSemi=*/true, KeepIfBraces, &IfBlockKind);
2741 if (Style.BraceWrapping.BeforeElse)
2744 NeedsUnwrappedLine = true;
2745 } else if (IsVerilogAssert && FormatTok->is(tok::kw_else)) {
2748 parseUnbracedBody();
2751 if (Style.RemoveBracesLLVM) {
2752 assert(!NestedTooDeep.empty());
2753 KeepIfBraces = KeepIfBraces ||
2754 (IfLeftBrace && !IfLeftBrace->MatchingParen) ||
2755 NestedTooDeep.back() || IfBlockKind == IfStmtKind::IfOnly ||
2756 IfBlockKind == IfStmtKind::IfElseIf;
2759 bool KeepElseBraces = KeepIfBraces;
2760 FormatToken *ElseLeftBrace = nullptr;
2761 IfStmtKind Kind = IfStmtKind::IfOnly;
2763 if (FormatTok->is(tok::kw_else)) {
2764 if (Style.RemoveBracesLLVM) {
2765 NestedTooDeep.back() = false;
2766 Kind = IfStmtKind::IfElse;
2770 if (isBlockBegin(*FormatTok)) {
2771 const bool FollowedByIf = Tokens->peekNextToken()->is(tok::kw_if);
2772 FormatTok->setFinalizedType(TT_ElseLBrace);
2773 ElseLeftBrace = FormatTok;
2774 CompoundStatementIndenter Indenter(this, Style, Line->Level);
2775 IfStmtKind ElseBlockKind = IfStmtKind::NotIf;
2776 FormatToken *IfLBrace =
2777 parseBlock(/*MustBeDeclaration=*/false, /*AddLevels=*/1u,
2778 /*MunchSemi=*/true, KeepElseBraces, &ElseBlockKind);
2779 if (FormatTok->is(tok::kw_else)) {
2780 KeepElseBraces = KeepElseBraces ||
2781 ElseBlockKind == IfStmtKind::IfOnly ||
2782 ElseBlockKind == IfStmtKind::IfElseIf;
2783 } else if (FollowedByIf && IfLBrace && !IfLBrace->Optional) {
2784 KeepElseBraces = true;
2785 assert(ElseLeftBrace->MatchingParen);
2786 markOptionalBraces(ElseLeftBrace);
2789 } else if (!IsVerilogAssert && FormatTok->is(tok::kw_if)) {
2790 const FormatToken *Previous = Tokens->getPreviousToken();
2792 const bool IsPrecededByComment = Previous->is(tok::comment);
2793 if (IsPrecededByComment) {
2797 bool TooDeep = true;
2798 if (Style.RemoveBracesLLVM) {
2799 Kind = IfStmtKind::IfElseIf;
2800 TooDeep = NestedTooDeep.pop_back_val();
2802 ElseLeftBrace = parseIfThenElse(/*IfKind=*/nullptr, KeepIfBraces);
2803 if (Style.RemoveBracesLLVM)
2804 NestedTooDeep.push_back(TooDeep);
2805 if (IsPrecededByComment)
2808 parseUnbracedBody(/*CheckEOF=*/true);
2811 KeepIfBraces = KeepIfBraces || IfBlockKind == IfStmtKind::IfElse;
2812 if (NeedsUnwrappedLine)
2816 if (!Style.RemoveBracesLLVM)
2819 assert(!NestedTooDeep.empty());
2820 KeepElseBraces = KeepElseBraces ||
2821 (ElseLeftBrace && !ElseLeftBrace->MatchingParen) ||
2822 NestedTooDeep.back();
2824 NestedTooDeep.pop_back();
2826 if (!KeepIfBraces && !KeepElseBraces) {
2827 markOptionalBraces(IfLeftBrace);
2828 markOptionalBraces(ElseLeftBrace);
2829 } else if (IfLeftBrace) {
2830 FormatToken *IfRightBrace = IfLeftBrace->MatchingParen;
2832 assert(IfRightBrace->MatchingParen == IfLeftBrace);
2833 assert(!IfLeftBrace->Optional);
2834 assert(!IfRightBrace->Optional);
2835 IfLeftBrace->MatchingParen = nullptr;
2836 IfRightBrace->MatchingParen = nullptr;
2846 void UnwrappedLineParser::parseTryCatch() {
2847 assert(FormatTok->isOneOf(tok::kw_try, tok::kw___try) && "'try' expected");
2849 bool NeedsUnwrappedLine = false;
2850 if (FormatTok->is(tok::colon)) {
2851 // We are in a function try block, what comes is an initializer list.
2854 // In case identifiers were removed by clang-tidy, what might follow is
2855 // multiple commas in sequence - before the first identifier.
2856 while (FormatTok->is(tok::comma))
2859 while (FormatTok->is(tok::identifier)) {
2861 if (FormatTok->is(tok::l_paren))
2863 if (FormatTok->Previous && FormatTok->Previous->is(tok::identifier) &&
2864 FormatTok->is(tok::l_brace)) {
2867 } while (!FormatTok->is(tok::r_brace));
2871 // In case identifiers were removed by clang-tidy, what might follow is
2872 // multiple commas in sequence - after the first identifier.
2873 while (FormatTok->is(tok::comma))
2877 // Parse try with resource.
2878 if (Style.Language == FormatStyle::LK_Java && FormatTok->is(tok::l_paren))
2881 keepAncestorBraces();
2883 if (FormatTok->is(tok::l_brace)) {
2884 CompoundStatementIndenter Indenter(this, Style, Line->Level);
2886 if (Style.BraceWrapping.BeforeCatch)
2889 NeedsUnwrappedLine = true;
2890 } else if (!FormatTok->is(tok::kw_catch)) {
2891 // The C++ standard requires a compound-statement after a try.
2892 // If there's none, we try to assume there's a structuralElement
2893 // and try to continue.
2896 parseStructuralElement();
2900 if (FormatTok->is(tok::at))
2902 if (!(FormatTok->isOneOf(tok::kw_catch, Keywords.kw___except,
2903 tok::kw___finally) ||
2904 ((Style.Language == FormatStyle::LK_Java || Style.isJavaScript()) &&
2905 FormatTok->is(Keywords.kw_finally)) ||
2906 (FormatTok->isObjCAtKeyword(tok::objc_catch) ||
2907 FormatTok->isObjCAtKeyword(tok::objc_finally)))) {
2911 while (FormatTok->isNot(tok::l_brace)) {
2912 if (FormatTok->is(tok::l_paren)) {
2916 if (FormatTok->isOneOf(tok::semi, tok::r_brace, tok::eof)) {
2917 if (Style.RemoveBracesLLVM)
2918 NestedTooDeep.pop_back();
2923 NeedsUnwrappedLine = false;
2924 Line->MustBeDeclaration = false;
2925 CompoundStatementIndenter Indenter(this, Style, Line->Level);
2927 if (Style.BraceWrapping.BeforeCatch)
2930 NeedsUnwrappedLine = true;
2933 if (Style.RemoveBracesLLVM)
2934 NestedTooDeep.pop_back();
2936 if (NeedsUnwrappedLine)
2940 void UnwrappedLineParser::parseNamespace() {
2941 assert(FormatTok->isOneOf(tok::kw_namespace, TT_NamespaceMacro) &&
2942 "'namespace' expected");
2944 const FormatToken &InitialToken = *FormatTok;
2946 if (InitialToken.is(TT_NamespaceMacro)) {
2949 while (FormatTok->isOneOf(tok::identifier, tok::coloncolon, tok::kw_inline,
2950 tok::l_square, tok::period, tok::l_paren) ||
2951 (Style.isCSharp() && FormatTok->is(tok::kw_union))) {
2952 if (FormatTok->is(tok::l_square))
2954 else if (FormatTok->is(tok::l_paren))
2960 if (FormatTok->is(tok::l_brace)) {
2961 if (ShouldBreakBeforeBrace(Style, InitialToken))
2964 unsigned AddLevels =
2965 Style.NamespaceIndentation == FormatStyle::NI_All ||
2966 (Style.NamespaceIndentation == FormatStyle::NI_Inner &&
2967 DeclarationScopeStack.size() > 1)
2970 bool ManageWhitesmithsBraces =
2972 Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths;
2974 // If we're in Whitesmiths mode, indent the brace if we're not indenting
2976 if (ManageWhitesmithsBraces)
2979 // Munch the semicolon after a namespace. This is more common than one would
2980 // think. Putting the semicolon into its own line is very ugly.
2981 parseBlock(/*MustBeDeclaration=*/true, AddLevels, /*MunchSemi=*/true,
2982 /*KeepBraces=*/true, /*IfKind=*/nullptr,
2983 ManageWhitesmithsBraces);
2985 addUnwrappedLine(AddLevels > 0 ? LineLevel::Remove : LineLevel::Keep);
2987 if (ManageWhitesmithsBraces)
2990 // FIXME: Add error handling.
2993 void UnwrappedLineParser::parseNew() {
2994 assert(FormatTok->is(tok::kw_new) && "'new' expected");
2997 if (Style.isCSharp()) {
2999 // Handle constructor invocation, e.g. `new(field: value)`.
3000 if (FormatTok->is(tok::l_paren))
3003 // Handle array initialization syntax, e.g. `new[] {10, 20, 30}`.
3004 if (FormatTok->is(tok::l_brace))
3007 if (FormatTok->isOneOf(tok::semi, tok::comma))
3014 if (Style.Language != FormatStyle::LK_Java)
3017 // In Java, we can parse everything up to the parens, which aren't optional.
3019 // There should not be a ;, { or } before the new's open paren.
3020 if (FormatTok->isOneOf(tok::semi, tok::l_brace, tok::r_brace))
3023 // Consume the parens.
3024 if (FormatTok->is(tok::l_paren)) {
3027 // If there is a class body of an anonymous class, consume that as child.
3028 if (FormatTok->is(tok::l_brace))
3036 void UnwrappedLineParser::parseLoopBody(bool KeepBraces, bool WrapRightBrace) {
3037 keepAncestorBraces();
3039 if (isBlockBegin(*FormatTok)) {
3041 FormatTok->setFinalizedType(TT_ControlStatementLBrace);
3042 FormatToken *LeftBrace = FormatTok;
3043 CompoundStatementIndenter Indenter(this, Style, Line->Level);
3044 parseBlock(/*MustBeDeclaration=*/false, /*AddLevels=*/1u,
3045 /*MunchSemi=*/true, KeepBraces);
3047 assert(!NestedTooDeep.empty());
3048 if (!NestedTooDeep.back())
3049 markOptionalBraces(LeftBrace);
3054 parseUnbracedBody();
3058 NestedTooDeep.pop_back();
3061 void UnwrappedLineParser::parseForOrWhileLoop(bool HasParens) {
3062 assert((FormatTok->isOneOf(tok::kw_for, tok::kw_while, TT_ForEachMacro) ||
3063 (Style.isVerilog() &&
3064 FormatTok->isOneOf(Keywords.kw_always, Keywords.kw_always_comb,
3065 Keywords.kw_always_ff, Keywords.kw_always_latch,
3066 Keywords.kw_final, Keywords.kw_initial,
3067 Keywords.kw_foreach, Keywords.kw_forever,
3068 Keywords.kw_repeat))) &&
3069 "'for', 'while' or foreach macro expected");
3070 const bool KeepBraces = !Style.RemoveBracesLLVM ||
3071 !FormatTok->isOneOf(tok::kw_for, tok::kw_while);
3074 // JS' for await ( ...
3075 if (Style.isJavaScript() && FormatTok->is(Keywords.kw_await))
3077 if (Style.isCpp() && FormatTok->is(tok::kw_co_await))
3079 if (HasParens && FormatTok->is(tok::l_paren)) {
3080 // The type is only set for Verilog basically because we were afraid to
3081 // change the existing behavior for loops. See the discussion on D121756 for
3083 if (Style.isVerilog())
3084 FormatTok->setFinalizedType(TT_ConditionLParen);
3088 if (Style.isVerilog())
3089 parseVerilogSensitivityList();
3092 parseLoopBody(KeepBraces, /*WrapRightBrace=*/true);
3095 void UnwrappedLineParser::parseDoWhile() {
3096 assert(FormatTok->is(tok::kw_do) && "'do' expected");
3099 parseLoopBody(/*KeepBraces=*/true, Style.BraceWrapping.BeforeWhile);
3101 // FIXME: Add error handling.
3102 if (!FormatTok->is(tok::kw_while)) {
3107 // If in Whitesmiths mode, the line with the while() needs to be indented
3108 // to the same level as the block.
3109 if (Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths)
3113 parseStructuralElement();
3116 void UnwrappedLineParser::parseLabel(bool LeftAlignLabel) {
3118 unsigned OldLineLevel = Line->Level;
3119 if (Line->Level > 1 || (!Line->InPPDirective && Line->Level > 0))
3124 if (!Style.IndentCaseBlocks && CommentsBeforeNextToken.empty() &&
3125 FormatTok->is(tok::l_brace)) {
3127 CompoundStatementIndenter Indenter(this, Line->Level,
3128 Style.BraceWrapping.AfterCaseLabel,
3129 Style.BraceWrapping.IndentBraces);
3131 if (FormatTok->is(tok::kw_break)) {
3132 if (Style.BraceWrapping.AfterControlStatement ==
3133 FormatStyle::BWACS_Always) {
3135 if (!Style.IndentCaseBlocks &&
3136 Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths) {
3140 parseStructuralElement();
3144 if (FormatTok->is(tok::semi))
3148 Line->Level = OldLineLevel;
3149 if (FormatTok->isNot(tok::l_brace)) {
3150 parseStructuralElement();
3155 void UnwrappedLineParser::parseCaseLabel() {
3156 assert(FormatTok->is(tok::kw_case) && "'case' expected");
3158 // FIXME: fix handling of complex expressions here.
3161 if (FormatTok->is(tok::colon)) {
3162 FormatTok->setFinalizedType(TT_CaseLabelColon);
3169 void UnwrappedLineParser::parseSwitch() {
3170 assert(FormatTok->is(tok::kw_switch) && "'switch' expected");
3172 if (FormatTok->is(tok::l_paren))
3175 keepAncestorBraces();
3177 if (FormatTok->is(tok::l_brace)) {
3178 CompoundStatementIndenter Indenter(this, Style, Line->Level);
3184 parseStructuralElement();
3188 if (Style.RemoveBracesLLVM)
3189 NestedTooDeep.pop_back();
3192 // Operators that can follow a C variable.
3193 static bool isCOperatorFollowingVar(tok::TokenKind kind) {
3199 case tok::caretequal:
3203 case tok::equalequal:
3205 case tok::exclaimequal:
3207 case tok::greaterequal:
3208 case tok::greatergreater:
3209 case tok::greatergreaterequal:
3213 case tok::lessequal:
3215 case tok::lesslessequal:
3217 case tok::minusequal:
3218 case tok::minusminus:
3220 case tok::percentequal:
3223 case tok::pipeequal:
3226 case tok::plusequal:
3234 case tok::slashequal:
3236 case tok::starequal:
3243 void UnwrappedLineParser::parseAccessSpecifier() {
3244 FormatToken *AccessSpecifierCandidate = FormatTok;
3246 // Understand Qt's slots.
3247 if (FormatTok->isOneOf(Keywords.kw_slots, Keywords.kw_qslots))
3249 // Otherwise, we don't know what it is, and we'd better keep the next token.
3250 if (FormatTok->is(tok::colon)) {
3253 } else if (!FormatTok->is(tok::coloncolon) &&
3254 !isCOperatorFollowingVar(FormatTok->Tok.getKind())) {
3255 // Not a variable name nor namespace name.
3257 } else if (AccessSpecifierCandidate) {
3258 // Consider the access specifier to be a C identifier.
3259 AccessSpecifierCandidate->Tok.setKind(tok::identifier);
3263 /// \brief Parses a requires, decides if it is a clause or an expression.
3264 /// \pre The current token has to be the requires keyword.
3265 /// \returns true if it parsed a clause.
3266 bool clang::format::UnwrappedLineParser::parseRequires() {
3267 assert(FormatTok->is(tok::kw_requires) && "'requires' expected");
3268 auto RequiresToken = FormatTok;
3270 // We try to guess if it is a requires clause, or a requires expression. For
3271 // that we first consume the keyword and check the next token.
3274 switch (FormatTok->Tok.getKind()) {
3276 // This can only be an expression, never a clause.
3277 parseRequiresExpression(RequiresToken);
3280 // Clauses and expression can start with a paren, it's unclear what we have.
3283 // All other tokens can only be a clause.
3284 parseRequiresClause(RequiresToken);
3288 // Looking forward we would have to decide if there are function declaration
3289 // like arguments to the requires expression:
3291 // Or there is a constraint expression for the requires clause:
3292 // requires (C<T> && ...
3294 // But first let's look behind.
3295 auto *PreviousNonComment = RequiresToken->getPreviousNonComment();
3297 if (!PreviousNonComment ||
3298 PreviousNonComment->is(TT_RequiresExpressionLBrace)) {
3299 // If there is no token, or an expression left brace, we are a requires
3300 // clause within a requires expression.
3301 parseRequiresClause(RequiresToken);
3305 switch (PreviousNonComment->Tok.getKind()) {
3308 case tok::kw_noexcept:
3310 // This is a requires clause.
3311 parseRequiresClause(RequiresToken);
3315 // This can be either:
3316 // if (... && requires (T t) ...)
3318 // void member(...) && requires (C<T> ...
3319 // We check the one token before that for a const:
3320 // void member(...) const && requires (C<T> ...
3321 auto PrevPrev = PreviousNonComment->getPreviousNonComment();
3322 if (PrevPrev && PrevPrev->is(tok::kw_const)) {
3323 parseRequiresClause(RequiresToken);
3329 if (PreviousNonComment->isTypeOrIdentifier()) {
3330 // This is a requires clause.
3331 parseRequiresClause(RequiresToken);
3334 // It's an expression.
3335 parseRequiresExpression(RequiresToken);
3339 // Now we look forward and try to check if the paren content is a parameter
3340 // list. The parameters can be cv-qualified and contain references or
3342 // So we want basically to check for TYPE NAME, but TYPE can contain all kinds
3343 // of stuff: typename, const, *, &, &&, ::, identifiers.
3345 unsigned StoredPosition = Tokens->getPosition();
3346 FormatToken *NextToken = Tokens->getNextToken();
3348 auto PeekNext = [&Lookahead, &NextToken, this] {
3350 NextToken = Tokens->getNextToken();
3353 bool FoundType = false;
3354 bool LastWasColonColon = false;
3357 for (; Lookahead < 50; PeekNext()) {
3358 switch (NextToken->Tok.getKind()) {
3359 case tok::kw_volatile:
3362 FormatTok = Tokens->setPosition(StoredPosition);
3363 parseRequiresExpression(RequiresToken);
3367 FormatTok = Tokens->setPosition(StoredPosition);
3368 parseRequiresClause(RequiresToken);
3371 // Break out of the loop.
3374 case tok::coloncolon:
3375 LastWasColonColon = true;
3377 case tok::identifier:
3378 if (FoundType && !LastWasColonColon && OpenAngles == 0) {
3379 FormatTok = Tokens->setPosition(StoredPosition);
3380 parseRequiresExpression(RequiresToken);
3384 LastWasColonColon = false;
3393 if (NextToken->isSimpleTypeSpecifier()) {
3394 FormatTok = Tokens->setPosition(StoredPosition);
3395 parseRequiresExpression(RequiresToken);
3401 // This seems to be a complicated expression, just assume it's a clause.
3402 FormatTok = Tokens->setPosition(StoredPosition);
3403 parseRequiresClause(RequiresToken);
3407 /// \brief Parses a requires clause.
3408 /// \param RequiresToken The requires keyword token, which starts this clause.
3409 /// \pre We need to be on the next token after the requires keyword.
3410 /// \sa parseRequiresExpression
3412 /// Returns if it either has finished parsing the clause, or it detects, that
3413 /// the clause is incorrect.
3414 void UnwrappedLineParser::parseRequiresClause(FormatToken *RequiresToken) {
3415 assert(FormatTok->getPreviousNonComment() == RequiresToken);
3416 assert(RequiresToken->is(tok::kw_requires) && "'requires' expected");
3418 // If there is no previous token, we are within a requires expression,
3419 // otherwise we will always have the template or function declaration in front
3421 bool InRequiresExpression =
3422 !RequiresToken->Previous ||
3423 RequiresToken->Previous->is(TT_RequiresExpressionLBrace);
3425 RequiresToken->setFinalizedType(InRequiresExpression
3426 ? TT_RequiresClauseInARequiresExpression
3427 : TT_RequiresClause);
3429 // NOTE: parseConstraintExpression is only ever called from this function.
3430 // It could be inlined into here.
3431 parseConstraintExpression();
3433 if (!InRequiresExpression)
3434 FormatTok->Previous->ClosesRequiresClause = true;
3437 /// \brief Parses a requires expression.
3438 /// \param RequiresToken The requires keyword token, which starts this clause.
3439 /// \pre We need to be on the next token after the requires keyword.
3440 /// \sa parseRequiresClause
3442 /// Returns if it either has finished parsing the expression, or it detects,
3443 /// that the expression is incorrect.
3444 void UnwrappedLineParser::parseRequiresExpression(FormatToken *RequiresToken) {
3445 assert(FormatTok->getPreviousNonComment() == RequiresToken);
3446 assert(RequiresToken->is(tok::kw_requires) && "'requires' expected");
3448 RequiresToken->setFinalizedType(TT_RequiresExpression);
3450 if (FormatTok->is(tok::l_paren)) {
3451 FormatTok->setFinalizedType(TT_RequiresExpressionLParen);
3455 if (FormatTok->is(tok::l_brace)) {
3456 FormatTok->setFinalizedType(TT_RequiresExpressionLBrace);
3457 parseChildBlock(/*CanContainBracedList=*/false,
3458 /*NextLBracesType=*/TT_CompoundRequirementLBrace);
3462 /// \brief Parses a constraint expression.
3464 /// This is the body of a requires clause. It returns, when the parsing is
3465 /// complete, or the expression is incorrect.
3466 void UnwrappedLineParser::parseConstraintExpression() {
3467 // The special handling for lambdas is needed since tryToParseLambda() eats a
3468 // token and if a requires expression is the last part of a requires clause
3469 // and followed by an attribute like [[nodiscard]] the ClosesRequiresClause is
3470 // not set on the correct token. Thus we need to be aware if we even expect a
3471 // lambda to be possible.
3472 // template <typename T> requires requires { ... } [[nodiscard]] ...;
3473 bool LambdaNextTimeAllowed = true;
3475 // Within lambda declarations, it is permitted to put a requires clause after
3476 // its template parameter list, which would place the requires clause right
3477 // before the parentheses of the parameters of the lambda declaration. Thus,
3478 // we track if we expect to see grouping parentheses at all.
3479 // Without this check, `requires foo<T> (T t)` in the below example would be
3480 // seen as the whole requires clause, accidentally eating the parameters of
3482 // [&]<typename T> requires foo<T> (T t) { ... };
3483 bool TopLevelParensAllowed = true;
3486 bool LambdaThisTimeAllowed = std::exchange(LambdaNextTimeAllowed, false);
3488 switch (FormatTok->Tok.getKind()) {
3489 case tok::kw_requires: {
3490 auto RequiresToken = FormatTok;
3492 parseRequiresExpression(RequiresToken);
3497 if (!TopLevelParensAllowed)
3499 parseParens(/*AmpAmpTokenType=*/TT_BinaryOperator);
3500 TopLevelParensAllowed = false;
3504 if (!LambdaThisTimeAllowed || !tryToParseLambda())
3511 case tok::kw_struct:
3516 // Potential function body.
3521 FormatTok->setFinalizedType(TT_BinaryOperator);
3523 LambdaNextTimeAllowed = true;
3524 TopLevelParensAllowed = true;
3529 LambdaNextTimeAllowed = LambdaThisTimeAllowed;
3533 case tok::kw_sizeof:
3535 case tok::greaterequal:
3536 case tok::greatergreater:
3538 case tok::lessequal:
3540 case tok::equalequal:
3542 case tok::exclaimequal:
3547 LambdaNextTimeAllowed = true;
3548 TopLevelParensAllowed = true;
3553 case tok::numeric_constant:
3554 case tok::coloncolon:
3557 TopLevelParensAllowed = false;
3562 case tok::kw_static_cast:
3563 case tok::kw_const_cast:
3564 case tok::kw_reinterpret_cast:
3565 case tok::kw_dynamic_cast:
3567 if (!FormatTok->is(tok::less))
3571 parseBracedList(/*ContinueOnSemicolons=*/false, /*IsEnum=*/false,
3572 /*ClosingBraceKind=*/tok::greater);
3576 if (!FormatTok->Tok.getIdentifierInfo()) {
3577 // Identifiers are part of the default case, we check for more then
3578 // tok::identifier to handle builtin type traits.
3582 // We need to differentiate identifiers for a template deduction guide,
3583 // variables, or function return types (the constraint expression has
3584 // ended before that), and basically all other cases. But it's easier to
3585 // check the other way around.
3586 assert(FormatTok->Previous);
3587 switch (FormatTok->Previous->Tok.getKind()) {
3588 case tok::coloncolon: // Nested identifier.
3589 case tok::ampamp: // Start of a function or variable for the
3590 case tok::pipepipe: // constraint expression. (binary)
3591 case tok::exclaim: // The same as above, but unary.
3592 case tok::kw_requires: // Initial identifier of a requires clause.
3593 case tok::equal: // Initial identifier of a concept declaration.
3599 // Read identifier with optional template declaration.
3601 if (FormatTok->is(tok::less)) {
3603 parseBracedList(/*ContinueOnSemicolons=*/false, /*IsEnum=*/false,
3604 /*ClosingBraceKind=*/tok::greater);
3606 TopLevelParensAllowed = false;
3612 bool UnwrappedLineParser::parseEnum() {
3613 const FormatToken &InitialToken = *FormatTok;
3615 // Won't be 'enum' for NS_ENUMs.
3616 if (FormatTok->is(tok::kw_enum))
3619 // In TypeScript, "enum" can also be used as property name, e.g. in interface
3620 // declarations. An "enum" keyword followed by a colon would be a syntax
3621 // error and thus assume it is just an identifier.
3622 if (Style.isJavaScript() && FormatTok->isOneOf(tok::colon, tok::question))
3625 // In protobuf, "enum" can be used as a field name.
3626 if (Style.Language == FormatStyle::LK_Proto && FormatTok->is(tok::equal))
3629 // Eat up enum class ...
3630 if (FormatTok->isOneOf(tok::kw_class, tok::kw_struct))
3633 while (FormatTok->Tok.getIdentifierInfo() ||
3634 FormatTok->isOneOf(tok::colon, tok::coloncolon, tok::less,
3635 tok::greater, tok::comma, tok::question,
3636 tok::l_square, tok::r_square)) {
3637 if (Style.isVerilog()) {
3638 FormatTok->setFinalizedType(TT_VerilogDimensionedTypeName);
3640 // In Verilog the base type can have dimensions.
3641 while (FormatTok->is(tok::l_square))
3646 // We can have macros or attributes in between 'enum' and the enum name.
3647 if (FormatTok->is(tok::l_paren))
3649 if (FormatTok->is(TT_AttributeSquare)) {
3651 // Consume the closing TT_AttributeSquare.
3652 if (FormatTok->Next && FormatTok->is(TT_AttributeSquare))
3655 if (FormatTok->is(tok::identifier)) {
3657 // If there are two identifiers in a row, this is likely an elaborate
3658 // return type. In Java, this can be "implements", etc.
3659 if (Style.isCpp() && FormatTok->is(tok::identifier))
3664 // Just a declaration or something is wrong.
3665 if (FormatTok->isNot(tok::l_brace))
3667 FormatTok->setFinalizedType(TT_EnumLBrace);
3668 FormatTok->setBlockKind(BK_Block);
3670 if (Style.Language == FormatStyle::LK_Java) {
3671 // Java enums are different.
3672 parseJavaEnumBody();
3675 if (Style.Language == FormatStyle::LK_Proto) {
3676 parseBlock(/*MustBeDeclaration=*/true);
3680 if (!Style.AllowShortEnumsOnASingleLine &&
3681 ShouldBreakBeforeBrace(Style, InitialToken)) {
3686 if (!Style.AllowShortEnumsOnASingleLine) {
3690 bool HasError = !parseBracedList(/*ContinueOnSemicolons=*/true,
3692 if (!Style.AllowShortEnumsOnASingleLine)
3695 if (FormatTok->is(tok::semi))
3701 // There is no addUnwrappedLine() here so that we fall through to parsing a
3702 // structural element afterwards. Thus, in "enum A {} n, m;",
3703 // "} n, m;" will end up in one unwrapped line.
3706 bool UnwrappedLineParser::parseStructLike() {
3707 // parseRecord falls through and does not yet add an unwrapped line as a
3708 // record declaration or definition can start a structural element.
3710 // This does not apply to Java, JavaScript and C#.
3711 if (Style.Language == FormatStyle::LK_Java || Style.isJavaScript() ||
3713 if (FormatTok->is(tok::semi))
3722 // A class used to set and restore the Token position when peeking
3723 // ahead in the token source.
3724 class ScopedTokenPosition {
3725 unsigned StoredPosition;
3726 FormatTokenSource *Tokens;
3729 ScopedTokenPosition(FormatTokenSource *Tokens) : Tokens(Tokens) {
3730 assert(Tokens && "Tokens expected to not be null");
3731 StoredPosition = Tokens->getPosition();
3734 ~ScopedTokenPosition() { Tokens->setPosition(StoredPosition); }
3738 // Look to see if we have [[ by looking ahead, if
3739 // its not then rewind to the original position.
3740 bool UnwrappedLineParser::tryToParseSimpleAttribute() {
3741 ScopedTokenPosition AutoPosition(Tokens);
3742 FormatToken *Tok = Tokens->getNextToken();
3743 // We already read the first [ check for the second.
3744 if (!Tok->is(tok::l_square))
3746 // Double check that the attribute is just something
3748 while (Tok->isNot(tok::eof)) {
3749 if (Tok->is(tok::r_square))
3751 Tok = Tokens->getNextToken();
3753 if (Tok->is(tok::eof))
3755 Tok = Tokens->getNextToken();
3756 if (!Tok->is(tok::r_square))
3758 Tok = Tokens->getNextToken();
3759 if (Tok->is(tok::semi))
3764 void UnwrappedLineParser::parseJavaEnumBody() {
3765 assert(FormatTok->is(tok::l_brace));
3766 const FormatToken *OpeningBrace = FormatTok;
3768 // Determine whether the enum is simple, i.e. does not have a semicolon or
3769 // constants with class bodies. Simple enums can be formatted like braced
3770 // lists, contracted to a single line, etc.
3771 unsigned StoredPosition = Tokens->getPosition();
3772 bool IsSimple = true;
3773 FormatToken *Tok = Tokens->getNextToken();
3774 while (!Tok->is(tok::eof)) {
3775 if (Tok->is(tok::r_brace))
3777 if (Tok->isOneOf(tok::l_brace, tok::semi)) {
3781 // FIXME: This will also mark enums with braces in the arguments to enum
3782 // constants as "not simple". This is probably fine in practice, though.
3783 Tok = Tokens->getNextToken();
3785 FormatTok = Tokens->setPosition(StoredPosition);
3794 // Parse the body of a more complex enum.
3795 // First add a line for everything up to the "{".
3800 // Parse the enum constants.
3802 if (FormatTok->is(tok::l_brace)) {
3803 // Parse the constant's class body.
3804 parseBlock(/*MustBeDeclaration=*/true, /*AddLevels=*/1u,
3805 /*MunchSemi=*/false);
3806 } else if (FormatTok->is(tok::l_paren)) {
3808 } else if (FormatTok->is(tok::comma)) {
3811 } else if (FormatTok->is(tok::semi)) {
3815 } else if (FormatTok->is(tok::r_brace)) {
3823 // Parse the class body after the enum's ";" if any.
3824 parseLevel(OpeningBrace);
3830 void UnwrappedLineParser::parseRecord(bool ParseAsExpr) {
3831 const FormatToken &InitialToken = *FormatTok;
3834 // The actual identifier can be a nested name specifier, and in macros
3835 // it is often token-pasted.
3836 // An [[attribute]] can be before the identifier.
3837 while (FormatTok->isOneOf(tok::identifier, tok::coloncolon, tok::hashhash,
3838 tok::kw___attribute, tok::kw___declspec,
3839 tok::kw_alignas, tok::l_square) ||
3840 ((Style.Language == FormatStyle::LK_Java || Style.isJavaScript()) &&
3841 FormatTok->isOneOf(tok::period, tok::comma))) {
3842 if (Style.isJavaScript() &&
3843 FormatTok->isOneOf(Keywords.kw_extends, Keywords.kw_implements)) {
3844 // JavaScript/TypeScript supports inline object types in
3845 // extends/implements positions:
3846 // class Foo implements {bar: number} { }
3848 if (FormatTok->is(tok::l_brace)) {
3849 tryToParseBracedList();
3853 if (FormatTok->is(tok::l_square) && handleCppAttributes())
3855 bool IsNonMacroIdentifier =
3856 FormatTok->is(tok::identifier) &&
3857 FormatTok->TokenText != FormatTok->TokenText.upper();
3859 // We can have macros in between 'class' and the class name.
3860 if (!IsNonMacroIdentifier && FormatTok->is(tok::l_paren))
3864 // Note that parsing away template declarations here leads to incorrectly
3865 // accepting function declarations as record declarations.
3866 // In general, we cannot solve this problem. Consider:
3867 // class A<int> B() {}
3868 // which can be a function definition or a class definition when B() is a
3869 // macro. If we find enough real-world cases where this is a problem, we
3870 // can parse for the 'template' keyword in the beginning of the statement,
3871 // and thus rule out the record production in case there is no template
3872 // (this would still leave us with an ambiguity between template function
3873 // and class declarations).
3874 if (FormatTok->isOneOf(tok::colon, tok::less)) {
3876 if (FormatTok->is(tok::l_brace)) {
3877 calculateBraceTypes(/*ExpectClassBody=*/true);
3878 if (!tryToParseBracedList())
3881 if (FormatTok->is(tok::l_square)) {
3882 FormatToken *Previous = FormatTok->Previous;
3884 !(Previous->is(tok::r_paren) || Previous->isTypeOrIdentifier())) {
3885 // Don't try parsing a lambda if we had a closing parenthesis before,
3886 // it was probably a pointer to an array: int (*)[].
3887 if (!tryToParseLambda())
3894 if (FormatTok->is(tok::semi))
3896 if (Style.isCSharp() && FormatTok->is(Keywords.kw_where)) {
3899 parseCSharpGenericTypeConstraint();
3906 auto GetBraceType = [](const FormatToken &RecordTok) {
3907 switch (RecordTok.Tok.getKind()) {
3909 return TT_ClassLBrace;
3910 case tok::kw_struct:
3911 return TT_StructLBrace;
3913 return TT_UnionLBrace;
3915 // Useful for e.g. interface.
3916 return TT_RecordLBrace;
3919 if (FormatTok->is(tok::l_brace)) {
3920 FormatTok->setFinalizedType(GetBraceType(InitialToken));
3924 if (ShouldBreakBeforeBrace(Style, InitialToken))
3927 unsigned AddLevels = Style.IndentAccessModifiers ? 2u : 1u;
3928 parseBlock(/*MustBeDeclaration=*/true, AddLevels, /*MunchSemi=*/false);
3931 // There is no addUnwrappedLine() here so that we fall through to parsing a
3932 // structural element afterwards. Thus, in "class A {} n, m;",
3933 // "} n, m;" will end up in one unwrapped line.
3936 void UnwrappedLineParser::parseObjCMethod() {
3937 assert(FormatTok->isOneOf(tok::l_paren, tok::identifier) &&
3938 "'(' or identifier expected.");
3940 if (FormatTok->is(tok::semi)) {
3944 } else if (FormatTok->is(tok::l_brace)) {
3945 if (Style.BraceWrapping.AfterFunction)
3956 void UnwrappedLineParser::parseObjCProtocolList() {
3957 assert(FormatTok->is(tok::less) && "'<' expected.");
3960 // Early exit in case someone forgot a close angle.
3961 if (FormatTok->isOneOf(tok::semi, tok::l_brace) ||
3962 FormatTok->isObjCAtKeyword(tok::objc_end)) {
3965 } while (!eof() && FormatTok->isNot(tok::greater));
3966 nextToken(); // Skip '>'.
3969 void UnwrappedLineParser::parseObjCUntilAtEnd() {
3971 if (FormatTok->isObjCAtKeyword(tok::objc_end)) {
3976 if (FormatTok->is(tok::l_brace)) {
3978 // In ObjC interfaces, nothing should be following the "}".
3980 } else if (FormatTok->is(tok::r_brace)) {
3981 // Ignore stray "}". parseStructuralElement doesn't consume them.
3984 } else if (FormatTok->isOneOf(tok::minus, tok::plus)) {
3988 parseStructuralElement();
3993 void UnwrappedLineParser::parseObjCInterfaceOrImplementation() {
3994 assert(FormatTok->Tok.getObjCKeywordID() == tok::objc_interface ||
3995 FormatTok->Tok.getObjCKeywordID() == tok::objc_implementation);
3997 nextToken(); // interface name
3999 // @interface can be followed by a lightweight generic
4000 // specialization list, then either a base class or a category.
4001 if (FormatTok->is(tok::less))
4002 parseObjCLightweightGenerics();
4003 if (FormatTok->is(tok::colon)) {
4005 nextToken(); // base class name
4006 // The base class can also have lightweight generics applied to it.
4007 if (FormatTok->is(tok::less))
4008 parseObjCLightweightGenerics();
4009 } else if (FormatTok->is(tok::l_paren)) {
4010 // Skip category, if present.
4014 if (FormatTok->is(tok::less))
4015 parseObjCProtocolList();
4017 if (FormatTok->is(tok::l_brace)) {
4018 if (Style.BraceWrapping.AfterObjCDeclaration)
4020 parseBlock(/*MustBeDeclaration=*/true);
4023 // With instance variables, this puts '}' on its own line. Without instance
4024 // variables, this ends the @interface line.
4027 parseObjCUntilAtEnd();
4030 void UnwrappedLineParser::parseObjCLightweightGenerics() {
4031 assert(FormatTok->is(tok::less));
4032 // Unlike protocol lists, generic parameterizations support
4035 // @interface Foo<ValueType : id <NSCopying, NSSecureCoding>> :
4036 // NSObject <NSCopying, NSSecureCoding>
4038 // so we need to count how many open angles we have left.
4039 unsigned NumOpenAngles = 1;
4042 // Early exit in case someone forgot a close angle.
4043 if (FormatTok->isOneOf(tok::semi, tok::l_brace) ||
4044 FormatTok->isObjCAtKeyword(tok::objc_end)) {
4047 if (FormatTok->is(tok::less)) {
4049 } else if (FormatTok->is(tok::greater)) {
4050 assert(NumOpenAngles > 0 && "'>' makes NumOpenAngles negative");
4053 } while (!eof() && NumOpenAngles != 0);
4054 nextToken(); // Skip '>'.
4057 // Returns true for the declaration/definition form of @protocol,
4058 // false for the expression form.
4059 bool UnwrappedLineParser::parseObjCProtocol() {
4060 assert(FormatTok->Tok.getObjCKeywordID() == tok::objc_protocol);
4063 if (FormatTok->is(tok::l_paren)) {
4064 // The expression form of @protocol, e.g. "Protocol* p = @protocol(foo);".
4068 // The definition/declaration form,
4070 // - (int)someMethod;
4073 nextToken(); // protocol name
4075 if (FormatTok->is(tok::less))
4076 parseObjCProtocolList();
4078 // Check for protocol declaration.
4079 if (FormatTok->is(tok::semi)) {
4086 parseObjCUntilAtEnd();
4090 void UnwrappedLineParser::parseJavaScriptEs6ImportExport() {
4091 bool IsImport = FormatTok->is(Keywords.kw_import);
4092 assert(IsImport || FormatTok->is(tok::kw_export));
4095 // Consume the "default" in "export default class/function".
4096 if (FormatTok->is(tok::kw_default))
4099 // Consume "async function", "function" and "default function", so that these
4100 // get parsed as free-standing JS functions, i.e. do not require a trailing
4102 if (FormatTok->is(Keywords.kw_async))
4104 if (FormatTok->is(Keywords.kw_function)) {
4109 // For imports, `export *`, `export {...}`, consume the rest of the line up
4110 // to the terminating `;`. For everything else, just return and continue
4111 // parsing the structural element, i.e. the declaration or expression for
4112 // `export default`.
4113 if (!IsImport && !FormatTok->isOneOf(tok::l_brace, tok::star) &&
4114 !FormatTok->isStringLiteral() &&
4115 !(FormatTok->is(Keywords.kw_type) &&
4116 Tokens->peekNextToken()->isOneOf(tok::l_brace, tok::star))) {
4121 if (FormatTok->is(tok::semi))
4123 if (Line->Tokens.empty()) {
4124 // Common issue: Automatic Semicolon Insertion wrapped the line, so the
4125 // import statement should terminate.
4128 if (FormatTok->is(tok::l_brace)) {
4129 FormatTok->setBlockKind(BK_Block);
4138 void UnwrappedLineParser::parseStatementMacro() {
4140 if (FormatTok->is(tok::l_paren))
4142 if (FormatTok->is(tok::semi))
4147 void UnwrappedLineParser::parseVerilogHierarchyIdentifier() {
4148 // consume things like a::`b.c[d:e] or a::*
4150 if (FormatTok->isOneOf(tok::star, tok::period, tok::periodstar,
4151 tok::coloncolon, tok::hash) ||
4152 Keywords.isVerilogIdentifier(*FormatTok)) {
4154 } else if (FormatTok->is(tok::l_square)) {
4162 void UnwrappedLineParser::parseVerilogSensitivityList() {
4163 if (!FormatTok->is(tok::at))
4166 // A block event expression has 2 at signs.
4167 if (FormatTok->is(tok::at))
4169 switch (FormatTok->Tok.getKind()) {
4177 parseVerilogHierarchyIdentifier();
4182 unsigned UnwrappedLineParser::parseVerilogHierarchyHeader() {
4183 unsigned AddLevels = 0;
4185 if (FormatTok->is(Keywords.kw_clocking)) {
4187 if (Keywords.isVerilogIdentifier(*FormatTok))
4189 parseVerilogSensitivityList();
4190 if (FormatTok->is(tok::semi))
4192 } else if (FormatTok->isOneOf(tok::kw_case, Keywords.kw_casex,
4193 Keywords.kw_casez, Keywords.kw_randcase,
4194 Keywords.kw_randsequence)) {
4195 if (Style.IndentCaseLabels)
4198 if (FormatTok->is(tok::l_paren)) {
4199 FormatTok->setFinalizedType(TT_ConditionLParen);
4202 if (FormatTok->isOneOf(Keywords.kw_inside, Keywords.kw_matches))
4204 // The case header has no semicolon.
4208 // all the words like the name of the module and specifiers like
4209 // "automatic" and the width of function return type
4211 if (FormatTok->is(tok::l_square)) {
4212 auto Prev = FormatTok->getPreviousNonComment();
4213 if (Prev && Keywords.isVerilogIdentifier(*Prev))
4214 Prev->setFinalizedType(TT_VerilogDimensionedTypeName);
4216 } else if (Keywords.isVerilogIdentifier(*FormatTok) ||
4217 FormatTok->isOneOf(Keywords.kw_automatic, tok::kw_static)) {
4224 auto NewLine = [this]() {
4226 Line->IsContinuation = true;
4230 while (FormatTok->is(Keywords.kw_import)) {
4233 parseVerilogHierarchyIdentifier();
4234 if (FormatTok->is(tok::semi))
4238 // parameters and ports
4239 if (FormatTok->is(Keywords.kw_verilogHash)) {
4242 if (FormatTok->is(tok::l_paren)) {
4243 FormatTok->setFinalizedType(TT_VerilogMultiLineListLParen);
4247 if (FormatTok->is(tok::l_paren)) {
4249 FormatTok->setFinalizedType(TT_VerilogMultiLineListLParen);
4253 // extends and implements
4254 if (FormatTok->is(Keywords.kw_extends)) {
4257 parseVerilogHierarchyIdentifier();
4258 if (FormatTok->is(tok::l_paren))
4261 if (FormatTok->is(Keywords.kw_implements)) {
4265 parseVerilogHierarchyIdentifier();
4266 } while (FormatTok->is(tok::comma));
4269 // Coverage event for cover groups.
4270 if (FormatTok->is(tok::at)) {
4272 parseVerilogSensitivityList();
4275 if (FormatTok->is(tok::semi))
4276 nextToken(/*LevelDifference=*/1);
4283 void UnwrappedLineParser::parseVerilogTable() {
4284 assert(FormatTok->is(Keywords.kw_table));
4285 nextToken(/*LevelDifference=*/1);
4288 auto InitialLevel = Line->Level++;
4289 while (!eof() && !Keywords.isVerilogEnd(*FormatTok)) {
4290 FormatToken *Tok = FormatTok;
4292 if (Tok->is(tok::semi))
4294 else if (Tok->isOneOf(tok::star, tok::colon, tok::question, tok::minus))
4295 Tok->setFinalizedType(TT_VerilogTableItem);
4297 Line->Level = InitialLevel;
4298 nextToken(/*LevelDifference=*/-1);
4302 void UnwrappedLineParser::parseVerilogCaseLabel() {
4303 // The label will get unindented in AnnotatingParser. If there are no leading
4304 // spaces, indent the rest here so that things inside the block will be
4305 // indented relative to things outside. We don't use parseLabel because we
4306 // don't know whether this colon is a label or a ternary expression at this
4308 auto OrigLevel = Line->Level;
4309 auto FirstLine = CurrentLines->size();
4310 if (Line->Level == 0 || (Line->InPPDirective && Line->Level <= 1))
4312 else if (!Style.IndentCaseBlocks && Keywords.isVerilogBegin(*FormatTok))
4314 parseStructuralElement();
4315 // Restore the indentation in both the new line and the line that has the
4317 if (CurrentLines->size() > FirstLine)
4318 (*CurrentLines)[FirstLine].Level = OrigLevel;
4319 Line->Level = OrigLevel;
4322 bool UnwrappedLineParser::containsExpansion(const UnwrappedLine &Line) const {
4323 for (const auto &N : Line.Tokens) {
4324 if (N.Tok->MacroCtx)
4326 for (const UnwrappedLine &Child : N.Children)
4327 if (containsExpansion(Child))
4333 void UnwrappedLineParser::addUnwrappedLine(LineLevel AdjustLevel) {
4334 if (Line->Tokens.empty())
4337 if (!parsingPPDirective()) {
4338 llvm::dbgs() << "Adding unwrapped line:\n";
4339 printDebugInfo(*Line);
4343 // If this line closes a block when in Whitesmiths mode, remember that
4344 // information so that the level can be decreased after the line is added.
4345 // This has to happen after the addition of the line since the line itself
4346 // needs to be indented.
4347 bool ClosesWhitesmithsBlock =
4348 Line->MatchingOpeningBlockLineIndex != UnwrappedLine::kInvalidIndex &&
4349 Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths;
4351 // If the current line was expanded from a macro call, we use it to
4352 // reconstruct an unwrapped line from the structure of the expanded unwrapped
4353 // line and the unexpanded token stream.
4354 if (!parsingPPDirective() && !InExpansion && containsExpansion(*Line)) {
4356 Reconstruct.emplace(Line->Level, Unexpanded);
4357 Reconstruct->addLine(*Line);
4359 // While the reconstructed unexpanded lines are stored in the normal
4360 // flow of lines, the expanded lines are stored on the side to be analyzed
4361 // in an extra step.
4362 CurrentExpandedLines.push_back(std::move(*Line));
4364 if (Reconstruct->finished()) {
4365 UnwrappedLine Reconstructed = std::move(*Reconstruct).takeResult();
4366 assert(!Reconstructed.Tokens.empty() &&
4367 "Reconstructed must at least contain the macro identifier.");
4368 assert(!parsingPPDirective());
4370 llvm::dbgs() << "Adding unexpanded line:\n";
4371 printDebugInfo(Reconstructed);
4373 ExpandedLines[Reconstructed.Tokens.begin()->Tok] = CurrentExpandedLines;
4374 Lines.push_back(std::move(Reconstructed));
4375 CurrentExpandedLines.clear();
4376 Reconstruct.reset();
4379 // At the top level we only get here when no unexpansion is going on, or
4380 // when conditional formatting led to unfinished macro reconstructions.
4381 assert(!Reconstruct || (CurrentLines != &Lines) || PPStack.size() > 0);
4382 CurrentLines->push_back(std::move(*Line));
4384 Line->Tokens.clear();
4385 Line->MatchingOpeningBlockLineIndex = UnwrappedLine::kInvalidIndex;
4386 Line->FirstStartColumn = 0;
4387 Line->IsContinuation = false;
4389 if (ClosesWhitesmithsBlock && AdjustLevel == LineLevel::Remove)
4391 if (!parsingPPDirective() && !PreprocessorDirectives.empty()) {
4392 CurrentLines->append(
4393 std::make_move_iterator(PreprocessorDirectives.begin()),
4394 std::make_move_iterator(PreprocessorDirectives.end()));
4395 PreprocessorDirectives.clear();
4397 // Disconnect the current token from the last token on the previous line.
4398 FormatTok->Previous = nullptr;
4401 bool UnwrappedLineParser::eof() const { return FormatTok->is(tok::eof); }
4403 bool UnwrappedLineParser::isOnNewLine(const FormatToken &FormatTok) {
4404 return (Line->InPPDirective || FormatTok.HasUnescapedNewline) &&
4405 FormatTok.NewlinesBefore > 0;
4408 // Checks if \p FormatTok is a line comment that continues the line comment
4409 // section on \p Line.
4411 continuesLineCommentSection(const FormatToken &FormatTok,
4412 const UnwrappedLine &Line,
4413 const llvm::Regex &CommentPragmasRegex) {
4414 if (Line.Tokens.empty())
4417 StringRef IndentContent = FormatTok.TokenText;
4418 if (FormatTok.TokenText.startswith("//") ||
4419 FormatTok.TokenText.startswith("/*")) {
4420 IndentContent = FormatTok.TokenText.substr(2);
4422 if (CommentPragmasRegex.match(IndentContent))
4425 // If Line starts with a line comment, then FormatTok continues the comment
4426 // section if its original column is greater or equal to the original start
4427 // column of the line.
4429 // Define the min column token of a line as follows: if a line ends in '{' or
4430 // contains a '{' followed by a line comment, then the min column token is
4431 // that '{'. Otherwise, the min column token of the line is the first token of
4434 // If Line starts with a token other than a line comment, then FormatTok
4435 // continues the comment section if its original column is greater than the
4436 // original start column of the min column token of the line.
4438 // For example, the second line comment continues the first in these cases:
4450 // int i; // first line
4455 // do { // first line
4468 // The second line comment doesn't continue the first in these cases:
4475 // int i; // first line
4480 // do { // first line
4491 const FormatToken *MinColumnToken = Line.Tokens.front().Tok;
4493 // Scan for '{//'. If found, use the column of '{' as a min column for line
4494 // comment section continuation.
4495 const FormatToken *PreviousToken = nullptr;
4496 for (const UnwrappedLineNode &Node : Line.Tokens) {
4497 if (PreviousToken && PreviousToken->is(tok::l_brace) &&
4498 isLineComment(*Node.Tok)) {
4499 MinColumnToken = PreviousToken;
4502 PreviousToken = Node.Tok;
4504 // Grab the last newline preceding a token in this unwrapped line.
4505 if (Node.Tok->NewlinesBefore > 0)
4506 MinColumnToken = Node.Tok;
4508 if (PreviousToken && PreviousToken->is(tok::l_brace))
4509 MinColumnToken = PreviousToken;
4511 return continuesLineComment(FormatTok, /*Previous=*/Line.Tokens.back().Tok,
4515 void UnwrappedLineParser::flushComments(bool NewlineBeforeNext) {
4516 bool JustComments = Line->Tokens.empty();
4517 for (FormatToken *Tok : CommentsBeforeNextToken) {
4518 // Line comments that belong to the same line comment section are put on the
4519 // same line since later we might want to reflow content between them.
4520 // Additional fine-grained breaking of line comment sections is controlled
4521 // by the class BreakableLineCommentSection in case it is desirable to keep
4522 // several line comment sections in the same unwrapped line.
4524 // FIXME: Consider putting separate line comment sections as children to the
4525 // unwrapped line instead.
4526 Tok->ContinuesLineCommentSection =
4527 continuesLineCommentSection(*Tok, *Line, CommentPragmasRegex);
4528 if (isOnNewLine(*Tok) && JustComments && !Tok->ContinuesLineCommentSection)
4532 if (NewlineBeforeNext && JustComments)
4534 CommentsBeforeNextToken.clear();
4537 void UnwrappedLineParser::nextToken(int LevelDifference) {
4540 flushComments(isOnNewLine(*FormatTok));
4541 pushToken(FormatTok);
4542 FormatToken *Previous = FormatTok;
4543 if (!Style.isJavaScript())
4544 readToken(LevelDifference);
4546 readTokenWithJavaScriptASI();
4547 FormatTok->Previous = Previous;
4548 if (Style.isVerilog()) {
4549 // Blocks in Verilog can have `begin` and `end` instead of braces. For
4550 // keywords like `begin`, we can't treat them the same as left braces
4551 // because some contexts require one of them. For example structs use
4552 // braces and if blocks use keywords, and a left brace can occur in an if
4553 // statement, but it is not a block. For keywords like `end`, we simply
4554 // treat them the same as right braces.
4555 if (Keywords.isVerilogEnd(*FormatTok))
4556 FormatTok->Tok.setKind(tok::r_brace);
4560 void UnwrappedLineParser::distributeComments(
4561 const SmallVectorImpl<FormatToken *> &Comments,
4562 const FormatToken *NextTok) {
4563 // Whether or not a line comment token continues a line is controlled by
4564 // the method continuesLineCommentSection, with the following caveat:
4566 // Define a trail of Comments to be a nonempty proper postfix of Comments such
4567 // that each comment line from the trail is aligned with the next token, if
4568 // the next token exists. If a trail exists, the beginning of the maximal
4569 // trail is marked as a start of a new comment section.
4571 // For example in this code:
4573 // int a; // line about a
4574 // // line 1 about b
4575 // // line 2 about b
4578 // the two lines about b form a maximal trail, so there are two sections, the
4579 // first one consisting of the single comment "// line about a" and the
4580 // second one consisting of the next two comments.
4581 if (Comments.empty())
4583 bool ShouldPushCommentsInCurrentLine = true;
4584 bool HasTrailAlignedWithNextToken = false;
4585 unsigned StartOfTrailAlignedWithNextToken = 0;
4587 // We are skipping the first element intentionally.
4588 for (unsigned i = Comments.size() - 1; i > 0; --i) {
4589 if (Comments[i]->OriginalColumn == NextTok->OriginalColumn) {
4590 HasTrailAlignedWithNextToken = true;
4591 StartOfTrailAlignedWithNextToken = i;
4595 for (unsigned i = 0, e = Comments.size(); i < e; ++i) {
4596 FormatToken *FormatTok = Comments[i];
4597 if (HasTrailAlignedWithNextToken && i == StartOfTrailAlignedWithNextToken) {
4598 FormatTok->ContinuesLineCommentSection = false;
4600 FormatTok->ContinuesLineCommentSection =
4601 continuesLineCommentSection(*FormatTok, *Line, CommentPragmasRegex);
4603 if (!FormatTok->ContinuesLineCommentSection &&
4604 (isOnNewLine(*FormatTok) || FormatTok->IsFirst)) {
4605 ShouldPushCommentsInCurrentLine = false;
4607 if (ShouldPushCommentsInCurrentLine)
4608 pushToken(FormatTok);
4610 CommentsBeforeNextToken.push_back(FormatTok);
4614 void UnwrappedLineParser::readToken(int LevelDifference) {
4615 SmallVector<FormatToken *, 1> Comments;
4616 bool PreviousWasComment = false;
4617 bool FirstNonCommentOnLine = false;
4619 FormatTok = Tokens->getNextToken();
4621 while (FormatTok->getType() == TT_ConflictStart ||
4622 FormatTok->getType() == TT_ConflictEnd ||
4623 FormatTok->getType() == TT_ConflictAlternative) {
4624 if (FormatTok->getType() == TT_ConflictStart)
4625 conditionalCompilationStart(/*Unreachable=*/false);
4626 else if (FormatTok->getType() == TT_ConflictAlternative)
4627 conditionalCompilationAlternative();
4628 else if (FormatTok->getType() == TT_ConflictEnd)
4629 conditionalCompilationEnd();
4630 FormatTok = Tokens->getNextToken();
4631 FormatTok->MustBreakBefore = true;
4634 auto IsFirstNonCommentOnLine = [](bool FirstNonCommentOnLine,
4635 const FormatToken &Tok,
4636 bool PreviousWasComment) {
4637 auto IsFirstOnLine = [](const FormatToken &Tok) {
4638 return Tok.HasUnescapedNewline || Tok.IsFirst;
4641 // Consider preprocessor directives preceded by block comments as first
4643 if (PreviousWasComment)
4644 return FirstNonCommentOnLine || IsFirstOnLine(Tok);
4645 return IsFirstOnLine(Tok);
4648 FirstNonCommentOnLine = IsFirstNonCommentOnLine(
4649 FirstNonCommentOnLine, *FormatTok, PreviousWasComment);
4650 PreviousWasComment = FormatTok->is(tok::comment);
4652 while (!Line->InPPDirective && FormatTok->is(tok::hash) &&
4653 (!Style.isVerilog() ||
4654 Keywords.isVerilogPPDirective(*Tokens->peekNextToken())) &&
4655 FirstNonCommentOnLine) {
4656 distributeComments(Comments, FormatTok);
4658 // If there is an unfinished unwrapped line, we flush the preprocessor
4659 // directives only after that unwrapped line was finished later.
4660 bool SwitchToPreprocessorLines = !Line->Tokens.empty();
4661 ScopedLineState BlockState(*this, SwitchToPreprocessorLines);
4662 assert((LevelDifference >= 0 ||
4663 static_cast<unsigned>(-LevelDifference) <= Line->Level) &&
4664 "LevelDifference makes Line->Level negative");
4665 Line->Level += LevelDifference;
4666 // Comments stored before the preprocessor directive need to be output
4667 // before the preprocessor directive, at the same level as the
4668 // preprocessor directive, as we consider them to apply to the directive.
4669 if (Style.IndentPPDirectives == FormatStyle::PPDIS_BeforeHash &&
4670 PPBranchLevel > 0) {
4671 Line->Level += PPBranchLevel;
4673 flushComments(isOnNewLine(*FormatTok));
4675 PreviousWasComment = FormatTok->is(tok::comment);
4676 FirstNonCommentOnLine = IsFirstNonCommentOnLine(
4677 FirstNonCommentOnLine, *FormatTok, PreviousWasComment);
4680 if (!PPStack.empty() && (PPStack.back().Kind == PP_Unreachable) &&
4681 !Line->InPPDirective) {
4685 if (FormatTok->is(tok::identifier) &&
4686 Macros.defined(FormatTok->TokenText) &&
4687 // FIXME: Allow expanding macros in preprocessor directives.
4688 !Line->InPPDirective) {
4689 FormatToken *ID = FormatTok;
4690 unsigned Position = Tokens->getPosition();
4692 // To correctly parse the code, we need to replace the tokens of the macro
4693 // call with its expansion.
4694 auto PreCall = std::move(Line);
4695 Line.reset(new UnwrappedLine);
4696 bool OldInExpansion = InExpansion;
4698 // We parse the macro call into a new line.
4699 auto Args = parseMacroCall();
4700 InExpansion = OldInExpansion;
4701 assert(Line->Tokens.front().Tok == ID);
4702 // And remember the unexpanded macro call tokens.
4703 auto UnexpandedLine = std::move(Line);
4704 // Reset to the old line.
4705 Line = std::move(PreCall);
4708 llvm::dbgs() << "Macro call: " << ID->TokenText << "(";
4710 llvm::dbgs() << "(";
4711 for (const auto &Arg : Args.value())
4712 for (const auto &T : Arg)
4713 llvm::dbgs() << T->TokenText << " ";
4714 llvm::dbgs() << ")";
4716 llvm::dbgs() << "\n";
4718 if (Macros.objectLike(ID->TokenText) && Args &&
4719 !Macros.hasArity(ID->TokenText, Args->size())) {
4720 // The macro is either
4721 // - object-like, but we got argumnets, or
4722 // - overloaded to be both object-like and function-like, but none of
4723 // the function-like arities match the number of arguments.
4724 // Thus, expand as object-like macro.
4725 LLVM_DEBUG(llvm::dbgs()
4726 << "Macro \"" << ID->TokenText
4727 << "\" not overloaded for arity " << Args->size()
4728 << "or not function-like, using object-like overload.");
4730 UnexpandedLine->Tokens.resize(1);
4731 Tokens->setPosition(Position);
4733 assert(!Args && Macros.objectLike(ID->TokenText));
4735 if ((!Args && Macros.objectLike(ID->TokenText)) ||
4736 (Args && Macros.hasArity(ID->TokenText, Args->size()))) {
4737 // Next, we insert the expanded tokens in the token stream at the
4738 // current position, and continue parsing.
4739 Unexpanded[ID] = std::move(UnexpandedLine);
4740 SmallVector<FormatToken *, 8> Expansion =
4741 Macros.expand(ID, std::move(Args));
4742 if (!Expansion.empty())
4743 FormatTok = Tokens->insertTokens(Expansion);
4746 llvm::dbgs() << "Expanded: ";
4747 for (const auto &T : Expansion)
4748 llvm::dbgs() << T->TokenText << " ";
4749 llvm::dbgs() << "\n";
4753 llvm::dbgs() << "Did not expand macro \"" << ID->TokenText
4754 << "\", because it was used ";
4756 llvm::dbgs() << "with " << Args->size();
4758 llvm::dbgs() << "without";
4759 llvm::dbgs() << " arguments, which doesn't match any definition.\n";
4761 Tokens->setPosition(Position);
4766 if (!FormatTok->is(tok::comment)) {
4767 distributeComments(Comments, FormatTok);
4772 Comments.push_back(FormatTok);
4775 distributeComments(Comments, nullptr);
4780 template <typename Iterator>
4781 void pushTokens(Iterator Begin, Iterator End,
4782 llvm::SmallVectorImpl<FormatToken *> &Into) {
4783 for (auto I = Begin; I != End; ++I) {
4784 Into.push_back(I->Tok);
4785 for (const auto &Child : I->Children)
4786 pushTokens(Child.Tokens.begin(), Child.Tokens.end(), Into);
4791 std::optional<llvm::SmallVector<llvm::SmallVector<FormatToken *, 8>, 1>>
4792 UnwrappedLineParser::parseMacroCall() {
4793 std::optional<llvm::SmallVector<llvm::SmallVector<FormatToken *, 8>, 1>> Args;
4794 assert(Line->Tokens.empty());
4796 if (!FormatTok->is(tok::l_paren))
4798 unsigned Position = Tokens->getPosition();
4799 FormatToken *Tok = FormatTok;
4802 auto ArgStart = std::prev(Line->Tokens.end());
4806 switch (FormatTok->Tok.getKind()) {
4811 case tok::r_paren: {
4817 Args->push_back({});
4818 pushTokens(std::next(ArgStart), Line->Tokens.end(), Args->back());
4827 Args->push_back({});
4828 pushTokens(std::next(ArgStart), Line->Tokens.end(), Args->back());
4830 ArgStart = std::prev(Line->Tokens.end());
4838 Line->Tokens.resize(1);
4839 Tokens->setPosition(Position);
4844 void UnwrappedLineParser::pushToken(FormatToken *Tok) {
4845 Line->Tokens.push_back(UnwrappedLineNode(Tok));
4846 if (MustBreakBeforeNextToken) {
4847 Line->Tokens.back().Tok->MustBreakBefore = true;
4848 MustBreakBeforeNextToken = false;
4852 } // end namespace format
4853 } // end namespace clang