1 //===--- UnwrappedLineParser.cpp - Format C++ code ------------------------===//
2 //
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
6 //
7 //===----------------------------------------------------------------------===//
8 ///
9 /// \file
10 /// This file contains the implementation of the UnwrappedLineParser,
11 /// which turns a stream of tokens into UnwrappedLines.
12 ///
13 //===----------------------------------------------------------------------===//
14 
15 #include "UnwrappedLineParser.h"
16 #include "FormatToken.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/Support/Debug.h"
19 #include "llvm/Support/raw_ostream.h"
20 
21 #include <algorithm>
22 #include <utility>
23 
24 #define DEBUG_TYPE "format-parser"
25 
26 namespace clang {
27 namespace format {
28 
29 class FormatTokenSource {
30 public:
31   virtual ~FormatTokenSource() {}
32 
33   // Returns the next token in the token stream.
34   virtual FormatToken *getNextToken() = 0;
35 
36   // Returns the token preceding the token returned by the last call to
37   // getNextToken() in the token stream, or nullptr if no such token exists.
38   virtual FormatToken *getPreviousToken() = 0;
39 
40   // Returns the token that would be returned by the next call to
41   // getNextToken().
42   virtual FormatToken *peekNextToken() = 0;
43 
44   // Returns the token that would be returned after the next N calls to
45   // getNextToken(). N needs to be greater than zero, and small enough that
46   // there are still tokens. Check for tok::eof with N-1 before calling it with
47   // N.
48   virtual FormatToken *peekNextToken(int N) = 0;
49 
50   // Returns whether we are at the end of the file.
51   // This can be different from whether getNextToken() returned an eof token
52   // when the FormatTokenSource is a view on a part of the token stream.
53   virtual bool isEOF() = 0;
54 
55   // Gets the current position in the token stream, to be used by setPosition().
56   virtual unsigned getPosition() = 0;
57 
58   // Resets the token stream to the state it was in when getPosition() returned
59   // Position, and return the token at that position in the stream.
60   virtual FormatToken *setPosition(unsigned Position) = 0;
61 };
62 
63 namespace {
64 
65 class ScopedDeclarationState {
66 public:
67   ScopedDeclarationState(UnwrappedLine &Line, llvm::BitVector &Stack,
68                          bool MustBeDeclaration)
69       : Line(Line), Stack(Stack) {
70     Line.MustBeDeclaration = MustBeDeclaration;
71     Stack.push_back(MustBeDeclaration);
72   }
73   ~ScopedDeclarationState() {
74     Stack.pop_back();
75     if (!Stack.empty())
76       Line.MustBeDeclaration = Stack.back();
77     else
78       Line.MustBeDeclaration = true;
79   }
80 
81 private:
82   UnwrappedLine &Line;
83   llvm::BitVector &Stack;
84 };
85 
86 static bool isLineComment(const FormatToken &FormatTok) {
87   return FormatTok.is(tok::comment) && !FormatTok.TokenText.startswith("/*");
88 }
89 
90 // Checks if \p FormatTok is a line comment that continues the line comment
91 // \p Previous. The original column of \p MinColumnToken is used to determine
92 // whether \p FormatTok is indented enough to the right to continue \p Previous.
93 static bool continuesLineComment(const FormatToken &FormatTok,
94                                  const FormatToken *Previous,
95                                  const FormatToken *MinColumnToken) {
96   if (!Previous || !MinColumnToken)
97     return false;
98   unsigned MinContinueColumn =
99       MinColumnToken->OriginalColumn + (isLineComment(*MinColumnToken) ? 0 : 1);
100   return isLineComment(FormatTok) && FormatTok.NewlinesBefore == 1 &&
101          isLineComment(*Previous) &&
102          FormatTok.OriginalColumn >= MinContinueColumn;
103 }
104 
105 class ScopedMacroState : public FormatTokenSource {
106 public:
107   ScopedMacroState(UnwrappedLine &Line, FormatTokenSource *&TokenSource,
108                    FormatToken *&ResetToken)
109       : Line(Line), TokenSource(TokenSource), ResetToken(ResetToken),
110         PreviousLineLevel(Line.Level), PreviousTokenSource(TokenSource),
111         Token(nullptr), PreviousToken(nullptr) {
112     FakeEOF.Tok.startToken();
113     FakeEOF.Tok.setKind(tok::eof);
114     TokenSource = this;
115     Line.Level = 0;
116     Line.InPPDirective = true;
117   }
118 
119   ~ScopedMacroState() override {
120     TokenSource = PreviousTokenSource;
121     ResetToken = Token;
122     Line.InPPDirective = false;
123     Line.Level = PreviousLineLevel;
124   }
125 
126   FormatToken *getNextToken() override {
127     // The \c UnwrappedLineParser guards against this by never calling
128     // \c getNextToken() after it has encountered the first eof token.
129     assert(!eof());
130     PreviousToken = Token;
131     Token = PreviousTokenSource->getNextToken();
132     if (eof())
133       return &FakeEOF;
134     return Token;
135   }
136 
137   FormatToken *getPreviousToken() override {
138     return PreviousTokenSource->getPreviousToken();
139   }
140 
141   FormatToken *peekNextToken() override {
142     if (eof())
143       return &FakeEOF;
144     return PreviousTokenSource->peekNextToken();
145   }
146 
147   FormatToken *peekNextToken(int N) override {
148     assert(N > 0);
149     if (eof())
150       return &FakeEOF;
151     return PreviousTokenSource->peekNextToken(N);
152   }
153 
154   bool isEOF() override { return PreviousTokenSource->isEOF(); }
155 
156   unsigned getPosition() override { return PreviousTokenSource->getPosition(); }
157 
158   FormatToken *setPosition(unsigned Position) override {
159     PreviousToken = nullptr;
160     Token = PreviousTokenSource->setPosition(Position);
161     return Token;
162   }
163 
164 private:
165   bool eof() {
166     return Token && Token->HasUnescapedNewline &&
167            !continuesLineComment(*Token, PreviousToken,
168                                  /*MinColumnToken=*/PreviousToken);
169   }
170 
171   FormatToken FakeEOF;
172   UnwrappedLine &Line;
173   FormatTokenSource *&TokenSource;
174   FormatToken *&ResetToken;
175   unsigned PreviousLineLevel;
176   FormatTokenSource *PreviousTokenSource;
177 
178   FormatToken *Token;
179   FormatToken *PreviousToken;
180 };
181 
182 } // end anonymous namespace
183 
184 class ScopedLineState {
185 public:
186   ScopedLineState(UnwrappedLineParser &Parser,
187                   bool SwitchToPreprocessorLines = false)
188       : Parser(Parser), OriginalLines(Parser.CurrentLines) {
189     if (SwitchToPreprocessorLines)
190       Parser.CurrentLines = &Parser.PreprocessorDirectives;
191     else if (!Parser.Line->Tokens.empty())
192       Parser.CurrentLines = &Parser.Line->Tokens.back().Children;
193     PreBlockLine = std::move(Parser.Line);
194     Parser.Line = std::make_unique<UnwrappedLine>();
195     Parser.Line->Level = PreBlockLine->Level;
196     Parser.Line->InPPDirective = PreBlockLine->InPPDirective;
197   }
198 
199   ~ScopedLineState() {
200     if (!Parser.Line->Tokens.empty())
201       Parser.addUnwrappedLine();
202     assert(Parser.Line->Tokens.empty());
203     Parser.Line = std::move(PreBlockLine);
204     if (Parser.CurrentLines == &Parser.PreprocessorDirectives)
205       Parser.MustBreakBeforeNextToken = true;
206     Parser.CurrentLines = OriginalLines;
207   }
208 
209 private:
210   UnwrappedLineParser &Parser;
211 
212   std::unique_ptr<UnwrappedLine> PreBlockLine;
213   SmallVectorImpl<UnwrappedLine> *OriginalLines;
214 };
215 
216 class CompoundStatementIndenter {
217 public:
218   CompoundStatementIndenter(UnwrappedLineParser *Parser,
219                             const FormatStyle &Style, unsigned &LineLevel)
220       : CompoundStatementIndenter(Parser, LineLevel,
221                                   Style.BraceWrapping.AfterControlStatement,
222                                   Style.BraceWrapping.IndentBraces) {}
223   CompoundStatementIndenter(UnwrappedLineParser *Parser, unsigned &LineLevel,
224                             bool WrapBrace, bool IndentBrace)
225       : LineLevel(LineLevel), OldLineLevel(LineLevel) {
226     if (WrapBrace)
227       Parser->addUnwrappedLine();
228     if (IndentBrace)
229       ++LineLevel;
230   }
231   ~CompoundStatementIndenter() { LineLevel = OldLineLevel; }
232 
233 private:
234   unsigned &LineLevel;
235   unsigned OldLineLevel;
236 };
237 
238 namespace {
239 
240 class IndexedTokenSource : public FormatTokenSource {
241 public:
242   IndexedTokenSource(ArrayRef<FormatToken *> Tokens)
243       : Tokens(Tokens), Position(-1) {}
244 
245   FormatToken *getNextToken() override {
246     if (Position >= 0 && Tokens[Position]->is(tok::eof)) {
247       LLVM_DEBUG({
248         llvm::dbgs() << "Next ";
249         dbgToken(Position);
250       });
251       return Tokens[Position];
252     }
253     ++Position;
254     LLVM_DEBUG({
255       llvm::dbgs() << "Next ";
256       dbgToken(Position);
257     });
258     return Tokens[Position];
259   }
260 
261   FormatToken *getPreviousToken() override {
262     return Position > 0 ? Tokens[Position - 1] : nullptr;
263   }
264 
265   FormatToken *peekNextToken() override {
266     int Next = Position + 1;
267     LLVM_DEBUG({
268       llvm::dbgs() << "Peeking ";
269       dbgToken(Next);
270     });
271     return Tokens[Next];
272   }
273 
274   FormatToken *peekNextToken(int N) override {
275     assert(N > 0);
276     int Next = Position + N;
277     LLVM_DEBUG({
278       llvm::dbgs() << "Peeking (+" << (N - 1) << ") ";
279       dbgToken(Next);
280     });
281     return Tokens[Next];
282   }
283 
284   bool isEOF() override { return Tokens[Position]->is(tok::eof); }
285 
286   unsigned getPosition() override {
287     LLVM_DEBUG(llvm::dbgs() << "Getting Position: " << Position << "\n");
288     assert(Position >= 0);
289     return Position;
290   }
291 
292   FormatToken *setPosition(unsigned P) override {
293     LLVM_DEBUG(llvm::dbgs() << "Setting Position: " << P << "\n");
294     Position = P;
295     return Tokens[Position];
296   }
297 
298   void reset() { Position = -1; }
299 
300 private:
301   void dbgToken(int Position, llvm::StringRef Indent = "") {
302     FormatToken *Tok = Tokens[Position];
303     llvm::dbgs() << Indent << "[" << Position
304                  << "] Token: " << Tok->Tok.getName() << " / " << Tok->TokenText
305                  << ", Macro: " << !!Tok->MacroCtx << "\n";
306   }
307 
308   ArrayRef<FormatToken *> Tokens;
309   int Position;
310 };
311 
312 } // end anonymous namespace
313 
314 UnwrappedLineParser::UnwrappedLineParser(const FormatStyle &Style,
315                                          const AdditionalKeywords &Keywords,
316                                          unsigned FirstStartColumn,
317                                          ArrayRef<FormatToken *> Tokens,
318                                          UnwrappedLineConsumer &Callback)
319     : Line(new UnwrappedLine), MustBreakBeforeNextToken(false),
320       CurrentLines(&Lines), Style(Style), Keywords(Keywords),
321       CommentPragmasRegex(Style.CommentPragmas), Tokens(nullptr),
322       Callback(Callback), AllTokens(Tokens), PPBranchLevel(-1),
323       IncludeGuard(Style.IndentPPDirectives == FormatStyle::PPDIS_None
324                        ? IG_Rejected
325                        : IG_Inited),
326       IncludeGuardToken(nullptr), FirstStartColumn(FirstStartColumn) {}
327 
328 void UnwrappedLineParser::reset() {
329   PPBranchLevel = -1;
330   IncludeGuard = Style.IndentPPDirectives == FormatStyle::PPDIS_None
331                      ? IG_Rejected
332                      : IG_Inited;
333   IncludeGuardToken = nullptr;
334   Line.reset(new UnwrappedLine);
335   CommentsBeforeNextToken.clear();
336   FormatTok = nullptr;
337   MustBreakBeforeNextToken = false;
338   PreprocessorDirectives.clear();
339   CurrentLines = &Lines;
340   DeclarationScopeStack.clear();
341   NestedTooDeep.clear();
342   PPStack.clear();
343   Line->FirstStartColumn = FirstStartColumn;
344 }
345 
346 void UnwrappedLineParser::parse() {
347   IndexedTokenSource TokenSource(AllTokens);
348   Line->FirstStartColumn = FirstStartColumn;
349   do {
350     LLVM_DEBUG(llvm::dbgs() << "----\n");
351     reset();
352     Tokens = &TokenSource;
353     TokenSource.reset();
354 
355     readToken();
356     parseFile();
357 
358     // If we found an include guard then all preprocessor directives (other than
359     // the guard) are over-indented by one.
360     if (IncludeGuard == IG_Found)
361       for (auto &Line : Lines)
362         if (Line.InPPDirective && Line.Level > 0)
363           --Line.Level;
364 
365     // Create line with eof token.
366     pushToken(FormatTok);
367     addUnwrappedLine();
368 
369     for (const UnwrappedLine &Line : Lines)
370       Callback.consumeUnwrappedLine(Line);
371 
372     Callback.finishRun();
373     Lines.clear();
374     while (!PPLevelBranchIndex.empty() &&
375            PPLevelBranchIndex.back() + 1 >= PPLevelBranchCount.back()) {
376       PPLevelBranchIndex.resize(PPLevelBranchIndex.size() - 1);
377       PPLevelBranchCount.resize(PPLevelBranchCount.size() - 1);
378     }
379     if (!PPLevelBranchIndex.empty()) {
380       ++PPLevelBranchIndex.back();
381       assert(PPLevelBranchIndex.size() == PPLevelBranchCount.size());
382       assert(PPLevelBranchIndex.back() <= PPLevelBranchCount.back());
383     }
384   } while (!PPLevelBranchIndex.empty());
385 }
386 
387 void UnwrappedLineParser::parseFile() {
388   // The top-level context in a file always has declarations, except for pre-
389   // processor directives and JavaScript files.
390   bool MustBeDeclaration = !Line->InPPDirective && !Style.isJavaScript();
391   ScopedDeclarationState DeclarationState(*Line, DeclarationScopeStack,
392                                           MustBeDeclaration);
393   if (Style.Language == FormatStyle::LK_TextProto)
394     parseBracedList();
395   else
396     parseLevel(/*HasOpeningBrace=*/false, /*CanContainBracedList=*/true);
397   // Make sure to format the remaining tokens.
398   //
399   // LK_TextProto is special since its top-level is parsed as the body of a
400   // braced list, which does not necessarily have natural line separators such
401   // as a semicolon. Comments after the last entry that have been determined to
402   // not belong to that line, as in:
403   //   key: value
404   //   // endfile comment
405   // do not have a chance to be put on a line of their own until this point.
406   // Here we add this newline before end-of-file comments.
407   if (Style.Language == FormatStyle::LK_TextProto &&
408       !CommentsBeforeNextToken.empty())
409     addUnwrappedLine();
410   flushComments(true);
411   addUnwrappedLine();
412 }
413 
414 void UnwrappedLineParser::parseCSharpGenericTypeConstraint() {
415   do {
416     switch (FormatTok->Tok.getKind()) {
417     case tok::l_brace:
418       return;
419     default:
420       if (FormatTok->is(Keywords.kw_where)) {
421         addUnwrappedLine();
422         nextToken();
423         parseCSharpGenericTypeConstraint();
424         break;
425       }
426       nextToken();
427       break;
428     }
429   } while (!eof());
430 }
431 
432 void UnwrappedLineParser::parseCSharpAttribute() {
433   int UnpairedSquareBrackets = 1;
434   do {
435     switch (FormatTok->Tok.getKind()) {
436     case tok::r_square:
437       nextToken();
438       --UnpairedSquareBrackets;
439       if (UnpairedSquareBrackets == 0) {
440         addUnwrappedLine();
441         return;
442       }
443       break;
444     case tok::l_square:
445       ++UnpairedSquareBrackets;
446       nextToken();
447       break;
448     default:
449       nextToken();
450       break;
451     }
452   } while (!eof());
453 }
454 
455 bool UnwrappedLineParser::precededByCommentOrPPDirective() const {
456   if (!Lines.empty() && Lines.back().InPPDirective)
457     return true;
458 
459   const FormatToken *Previous = Tokens->getPreviousToken();
460   return Previous && Previous->is(tok::comment) &&
461          (Previous->IsMultiline || Previous->NewlinesBefore > 0);
462 }
463 /// \brief Parses a level, that is ???.
464 /// \param HasOpeningBrace If that level is started by an opening brace.
465 /// \param CanContainBracedList If the content can contain (at any level) a
466 /// braced list.
467 /// \param NextLBracesType The type for left brace found in this level.
468 /// \returns true if a simple block, or false otherwise. (A simple block has a
469 /// single statement.)
470 bool UnwrappedLineParser::parseLevel(bool HasOpeningBrace,
471                                      bool CanContainBracedList,
472                                      IfStmtKind *IfKind,
473                                      TokenType NextLBracesType) {
474   auto NextLevelLBracesType = NextLBracesType == TT_CompoundRequirementLBrace
475                                   ? TT_BracedListLBrace
476                                   : TT_Unknown;
477   const bool IsPrecededByCommentOrPPDirective =
478       !Style.RemoveBracesLLVM || precededByCommentOrPPDirective();
479   unsigned StatementCount = 0;
480   bool SwitchLabelEncountered = false;
481   do {
482     tok::TokenKind kind = FormatTok->Tok.getKind();
483     if (FormatTok->getType() == TT_MacroBlockBegin)
484       kind = tok::l_brace;
485     else if (FormatTok->getType() == TT_MacroBlockEnd)
486       kind = tok::r_brace;
487 
488     auto ParseDefault = [this, HasOpeningBrace, IfKind, NextLevelLBracesType,
489                          &StatementCount] {
490       parseStructuralElement(IfKind, /*IsTopLevel=*/!HasOpeningBrace,
491                              /*NextLBracesType=*/NextLevelLBracesType);
492       ++StatementCount;
493       assert(StatementCount > 0 && "StatementCount overflow!");
494     };
495 
496     switch (kind) {
497     case tok::comment:
498       nextToken();
499       addUnwrappedLine();
500       break;
501     case tok::l_brace:
502       if (NextLBracesType != TT_Unknown)
503         FormatTok->setType(NextLBracesType);
504       else if (FormatTok->Previous &&
505                FormatTok->Previous->ClosesRequiresClause) {
506         // We need the 'default' case here to correctly parse a function
507         // l_brace.
508         ParseDefault();
509         continue;
510       }
511       if (CanContainBracedList && !FormatTok->is(TT_MacroBlockBegin) &&
512           tryToParseBracedList())
513         continue;
514       parseBlock(/*MustBeDeclaration=*/false, /*AddLevels=*/1u,
515                  /*MunchSemi=*/true, /*UnindentWhitesmithBraces=*/false,
516                  CanContainBracedList,
517                  /*NextLBracesType=*/NextLBracesType);
518       ++StatementCount;
519       assert(StatementCount > 0 && "StatementCount overflow!");
520       addUnwrappedLine();
521       break;
522     case tok::r_brace:
523       if (HasOpeningBrace) {
524         if (!Style.RemoveBracesLLVM)
525           return false;
526         if (FormatTok->isNot(tok::r_brace) || StatementCount != 1 ||
527             IsPrecededByCommentOrPPDirective ||
528             precededByCommentOrPPDirective())
529           return false;
530         const FormatToken *Next = Tokens->peekNextToken();
531         return Next->isNot(tok::comment) || Next->NewlinesBefore > 0;
532       }
533       nextToken();
534       addUnwrappedLine();
535       break;
536     case tok::kw_default: {
537       unsigned StoredPosition = Tokens->getPosition();
538       FormatToken *Next;
539       do {
540         Next = Tokens->getNextToken();
541         assert(Next);
542       } while (Next->is(tok::comment));
543       FormatTok = Tokens->setPosition(StoredPosition);
544       if (Next->isNot(tok::colon)) {
545         // default not followed by ':' is not a case label; treat it like
546         // an identifier.
547         parseStructuralElement();
548         break;
549       }
550       // Else, if it is 'default:', fall through to the case handling.
551       LLVM_FALLTHROUGH;
552     }
553     case tok::kw_case:
554       if (Style.isJavaScript() && Line->MustBeDeclaration) {
555         // A 'case: string' style field declaration.
556         parseStructuralElement();
557         break;
558       }
559       if (!SwitchLabelEncountered &&
560           (Style.IndentCaseLabels || (Line->InPPDirective && Line->Level == 1)))
561         ++Line->Level;
562       SwitchLabelEncountered = true;
563       parseStructuralElement();
564       break;
565     case tok::l_square:
566       if (Style.isCSharp()) {
567         nextToken();
568         parseCSharpAttribute();
569         break;
570       }
571       LLVM_FALLTHROUGH;
572     default:
573       ParseDefault();
574       break;
575     }
576   } while (!eof());
577   return false;
578 }
579 
580 void UnwrappedLineParser::calculateBraceTypes(bool ExpectClassBody) {
581   // We'll parse forward through the tokens until we hit
582   // a closing brace or eof - note that getNextToken() will
583   // parse macros, so this will magically work inside macro
584   // definitions, too.
585   unsigned StoredPosition = Tokens->getPosition();
586   FormatToken *Tok = FormatTok;
587   const FormatToken *PrevTok = Tok->Previous;
588   // Keep a stack of positions of lbrace tokens. We will
589   // update information about whether an lbrace starts a
590   // braced init list or a different block during the loop.
591   SmallVector<FormatToken *, 8> LBraceStack;
592   assert(Tok->is(tok::l_brace));
593   do {
594     // Get next non-comment token.
595     FormatToken *NextTok;
596     unsigned ReadTokens = 0;
597     do {
598       NextTok = Tokens->getNextToken();
599       ++ReadTokens;
600     } while (NextTok->is(tok::comment));
601 
602     switch (Tok->Tok.getKind()) {
603     case tok::l_brace:
604       if (Style.isJavaScript() && PrevTok) {
605         if (PrevTok->isOneOf(tok::colon, tok::less))
606           // A ':' indicates this code is in a type, or a braced list
607           // following a label in an object literal ({a: {b: 1}}).
608           // A '<' could be an object used in a comparison, but that is nonsense
609           // code (can never return true), so more likely it is a generic type
610           // argument (`X<{a: string; b: number}>`).
611           // The code below could be confused by semicolons between the
612           // individual members in a type member list, which would normally
613           // trigger BK_Block. In both cases, this must be parsed as an inline
614           // braced init.
615           Tok->setBlockKind(BK_BracedInit);
616         else if (PrevTok->is(tok::r_paren))
617           // `) { }` can only occur in function or method declarations in JS.
618           Tok->setBlockKind(BK_Block);
619       } else {
620         Tok->setBlockKind(BK_Unknown);
621       }
622       LBraceStack.push_back(Tok);
623       break;
624     case tok::r_brace:
625       if (LBraceStack.empty())
626         break;
627       if (LBraceStack.back()->is(BK_Unknown)) {
628         bool ProbablyBracedList = false;
629         if (Style.Language == FormatStyle::LK_Proto) {
630           ProbablyBracedList = NextTok->isOneOf(tok::comma, tok::r_square);
631         } else {
632           // Skip NextTok over preprocessor lines, otherwise we may not
633           // properly diagnose the block as a braced intializer
634           // if the comma separator appears after the pp directive.
635           while (NextTok->is(tok::hash)) {
636             ScopedMacroState MacroState(*Line, Tokens, NextTok);
637             do {
638               NextTok = Tokens->getNextToken();
639               ++ReadTokens;
640             } while (NextTok->isNot(tok::eof));
641           }
642 
643           // Using OriginalColumn to distinguish between ObjC methods and
644           // binary operators is a bit hacky.
645           bool NextIsObjCMethod = NextTok->isOneOf(tok::plus, tok::minus) &&
646                                   NextTok->OriginalColumn == 0;
647 
648           // Try to detect a braced list. Note that regardless how we mark inner
649           // braces here, we will overwrite the BlockKind later if we parse a
650           // braced list (where all blocks inside are by default braced lists),
651           // or when we explicitly detect blocks (for example while parsing
652           // lambdas).
653 
654           // If we already marked the opening brace as braced list, the closing
655           // must also be part of it.
656           ProbablyBracedList = LBraceStack.back()->is(TT_BracedListLBrace);
657 
658           ProbablyBracedList = ProbablyBracedList ||
659                                (Style.isJavaScript() &&
660                                 NextTok->isOneOf(Keywords.kw_of, Keywords.kw_in,
661                                                  Keywords.kw_as));
662           ProbablyBracedList = ProbablyBracedList ||
663                                (Style.isCpp() && NextTok->is(tok::l_paren));
664 
665           // If there is a comma, semicolon or right paren after the closing
666           // brace, we assume this is a braced initializer list.
667           // FIXME: Some of these do not apply to JS, e.g. "} {" can never be a
668           // braced list in JS.
669           ProbablyBracedList =
670               ProbablyBracedList ||
671               NextTok->isOneOf(tok::comma, tok::period, tok::colon,
672                                tok::r_paren, tok::r_square, tok::l_brace,
673                                tok::ellipsis);
674 
675           ProbablyBracedList =
676               ProbablyBracedList ||
677               (NextTok->is(tok::identifier) &&
678                !PrevTok->isOneOf(tok::semi, tok::r_brace, tok::l_brace));
679 
680           ProbablyBracedList = ProbablyBracedList ||
681                                (NextTok->is(tok::semi) &&
682                                 (!ExpectClassBody || LBraceStack.size() != 1));
683 
684           ProbablyBracedList =
685               ProbablyBracedList ||
686               (NextTok->isBinaryOperator() && !NextIsObjCMethod);
687 
688           if (!Style.isCSharp() && NextTok->is(tok::l_square)) {
689             // We can have an array subscript after a braced init
690             // list, but C++11 attributes are expected after blocks.
691             NextTok = Tokens->getNextToken();
692             ++ReadTokens;
693             ProbablyBracedList = NextTok->isNot(tok::l_square);
694           }
695         }
696         if (ProbablyBracedList) {
697           Tok->setBlockKind(BK_BracedInit);
698           LBraceStack.back()->setBlockKind(BK_BracedInit);
699         } else {
700           Tok->setBlockKind(BK_Block);
701           LBraceStack.back()->setBlockKind(BK_Block);
702         }
703       }
704       LBraceStack.pop_back();
705       break;
706     case tok::identifier:
707       if (!Tok->is(TT_StatementMacro))
708         break;
709       LLVM_FALLTHROUGH;
710     case tok::at:
711     case tok::semi:
712     case tok::kw_if:
713     case tok::kw_while:
714     case tok::kw_for:
715     case tok::kw_switch:
716     case tok::kw_try:
717     case tok::kw___try:
718       if (!LBraceStack.empty() && LBraceStack.back()->is(BK_Unknown))
719         LBraceStack.back()->setBlockKind(BK_Block);
720       break;
721     default:
722       break;
723     }
724     PrevTok = Tok;
725     Tok = NextTok;
726   } while (Tok->isNot(tok::eof) && !LBraceStack.empty());
727 
728   // Assume other blocks for all unclosed opening braces.
729   for (FormatToken *LBrace : LBraceStack)
730     if (LBrace->is(BK_Unknown))
731       LBrace->setBlockKind(BK_Block);
732 
733   FormatTok = Tokens->setPosition(StoredPosition);
734 }
735 
736 template <class T>
737 static inline void hash_combine(std::size_t &seed, const T &v) {
738   std::hash<T> hasher;
739   seed ^= hasher(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
740 }
741 
742 size_t UnwrappedLineParser::computePPHash() const {
743   size_t h = 0;
744   for (const auto &i : PPStack) {
745     hash_combine(h, size_t(i.Kind));
746     hash_combine(h, i.Line);
747   }
748   return h;
749 }
750 
751 UnwrappedLineParser::IfStmtKind
752 UnwrappedLineParser::parseBlock(bool MustBeDeclaration, unsigned AddLevels,
753                                 bool MunchSemi, bool UnindentWhitesmithsBraces,
754                                 bool CanContainBracedList,
755                                 TokenType NextLBracesType) {
756   assert(FormatTok->isOneOf(tok::l_brace, TT_MacroBlockBegin) &&
757          "'{' or macro block token expected");
758   FormatToken *Tok = FormatTok;
759   const bool MacroBlock = FormatTok->is(TT_MacroBlockBegin);
760   FormatTok->setBlockKind(BK_Block);
761 
762   // For Whitesmiths mode, jump to the next level prior to skipping over the
763   // braces.
764   if (AddLevels > 0 && Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths)
765     ++Line->Level;
766 
767   size_t PPStartHash = computePPHash();
768 
769   unsigned InitialLevel = Line->Level;
770   nextToken(/*LevelDifference=*/AddLevels);
771 
772   if (MacroBlock && FormatTok->is(tok::l_paren))
773     parseParens();
774 
775   size_t NbPreprocessorDirectives =
776       CurrentLines == &Lines ? PreprocessorDirectives.size() : 0;
777   addUnwrappedLine();
778   size_t OpeningLineIndex =
779       CurrentLines->empty()
780           ? (UnwrappedLine::kInvalidIndex)
781           : (CurrentLines->size() - 1 - NbPreprocessorDirectives);
782 
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)
787     --Line->Level;
788 
789   ScopedDeclarationState DeclarationState(*Line, DeclarationScopeStack,
790                                           MustBeDeclaration);
791   if (AddLevels > 0u && Style.BreakBeforeBraces != FormatStyle::BS_Whitesmiths)
792     Line->Level += AddLevels;
793 
794   IfStmtKind IfKind = IfStmtKind::NotIf;
795   const bool SimpleBlock = parseLevel(
796       /*HasOpeningBrace=*/true, CanContainBracedList, &IfKind, NextLBracesType);
797 
798   if (eof())
799     return IfKind;
800 
801   if (MacroBlock ? !FormatTok->is(TT_MacroBlockEnd)
802                  : !FormatTok->is(tok::r_brace)) {
803     Line->Level = InitialLevel;
804     FormatTok->setBlockKind(BK_Block);
805     return IfKind;
806   }
807 
808   if (SimpleBlock && Tok->is(tok::l_brace)) {
809     assert(FormatTok->is(tok::r_brace));
810     const FormatToken *Previous = Tokens->getPreviousToken();
811     assert(Previous);
812     if (Previous->isNot(tok::r_brace) || Previous->Optional) {
813       Tok->MatchingParen = FormatTok;
814       FormatTok->MatchingParen = Tok;
815     }
816   }
817 
818   size_t PPEndHash = computePPHash();
819 
820   // Munch the closing brace.
821   nextToken(/*LevelDifference=*/-AddLevels);
822 
823   if (MacroBlock && FormatTok->is(tok::l_paren))
824     parseParens();
825 
826   if (FormatTok->is(tok::kw_noexcept)) {
827     // A noexcept in a requires expression.
828     nextToken();
829   }
830 
831   if (FormatTok->is(tok::arrow)) {
832     // Following the } or noexcept we can find a trailing return type arrow
833     // as part of an implicit conversion constraint.
834     nextToken();
835     parseStructuralElement();
836   }
837 
838   if (MunchSemi && FormatTok->is(tok::semi))
839     nextToken();
840 
841   Line->Level = InitialLevel;
842 
843   if (PPStartHash == PPEndHash) {
844     Line->MatchingOpeningBlockLineIndex = OpeningLineIndex;
845     if (OpeningLineIndex != UnwrappedLine::kInvalidIndex) {
846       // Update the opening line to add the forward reference as well
847       (*CurrentLines)[OpeningLineIndex].MatchingClosingBlockLineIndex =
848           CurrentLines->size() - 1;
849     }
850   }
851 
852   return IfKind;
853 }
854 
855 static bool isGoogScope(const UnwrappedLine &Line) {
856   // FIXME: Closure-library specific stuff should not be hard-coded but be
857   // configurable.
858   if (Line.Tokens.size() < 4)
859     return false;
860   auto I = Line.Tokens.begin();
861   if (I->Tok->TokenText != "goog")
862     return false;
863   ++I;
864   if (I->Tok->isNot(tok::period))
865     return false;
866   ++I;
867   if (I->Tok->TokenText != "scope")
868     return false;
869   ++I;
870   return I->Tok->is(tok::l_paren);
871 }
872 
873 static bool isIIFE(const UnwrappedLine &Line,
874                    const AdditionalKeywords &Keywords) {
875   // Look for the start of an immediately invoked anonymous function.
876   // https://en.wikipedia.org/wiki/Immediately-invoked_function_expression
877   // This is commonly done in JavaScript to create a new, anonymous scope.
878   // Example: (function() { ... })()
879   if (Line.Tokens.size() < 3)
880     return false;
881   auto I = Line.Tokens.begin();
882   if (I->Tok->isNot(tok::l_paren))
883     return false;
884   ++I;
885   if (I->Tok->isNot(Keywords.kw_function))
886     return false;
887   ++I;
888   return I->Tok->is(tok::l_paren);
889 }
890 
891 static bool ShouldBreakBeforeBrace(const FormatStyle &Style,
892                                    const FormatToken &InitialToken) {
893   if (InitialToken.isOneOf(tok::kw_namespace, TT_NamespaceMacro))
894     return Style.BraceWrapping.AfterNamespace;
895   if (InitialToken.is(tok::kw_class))
896     return Style.BraceWrapping.AfterClass;
897   if (InitialToken.is(tok::kw_union))
898     return Style.BraceWrapping.AfterUnion;
899   if (InitialToken.is(tok::kw_struct))
900     return Style.BraceWrapping.AfterStruct;
901   if (InitialToken.is(tok::kw_enum))
902     return Style.BraceWrapping.AfterEnum;
903   return false;
904 }
905 
906 void UnwrappedLineParser::parseChildBlock(
907     bool CanContainBracedList, clang::format::TokenType NextLBracesType) {
908   FormatTok->setBlockKind(BK_Block);
909   nextToken();
910   {
911     bool SkipIndent = (Style.isJavaScript() &&
912                        (isGoogScope(*Line) || isIIFE(*Line, Keywords)));
913     ScopedLineState LineState(*this);
914     ScopedDeclarationState DeclarationState(*Line, DeclarationScopeStack,
915                                             /*MustBeDeclaration=*/false);
916     Line->Level += SkipIndent ? 0 : 1;
917     parseLevel(/*HasOpeningBrace=*/true, CanContainBracedList,
918                /*IfKind=*/nullptr, NextLBracesType);
919     flushComments(isOnNewLine(*FormatTok));
920     Line->Level -= SkipIndent ? 0 : 1;
921   }
922   nextToken();
923 }
924 
925 void UnwrappedLineParser::parsePPDirective() {
926   assert(FormatTok->is(tok::hash) && "'#' expected");
927   ScopedMacroState MacroState(*Line, Tokens, FormatTok);
928 
929   nextToken();
930 
931   if (!FormatTok->Tok.getIdentifierInfo()) {
932     parsePPUnknown();
933     return;
934   }
935 
936   switch (FormatTok->Tok.getIdentifierInfo()->getPPKeywordID()) {
937   case tok::pp_define:
938     parsePPDefine();
939     return;
940   case tok::pp_if:
941     parsePPIf(/*IfDef=*/false);
942     break;
943   case tok::pp_ifdef:
944   case tok::pp_ifndef:
945     parsePPIf(/*IfDef=*/true);
946     break;
947   case tok::pp_else:
948     parsePPElse();
949     break;
950   case tok::pp_elifdef:
951   case tok::pp_elifndef:
952   case tok::pp_elif:
953     parsePPElIf();
954     break;
955   case tok::pp_endif:
956     parsePPEndIf();
957     break;
958   default:
959     parsePPUnknown();
960     break;
961   }
962 }
963 
964 void UnwrappedLineParser::conditionalCompilationCondition(bool Unreachable) {
965   size_t Line = CurrentLines->size();
966   if (CurrentLines == &PreprocessorDirectives)
967     Line += Lines.size();
968 
969   if (Unreachable ||
970       (!PPStack.empty() && PPStack.back().Kind == PP_Unreachable))
971     PPStack.push_back({PP_Unreachable, Line});
972   else
973     PPStack.push_back({PP_Conditional, Line});
974 }
975 
976 void UnwrappedLineParser::conditionalCompilationStart(bool Unreachable) {
977   ++PPBranchLevel;
978   assert(PPBranchLevel >= 0 && PPBranchLevel <= (int)PPLevelBranchIndex.size());
979   if (PPBranchLevel == (int)PPLevelBranchIndex.size()) {
980     PPLevelBranchIndex.push_back(0);
981     PPLevelBranchCount.push_back(0);
982   }
983   PPChainBranchIndex.push(0);
984   bool Skip = PPLevelBranchIndex[PPBranchLevel] > 0;
985   conditionalCompilationCondition(Unreachable || Skip);
986 }
987 
988 void UnwrappedLineParser::conditionalCompilationAlternative() {
989   if (!PPStack.empty())
990     PPStack.pop_back();
991   assert(PPBranchLevel < (int)PPLevelBranchIndex.size());
992   if (!PPChainBranchIndex.empty())
993     ++PPChainBranchIndex.top();
994   conditionalCompilationCondition(
995       PPBranchLevel >= 0 && !PPChainBranchIndex.empty() &&
996       PPLevelBranchIndex[PPBranchLevel] != PPChainBranchIndex.top());
997 }
998 
999 void UnwrappedLineParser::conditionalCompilationEnd() {
1000   assert(PPBranchLevel < (int)PPLevelBranchIndex.size());
1001   if (PPBranchLevel >= 0 && !PPChainBranchIndex.empty()) {
1002     if (PPChainBranchIndex.top() + 1 > PPLevelBranchCount[PPBranchLevel])
1003       PPLevelBranchCount[PPBranchLevel] = PPChainBranchIndex.top() + 1;
1004   }
1005   // Guard against #endif's without #if.
1006   if (PPBranchLevel > -1)
1007     --PPBranchLevel;
1008   if (!PPChainBranchIndex.empty())
1009     PPChainBranchIndex.pop();
1010   if (!PPStack.empty())
1011     PPStack.pop_back();
1012 }
1013 
1014 void UnwrappedLineParser::parsePPIf(bool IfDef) {
1015   bool IfNDef = FormatTok->is(tok::pp_ifndef);
1016   nextToken();
1017   bool Unreachable = false;
1018   if (!IfDef && (FormatTok->is(tok::kw_false) || FormatTok->TokenText == "0"))
1019     Unreachable = true;
1020   if (IfDef && !IfNDef && FormatTok->TokenText == "SWIG")
1021     Unreachable = true;
1022   conditionalCompilationStart(Unreachable);
1023   FormatToken *IfCondition = FormatTok;
1024   // If there's a #ifndef on the first line, and the only lines before it are
1025   // comments, it could be an include guard.
1026   bool MaybeIncludeGuard = IfNDef;
1027   if (IncludeGuard == IG_Inited && MaybeIncludeGuard)
1028     for (auto &Line : Lines) {
1029       if (!Line.Tokens.front().Tok->is(tok::comment)) {
1030         MaybeIncludeGuard = false;
1031         IncludeGuard = IG_Rejected;
1032         break;
1033       }
1034     }
1035   --PPBranchLevel;
1036   parsePPUnknown();
1037   ++PPBranchLevel;
1038   if (IncludeGuard == IG_Inited && MaybeIncludeGuard) {
1039     IncludeGuard = IG_IfNdefed;
1040     IncludeGuardToken = IfCondition;
1041   }
1042 }
1043 
1044 void UnwrappedLineParser::parsePPElse() {
1045   // If a potential include guard has an #else, it's not an include guard.
1046   if (IncludeGuard == IG_Defined && PPBranchLevel == 0)
1047     IncludeGuard = IG_Rejected;
1048   conditionalCompilationAlternative();
1049   if (PPBranchLevel > -1)
1050     --PPBranchLevel;
1051   parsePPUnknown();
1052   ++PPBranchLevel;
1053 }
1054 
1055 void UnwrappedLineParser::parsePPElIf() { parsePPElse(); }
1056 
1057 void UnwrappedLineParser::parsePPEndIf() {
1058   conditionalCompilationEnd();
1059   parsePPUnknown();
1060   // If the #endif of a potential include guard is the last thing in the file,
1061   // then we found an include guard.
1062   if (IncludeGuard == IG_Defined && PPBranchLevel == -1 && Tokens->isEOF() &&
1063       Style.IndentPPDirectives != FormatStyle::PPDIS_None)
1064     IncludeGuard = IG_Found;
1065 }
1066 
1067 void UnwrappedLineParser::parsePPDefine() {
1068   nextToken();
1069 
1070   if (!FormatTok->Tok.getIdentifierInfo()) {
1071     IncludeGuard = IG_Rejected;
1072     IncludeGuardToken = nullptr;
1073     parsePPUnknown();
1074     return;
1075   }
1076 
1077   if (IncludeGuard == IG_IfNdefed &&
1078       IncludeGuardToken->TokenText == FormatTok->TokenText) {
1079     IncludeGuard = IG_Defined;
1080     IncludeGuardToken = nullptr;
1081     for (auto &Line : Lines) {
1082       if (!Line.Tokens.front().Tok->isOneOf(tok::comment, tok::hash)) {
1083         IncludeGuard = IG_Rejected;
1084         break;
1085       }
1086     }
1087   }
1088 
1089   // In the context of a define, even keywords should be treated as normal
1090   // identifiers. Setting the kind to identifier is not enough, because we need
1091   // to treat additional keywords like __except as well, which are already
1092   // identifiers. Setting the identifier info to null interferes with include
1093   // guard processing above, and changes preprocessing nesting.
1094   FormatTok->Tok.setKind(tok::identifier);
1095   FormatTok->Tok.setIdentifierInfo(Keywords.kw_internal_ident_after_define);
1096   nextToken();
1097   if (FormatTok->Tok.getKind() == tok::l_paren &&
1098       !FormatTok->hasWhitespaceBefore())
1099     parseParens();
1100   if (Style.IndentPPDirectives != FormatStyle::PPDIS_None)
1101     Line->Level += PPBranchLevel + 1;
1102   addUnwrappedLine();
1103   ++Line->Level;
1104 
1105   // Errors during a preprocessor directive can only affect the layout of the
1106   // preprocessor directive, and thus we ignore them. An alternative approach
1107   // would be to use the same approach we use on the file level (no
1108   // re-indentation if there was a structural error) within the macro
1109   // definition.
1110   parseFile();
1111 }
1112 
1113 void UnwrappedLineParser::parsePPUnknown() {
1114   do {
1115     nextToken();
1116   } while (!eof());
1117   if (Style.IndentPPDirectives != FormatStyle::PPDIS_None)
1118     Line->Level += PPBranchLevel + 1;
1119   addUnwrappedLine();
1120 }
1121 
1122 // Here we exclude certain tokens that are not usually the first token in an
1123 // unwrapped line. This is used in attempt to distinguish macro calls without
1124 // trailing semicolons from other constructs split to several lines.
1125 static bool tokenCanStartNewLine(const FormatToken &Tok) {
1126   // Semicolon can be a null-statement, l_square can be a start of a macro or
1127   // a C++11 attribute, but this doesn't seem to be common.
1128   return Tok.isNot(tok::semi) && Tok.isNot(tok::l_brace) &&
1129          Tok.isNot(TT_AttributeSquare) &&
1130          // Tokens that can only be used as binary operators and a part of
1131          // overloaded operator names.
1132          Tok.isNot(tok::period) && Tok.isNot(tok::periodstar) &&
1133          Tok.isNot(tok::arrow) && Tok.isNot(tok::arrowstar) &&
1134          Tok.isNot(tok::less) && Tok.isNot(tok::greater) &&
1135          Tok.isNot(tok::slash) && Tok.isNot(tok::percent) &&
1136          Tok.isNot(tok::lessless) && Tok.isNot(tok::greatergreater) &&
1137          Tok.isNot(tok::equal) && Tok.isNot(tok::plusequal) &&
1138          Tok.isNot(tok::minusequal) && Tok.isNot(tok::starequal) &&
1139          Tok.isNot(tok::slashequal) && Tok.isNot(tok::percentequal) &&
1140          Tok.isNot(tok::ampequal) && Tok.isNot(tok::pipeequal) &&
1141          Tok.isNot(tok::caretequal) && Tok.isNot(tok::greatergreaterequal) &&
1142          Tok.isNot(tok::lesslessequal) &&
1143          // Colon is used in labels, base class lists, initializer lists,
1144          // range-based for loops, ternary operator, but should never be the
1145          // first token in an unwrapped line.
1146          Tok.isNot(tok::colon) &&
1147          // 'noexcept' is a trailing annotation.
1148          Tok.isNot(tok::kw_noexcept);
1149 }
1150 
1151 static bool mustBeJSIdent(const AdditionalKeywords &Keywords,
1152                           const FormatToken *FormatTok) {
1153   // FIXME: This returns true for C/C++ keywords like 'struct'.
1154   return FormatTok->is(tok::identifier) &&
1155          (FormatTok->Tok.getIdentifierInfo() == nullptr ||
1156           !FormatTok->isOneOf(
1157               Keywords.kw_in, Keywords.kw_of, Keywords.kw_as, Keywords.kw_async,
1158               Keywords.kw_await, Keywords.kw_yield, Keywords.kw_finally,
1159               Keywords.kw_function, Keywords.kw_import, Keywords.kw_is,
1160               Keywords.kw_let, Keywords.kw_var, tok::kw_const,
1161               Keywords.kw_abstract, Keywords.kw_extends, Keywords.kw_implements,
1162               Keywords.kw_instanceof, Keywords.kw_interface,
1163               Keywords.kw_override, Keywords.kw_throws, Keywords.kw_from));
1164 }
1165 
1166 static bool mustBeJSIdentOrValue(const AdditionalKeywords &Keywords,
1167                                  const FormatToken *FormatTok) {
1168   return FormatTok->Tok.isLiteral() ||
1169          FormatTok->isOneOf(tok::kw_true, tok::kw_false) ||
1170          mustBeJSIdent(Keywords, FormatTok);
1171 }
1172 
1173 // isJSDeclOrStmt returns true if |FormatTok| starts a declaration or statement
1174 // when encountered after a value (see mustBeJSIdentOrValue).
1175 static bool isJSDeclOrStmt(const AdditionalKeywords &Keywords,
1176                            const FormatToken *FormatTok) {
1177   return FormatTok->isOneOf(
1178       tok::kw_return, Keywords.kw_yield,
1179       // conditionals
1180       tok::kw_if, tok::kw_else,
1181       // loops
1182       tok::kw_for, tok::kw_while, tok::kw_do, tok::kw_continue, tok::kw_break,
1183       // switch/case
1184       tok::kw_switch, tok::kw_case,
1185       // exceptions
1186       tok::kw_throw, tok::kw_try, tok::kw_catch, Keywords.kw_finally,
1187       // declaration
1188       tok::kw_const, tok::kw_class, Keywords.kw_var, Keywords.kw_let,
1189       Keywords.kw_async, Keywords.kw_function,
1190       // import/export
1191       Keywords.kw_import, tok::kw_export);
1192 }
1193 
1194 // Checks whether a token is a type in K&R C (aka C78).
1195 static bool isC78Type(const FormatToken &Tok) {
1196   return Tok.isOneOf(tok::kw_char, tok::kw_short, tok::kw_int, tok::kw_long,
1197                      tok::kw_unsigned, tok::kw_float, tok::kw_double,
1198                      tok::identifier);
1199 }
1200 
1201 // This function checks whether a token starts the first parameter declaration
1202 // in a K&R C (aka C78) function definition, e.g.:
1203 //   int f(a, b)
1204 //   short a, b;
1205 //   {
1206 //      return a + b;
1207 //   }
1208 static bool isC78ParameterDecl(const FormatToken *Tok, const FormatToken *Next,
1209                                const FormatToken *FuncName) {
1210   assert(Tok);
1211   assert(Next);
1212   assert(FuncName);
1213 
1214   if (FuncName->isNot(tok::identifier))
1215     return false;
1216 
1217   const FormatToken *Prev = FuncName->Previous;
1218   if (!Prev || (Prev->isNot(tok::star) && !isC78Type(*Prev)))
1219     return false;
1220 
1221   if (!isC78Type(*Tok) &&
1222       !Tok->isOneOf(tok::kw_register, tok::kw_struct, tok::kw_union))
1223     return false;
1224 
1225   if (Next->isNot(tok::star) && !Next->Tok.getIdentifierInfo())
1226     return false;
1227 
1228   Tok = Tok->Previous;
1229   if (!Tok || Tok->isNot(tok::r_paren))
1230     return false;
1231 
1232   Tok = Tok->Previous;
1233   if (!Tok || Tok->isNot(tok::identifier))
1234     return false;
1235 
1236   return Tok->Previous && Tok->Previous->isOneOf(tok::l_paren, tok::comma);
1237 }
1238 
1239 void UnwrappedLineParser::parseModuleImport() {
1240   nextToken();
1241   while (!eof()) {
1242     if (FormatTok->is(tok::colon)) {
1243       FormatTok->setType(TT_ModulePartitionColon);
1244     }
1245     // Handle import <foo/bar.h> as we would an include statement.
1246     else if (FormatTok->is(tok::less)) {
1247       nextToken();
1248       while (!FormatTok->isOneOf(tok::semi, tok::greater, tok::eof)) {
1249         // Mark tokens up to the trailing line comments as implicit string
1250         // literals.
1251         if (FormatTok->isNot(tok::comment) &&
1252             !FormatTok->TokenText.startswith("//"))
1253           FormatTok->setType(TT_ImplicitStringLiteral);
1254         nextToken();
1255       }
1256     }
1257     if (FormatTok->is(tok::semi)) {
1258       nextToken();
1259       break;
1260     }
1261     nextToken();
1262   }
1263 
1264   addUnwrappedLine();
1265 }
1266 
1267 // readTokenWithJavaScriptASI reads the next token and terminates the current
1268 // line if JavaScript Automatic Semicolon Insertion must
1269 // happen between the current token and the next token.
1270 //
1271 // This method is conservative - it cannot cover all edge cases of JavaScript,
1272 // but only aims to correctly handle certain well known cases. It *must not*
1273 // return true in speculative cases.
1274 void UnwrappedLineParser::readTokenWithJavaScriptASI() {
1275   FormatToken *Previous = FormatTok;
1276   readToken();
1277   FormatToken *Next = FormatTok;
1278 
1279   bool IsOnSameLine =
1280       CommentsBeforeNextToken.empty()
1281           ? Next->NewlinesBefore == 0
1282           : CommentsBeforeNextToken.front()->NewlinesBefore == 0;
1283   if (IsOnSameLine)
1284     return;
1285 
1286   bool PreviousMustBeValue = mustBeJSIdentOrValue(Keywords, Previous);
1287   bool PreviousStartsTemplateExpr =
1288       Previous->is(TT_TemplateString) && Previous->TokenText.endswith("${");
1289   if (PreviousMustBeValue || Previous->is(tok::r_paren)) {
1290     // If the line contains an '@' sign, the previous token might be an
1291     // annotation, which can precede another identifier/value.
1292     bool HasAt = llvm::any_of(Line->Tokens, [](UnwrappedLineNode &LineNode) {
1293       return LineNode.Tok->is(tok::at);
1294     });
1295     if (HasAt)
1296       return;
1297   }
1298   if (Next->is(tok::exclaim) && PreviousMustBeValue)
1299     return addUnwrappedLine();
1300   bool NextMustBeValue = mustBeJSIdentOrValue(Keywords, Next);
1301   bool NextEndsTemplateExpr =
1302       Next->is(TT_TemplateString) && Next->TokenText.startswith("}");
1303   if (NextMustBeValue && !NextEndsTemplateExpr && !PreviousStartsTemplateExpr &&
1304       (PreviousMustBeValue ||
1305        Previous->isOneOf(tok::r_square, tok::r_paren, tok::plusplus,
1306                          tok::minusminus)))
1307     return addUnwrappedLine();
1308   if ((PreviousMustBeValue || Previous->is(tok::r_paren)) &&
1309       isJSDeclOrStmt(Keywords, Next))
1310     return addUnwrappedLine();
1311 }
1312 
1313 void UnwrappedLineParser::parseStructuralElement(IfStmtKind *IfKind,
1314                                                  bool IsTopLevel,
1315                                                  TokenType NextLBracesType) {
1316   if (Style.Language == FormatStyle::LK_TableGen &&
1317       FormatTok->is(tok::pp_include)) {
1318     nextToken();
1319     if (FormatTok->is(tok::string_literal))
1320       nextToken();
1321     addUnwrappedLine();
1322     return;
1323   }
1324   switch (FormatTok->Tok.getKind()) {
1325   case tok::kw_asm:
1326     nextToken();
1327     if (FormatTok->is(tok::l_brace)) {
1328       FormatTok->setType(TT_InlineASMBrace);
1329       nextToken();
1330       while (FormatTok && FormatTok->isNot(tok::eof)) {
1331         if (FormatTok->is(tok::r_brace)) {
1332           FormatTok->setType(TT_InlineASMBrace);
1333           nextToken();
1334           addUnwrappedLine();
1335           break;
1336         }
1337         FormatTok->Finalized = true;
1338         nextToken();
1339       }
1340     }
1341     break;
1342   case tok::kw_namespace:
1343     parseNamespace();
1344     return;
1345   case tok::kw_public:
1346   case tok::kw_protected:
1347   case tok::kw_private:
1348     if (Style.Language == FormatStyle::LK_Java || Style.isJavaScript() ||
1349         Style.isCSharp())
1350       nextToken();
1351     else
1352       parseAccessSpecifier();
1353     return;
1354   case tok::kw_if:
1355     if (Style.isJavaScript() && Line->MustBeDeclaration)
1356       // field/method declaration.
1357       break;
1358     parseIfThenElse(IfKind);
1359     return;
1360   case tok::kw_for:
1361   case tok::kw_while:
1362     if (Style.isJavaScript() && Line->MustBeDeclaration)
1363       // field/method declaration.
1364       break;
1365     parseForOrWhileLoop();
1366     return;
1367   case tok::kw_do:
1368     if (Style.isJavaScript() && Line->MustBeDeclaration)
1369       // field/method declaration.
1370       break;
1371     parseDoWhile();
1372     return;
1373   case tok::kw_switch:
1374     if (Style.isJavaScript() && Line->MustBeDeclaration)
1375       // 'switch: string' field declaration.
1376       break;
1377     parseSwitch();
1378     return;
1379   case tok::kw_default:
1380     if (Style.isJavaScript() && Line->MustBeDeclaration)
1381       // 'default: string' field declaration.
1382       break;
1383     nextToken();
1384     if (FormatTok->is(tok::colon)) {
1385       parseLabel();
1386       return;
1387     }
1388     // e.g. "default void f() {}" in a Java interface.
1389     break;
1390   case tok::kw_case:
1391     if (Style.isJavaScript() && Line->MustBeDeclaration)
1392       // 'case: string' field declaration.
1393       break;
1394     parseCaseLabel();
1395     return;
1396   case tok::kw_try:
1397   case tok::kw___try:
1398     if (Style.isJavaScript() && Line->MustBeDeclaration)
1399       // field/method declaration.
1400       break;
1401     parseTryCatch();
1402     return;
1403   case tok::kw_extern:
1404     nextToken();
1405     if (FormatTok->is(tok::string_literal)) {
1406       nextToken();
1407       if (FormatTok->is(tok::l_brace)) {
1408         if (Style.BraceWrapping.AfterExternBlock)
1409           addUnwrappedLine();
1410         // Either we indent or for backwards compatibility we follow the
1411         // AfterExternBlock style.
1412         unsigned AddLevels =
1413             (Style.IndentExternBlock == FormatStyle::IEBS_Indent) ||
1414                     (Style.BraceWrapping.AfterExternBlock &&
1415                      Style.IndentExternBlock ==
1416                          FormatStyle::IEBS_AfterExternBlock)
1417                 ? 1u
1418                 : 0u;
1419         parseBlock(/*MustBeDeclaration=*/true, AddLevels);
1420         addUnwrappedLine();
1421         return;
1422       }
1423     }
1424     break;
1425   case tok::kw_export:
1426     if (Style.isJavaScript()) {
1427       parseJavaScriptEs6ImportExport();
1428       return;
1429     }
1430     if (!Style.isCpp())
1431       break;
1432     // Handle C++ "(inline|export) namespace".
1433     LLVM_FALLTHROUGH;
1434   case tok::kw_inline:
1435     nextToken();
1436     if (FormatTok->is(tok::kw_namespace)) {
1437       parseNamespace();
1438       return;
1439     }
1440     break;
1441   case tok::identifier:
1442     if (FormatTok->is(TT_ForEachMacro)) {
1443       parseForOrWhileLoop();
1444       return;
1445     }
1446     if (FormatTok->is(TT_MacroBlockBegin)) {
1447       parseBlock(/*MustBeDeclaration=*/false, /*AddLevels=*/1u,
1448                  /*MunchSemi=*/false);
1449       return;
1450     }
1451     if (FormatTok->is(Keywords.kw_import)) {
1452       if (Style.isJavaScript()) {
1453         parseJavaScriptEs6ImportExport();
1454         return;
1455       }
1456       if (Style.Language == FormatStyle::LK_Proto) {
1457         nextToken();
1458         if (FormatTok->is(tok::kw_public))
1459           nextToken();
1460         if (!FormatTok->is(tok::string_literal))
1461           return;
1462         nextToken();
1463         if (FormatTok->is(tok::semi))
1464           nextToken();
1465         addUnwrappedLine();
1466         return;
1467       }
1468       if (Style.isCpp()) {
1469         parseModuleImport();
1470         return;
1471       }
1472     }
1473     if (Style.isCpp() &&
1474         FormatTok->isOneOf(Keywords.kw_signals, Keywords.kw_qsignals,
1475                            Keywords.kw_slots, Keywords.kw_qslots)) {
1476       nextToken();
1477       if (FormatTok->is(tok::colon)) {
1478         nextToken();
1479         addUnwrappedLine();
1480         return;
1481       }
1482     }
1483     if (Style.isCpp() && FormatTok->is(TT_StatementMacro)) {
1484       parseStatementMacro();
1485       return;
1486     }
1487     if (Style.isCpp() && FormatTok->is(TT_NamespaceMacro)) {
1488       parseNamespace();
1489       return;
1490     }
1491     // In all other cases, parse the declaration.
1492     break;
1493   default:
1494     break;
1495   }
1496   do {
1497     const FormatToken *Previous = FormatTok->Previous;
1498     switch (FormatTok->Tok.getKind()) {
1499     case tok::at:
1500       nextToken();
1501       if (FormatTok->is(tok::l_brace)) {
1502         nextToken();
1503         parseBracedList();
1504         break;
1505       } else if (Style.Language == FormatStyle::LK_Java &&
1506                  FormatTok->is(Keywords.kw_interface)) {
1507         nextToken();
1508         break;
1509       }
1510       switch (FormatTok->Tok.getObjCKeywordID()) {
1511       case tok::objc_public:
1512       case tok::objc_protected:
1513       case tok::objc_package:
1514       case tok::objc_private:
1515         return parseAccessSpecifier();
1516       case tok::objc_interface:
1517       case tok::objc_implementation:
1518         return parseObjCInterfaceOrImplementation();
1519       case tok::objc_protocol:
1520         if (parseObjCProtocol())
1521           return;
1522         break;
1523       case tok::objc_end:
1524         return; // Handled by the caller.
1525       case tok::objc_optional:
1526       case tok::objc_required:
1527         nextToken();
1528         addUnwrappedLine();
1529         return;
1530       case tok::objc_autoreleasepool:
1531         nextToken();
1532         if (FormatTok->is(tok::l_brace)) {
1533           if (Style.BraceWrapping.AfterControlStatement ==
1534               FormatStyle::BWACS_Always)
1535             addUnwrappedLine();
1536           parseBlock();
1537         }
1538         addUnwrappedLine();
1539         return;
1540       case tok::objc_synchronized:
1541         nextToken();
1542         if (FormatTok->is(tok::l_paren))
1543           // Skip synchronization object
1544           parseParens();
1545         if (FormatTok->is(tok::l_brace)) {
1546           if (Style.BraceWrapping.AfterControlStatement ==
1547               FormatStyle::BWACS_Always)
1548             addUnwrappedLine();
1549           parseBlock();
1550         }
1551         addUnwrappedLine();
1552         return;
1553       case tok::objc_try:
1554         // This branch isn't strictly necessary (the kw_try case below would
1555         // do this too after the tok::at is parsed above).  But be explicit.
1556         parseTryCatch();
1557         return;
1558       default:
1559         break;
1560       }
1561       break;
1562     case tok::kw_concept:
1563       parseConcept();
1564       return;
1565     case tok::kw_requires: {
1566       if (Style.isCpp()) {
1567         bool ParsedClause = parseRequires();
1568         if (ParsedClause)
1569           return;
1570       } else {
1571         nextToken();
1572       }
1573       break;
1574     }
1575     case tok::kw_enum:
1576       // Ignore if this is part of "template <enum ...".
1577       if (Previous && Previous->is(tok::less)) {
1578         nextToken();
1579         break;
1580       }
1581 
1582       // parseEnum falls through and does not yet add an unwrapped line as an
1583       // enum definition can start a structural element.
1584       if (!parseEnum())
1585         break;
1586       // This only applies for C++.
1587       if (!Style.isCpp()) {
1588         addUnwrappedLine();
1589         return;
1590       }
1591       break;
1592     case tok::kw_typedef:
1593       nextToken();
1594       if (FormatTok->isOneOf(Keywords.kw_NS_ENUM, Keywords.kw_NS_OPTIONS,
1595                              Keywords.kw_CF_ENUM, Keywords.kw_CF_OPTIONS,
1596                              Keywords.kw_CF_CLOSED_ENUM,
1597                              Keywords.kw_NS_CLOSED_ENUM))
1598         parseEnum();
1599       break;
1600     case tok::kw_struct:
1601     case tok::kw_union:
1602     case tok::kw_class:
1603       if (parseStructLike())
1604         return;
1605       break;
1606     case tok::period:
1607       nextToken();
1608       // In Java, classes have an implicit static member "class".
1609       if (Style.Language == FormatStyle::LK_Java && FormatTok &&
1610           FormatTok->is(tok::kw_class))
1611         nextToken();
1612       if (Style.isJavaScript() && FormatTok &&
1613           FormatTok->Tok.getIdentifierInfo())
1614         // JavaScript only has pseudo keywords, all keywords are allowed to
1615         // appear in "IdentifierName" positions. See http://es5.github.io/#x7.6
1616         nextToken();
1617       break;
1618     case tok::semi:
1619       nextToken();
1620       addUnwrappedLine();
1621       return;
1622     case tok::r_brace:
1623       addUnwrappedLine();
1624       return;
1625     case tok::l_paren: {
1626       parseParens();
1627       // Break the unwrapped line if a K&R C function definition has a parameter
1628       // declaration.
1629       if (!IsTopLevel || !Style.isCpp() || !Previous || FormatTok->is(tok::eof))
1630         break;
1631       if (isC78ParameterDecl(FormatTok, Tokens->peekNextToken(), Previous)) {
1632         addUnwrappedLine();
1633         return;
1634       }
1635       break;
1636     }
1637     case tok::kw_operator:
1638       nextToken();
1639       if (FormatTok->isBinaryOperator())
1640         nextToken();
1641       break;
1642     case tok::caret:
1643       nextToken();
1644       if (FormatTok->Tok.isAnyIdentifier() ||
1645           FormatTok->isSimpleTypeSpecifier())
1646         nextToken();
1647       if (FormatTok->is(tok::l_paren))
1648         parseParens();
1649       if (FormatTok->is(tok::l_brace))
1650         parseChildBlock();
1651       break;
1652     case tok::l_brace:
1653       if (NextLBracesType != TT_Unknown)
1654         FormatTok->setType(NextLBracesType);
1655       if (!tryToParsePropertyAccessor() && !tryToParseBracedList()) {
1656         // A block outside of parentheses must be the last part of a
1657         // structural element.
1658         // FIXME: Figure out cases where this is not true, and add projections
1659         // for them (the one we know is missing are lambdas).
1660         if (Style.Language == FormatStyle::LK_Java &&
1661             Line->Tokens.front().Tok->is(Keywords.kw_synchronized)) {
1662           // If necessary, we could set the type to something different than
1663           // TT_FunctionLBrace.
1664           if (Style.BraceWrapping.AfterControlStatement ==
1665               FormatStyle::BWACS_Always)
1666             addUnwrappedLine();
1667         } else if (Style.BraceWrapping.AfterFunction) {
1668           addUnwrappedLine();
1669         }
1670         if (!Line->InPPDirective)
1671           FormatTok->setType(TT_FunctionLBrace);
1672         parseBlock();
1673         addUnwrappedLine();
1674         return;
1675       }
1676       // Otherwise this was a braced init list, and the structural
1677       // element continues.
1678       break;
1679     case tok::kw_try:
1680       if (Style.isJavaScript() && Line->MustBeDeclaration) {
1681         // field/method declaration.
1682         nextToken();
1683         break;
1684       }
1685       // We arrive here when parsing function-try blocks.
1686       if (Style.BraceWrapping.AfterFunction)
1687         addUnwrappedLine();
1688       parseTryCatch();
1689       return;
1690     case tok::identifier: {
1691       if (Style.isCSharp() && FormatTok->is(Keywords.kw_where) &&
1692           Line->MustBeDeclaration) {
1693         addUnwrappedLine();
1694         parseCSharpGenericTypeConstraint();
1695         break;
1696       }
1697       if (FormatTok->is(TT_MacroBlockEnd)) {
1698         addUnwrappedLine();
1699         return;
1700       }
1701 
1702       // Function declarations (as opposed to function expressions) are parsed
1703       // on their own unwrapped line by continuing this loop. Function
1704       // expressions (functions that are not on their own line) must not create
1705       // a new unwrapped line, so they are special cased below.
1706       size_t TokenCount = Line->Tokens.size();
1707       if (Style.isJavaScript() && FormatTok->is(Keywords.kw_function) &&
1708           (TokenCount > 1 || (TokenCount == 1 && !Line->Tokens.front().Tok->is(
1709                                                      Keywords.kw_async)))) {
1710         tryToParseJSFunction();
1711         break;
1712       }
1713       if ((Style.isJavaScript() || Style.Language == FormatStyle::LK_Java) &&
1714           FormatTok->is(Keywords.kw_interface)) {
1715         if (Style.isJavaScript()) {
1716           // In JavaScript/TypeScript, "interface" can be used as a standalone
1717           // identifier, e.g. in `var interface = 1;`. If "interface" is
1718           // followed by another identifier, it is very like to be an actual
1719           // interface declaration.
1720           unsigned StoredPosition = Tokens->getPosition();
1721           FormatToken *Next = Tokens->getNextToken();
1722           FormatTok = Tokens->setPosition(StoredPosition);
1723           if (!mustBeJSIdent(Keywords, Next)) {
1724             nextToken();
1725             break;
1726           }
1727         }
1728         parseRecord();
1729         addUnwrappedLine();
1730         return;
1731       }
1732 
1733       if (FormatTok->is(Keywords.kw_interface)) {
1734         if (parseStructLike())
1735           return;
1736         break;
1737       }
1738 
1739       if (Style.isCpp() && FormatTok->is(TT_StatementMacro)) {
1740         parseStatementMacro();
1741         return;
1742       }
1743 
1744       // See if the following token should start a new unwrapped line.
1745       StringRef Text = FormatTok->TokenText;
1746 
1747       FormatToken *PreviousToken = FormatTok;
1748       nextToken();
1749 
1750       // JS doesn't have macros, and within classes colons indicate fields, not
1751       // labels.
1752       if (Style.isJavaScript())
1753         break;
1754 
1755       TokenCount = Line->Tokens.size();
1756       if (TokenCount == 1 ||
1757           (TokenCount == 2 && Line->Tokens.front().Tok->is(tok::comment))) {
1758         if (FormatTok->is(tok::colon) && !Line->MustBeDeclaration) {
1759           Line->Tokens.begin()->Tok->MustBreakBefore = true;
1760           parseLabel(!Style.IndentGotoLabels);
1761           return;
1762         }
1763         // Recognize function-like macro usages without trailing semicolon as
1764         // well as free-standing macros like Q_OBJECT.
1765         bool FunctionLike = FormatTok->is(tok::l_paren);
1766         if (FunctionLike)
1767           parseParens();
1768 
1769         bool FollowedByNewline =
1770             CommentsBeforeNextToken.empty()
1771                 ? FormatTok->NewlinesBefore > 0
1772                 : CommentsBeforeNextToken.front()->NewlinesBefore > 0;
1773 
1774         if (FollowedByNewline && (Text.size() >= 5 || FunctionLike) &&
1775             tokenCanStartNewLine(*FormatTok) && Text == Text.upper()) {
1776           PreviousToken->setType(TT_FunctionLikeOrFreestandingMacro);
1777           addUnwrappedLine();
1778           return;
1779         }
1780       }
1781       break;
1782     }
1783     case tok::equal:
1784       if ((Style.isJavaScript() || Style.isCSharp()) &&
1785           FormatTok->is(TT_FatArrow)) {
1786         tryToParseChildBlock();
1787         break;
1788       }
1789 
1790       nextToken();
1791       if (FormatTok->is(tok::l_brace)) {
1792         // Block kind should probably be set to BK_BracedInit for any language.
1793         // C# needs this change to ensure that array initialisers and object
1794         // initialisers are indented the same way.
1795         if (Style.isCSharp())
1796           FormatTok->setBlockKind(BK_BracedInit);
1797         nextToken();
1798         parseBracedList();
1799       } else if (Style.Language == FormatStyle::LK_Proto &&
1800                  FormatTok->is(tok::less)) {
1801         nextToken();
1802         parseBracedList(/*ContinueOnSemicolons=*/false, /*IsEnum=*/false,
1803                         /*ClosingBraceKind=*/tok::greater);
1804       }
1805       break;
1806     case tok::l_square:
1807       parseSquare();
1808       break;
1809     case tok::kw_new:
1810       parseNew();
1811       break;
1812     default:
1813       nextToken();
1814       break;
1815     }
1816   } while (!eof());
1817 }
1818 
1819 bool UnwrappedLineParser::tryToParsePropertyAccessor() {
1820   assert(FormatTok->is(tok::l_brace));
1821   if (!Style.isCSharp())
1822     return false;
1823   // See if it's a property accessor.
1824   if (FormatTok->Previous->isNot(tok::identifier))
1825     return false;
1826 
1827   // See if we are inside a property accessor.
1828   //
1829   // Record the current tokenPosition so that we can advance and
1830   // reset the current token. `Next` is not set yet so we need
1831   // another way to advance along the token stream.
1832   unsigned int StoredPosition = Tokens->getPosition();
1833   FormatToken *Tok = Tokens->getNextToken();
1834 
1835   // A trivial property accessor is of the form:
1836   // { [ACCESS_SPECIFIER] [get]; [ACCESS_SPECIFIER] [set] }
1837   // Track these as they do not require line breaks to be introduced.
1838   bool HasGetOrSet = false;
1839   bool IsTrivialPropertyAccessor = true;
1840   while (!eof()) {
1841     if (Tok->isOneOf(tok::semi, tok::kw_public, tok::kw_private,
1842                      tok::kw_protected, Keywords.kw_internal, Keywords.kw_get,
1843                      Keywords.kw_set)) {
1844       if (Tok->isOneOf(Keywords.kw_get, Keywords.kw_set))
1845         HasGetOrSet = true;
1846       Tok = Tokens->getNextToken();
1847       continue;
1848     }
1849     if (Tok->isNot(tok::r_brace))
1850       IsTrivialPropertyAccessor = false;
1851     break;
1852   }
1853 
1854   if (!HasGetOrSet) {
1855     Tokens->setPosition(StoredPosition);
1856     return false;
1857   }
1858 
1859   // Try to parse the property accessor:
1860   // https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/properties
1861   Tokens->setPosition(StoredPosition);
1862   if (!IsTrivialPropertyAccessor && Style.BraceWrapping.AfterFunction)
1863     addUnwrappedLine();
1864   nextToken();
1865   do {
1866     switch (FormatTok->Tok.getKind()) {
1867     case tok::r_brace:
1868       nextToken();
1869       if (FormatTok->is(tok::equal)) {
1870         while (!eof() && FormatTok->isNot(tok::semi))
1871           nextToken();
1872         nextToken();
1873       }
1874       addUnwrappedLine();
1875       return true;
1876     case tok::l_brace:
1877       ++Line->Level;
1878       parseBlock(/*MustBeDeclaration=*/true);
1879       addUnwrappedLine();
1880       --Line->Level;
1881       break;
1882     case tok::equal:
1883       if (FormatTok->is(TT_FatArrow)) {
1884         ++Line->Level;
1885         do {
1886           nextToken();
1887         } while (!eof() && FormatTok->isNot(tok::semi));
1888         nextToken();
1889         addUnwrappedLine();
1890         --Line->Level;
1891         break;
1892       }
1893       nextToken();
1894       break;
1895     default:
1896       if (FormatTok->isOneOf(Keywords.kw_get, Keywords.kw_set) &&
1897           !IsTrivialPropertyAccessor) {
1898         // Non-trivial get/set needs to be on its own line.
1899         addUnwrappedLine();
1900       }
1901       nextToken();
1902     }
1903   } while (!eof());
1904 
1905   // Unreachable for well-formed code (paired '{' and '}').
1906   return true;
1907 }
1908 
1909 bool UnwrappedLineParser::tryToParseLambda() {
1910   if (!Style.isCpp()) {
1911     nextToken();
1912     return false;
1913   }
1914   assert(FormatTok->is(tok::l_square));
1915   FormatToken &LSquare = *FormatTok;
1916   if (!tryToParseLambdaIntroducer())
1917     return false;
1918 
1919   bool SeenArrow = false;
1920   bool InTemplateParameterList = false;
1921 
1922   while (FormatTok->isNot(tok::l_brace)) {
1923     if (FormatTok->isSimpleTypeSpecifier()) {
1924       nextToken();
1925       continue;
1926     }
1927     switch (FormatTok->Tok.getKind()) {
1928     case tok::l_brace:
1929       break;
1930     case tok::l_paren:
1931       parseParens();
1932       break;
1933     case tok::l_square:
1934       parseSquare();
1935       break;
1936     case tok::kw_class:
1937     case tok::kw_template:
1938     case tok::kw_typename:
1939       assert(FormatTok->Previous);
1940       if (FormatTok->Previous->is(tok::less))
1941         InTemplateParameterList = true;
1942       nextToken();
1943       break;
1944     case tok::amp:
1945     case tok::star:
1946     case tok::kw_const:
1947     case tok::comma:
1948     case tok::less:
1949     case tok::greater:
1950     case tok::identifier:
1951     case tok::numeric_constant:
1952     case tok::coloncolon:
1953     case tok::kw_mutable:
1954     case tok::kw_noexcept:
1955       nextToken();
1956       break;
1957     // Specialization of a template with an integer parameter can contain
1958     // arithmetic, logical, comparison and ternary operators.
1959     //
1960     // FIXME: This also accepts sequences of operators that are not in the scope
1961     // of a template argument list.
1962     //
1963     // In a C++ lambda a template type can only occur after an arrow. We use
1964     // this as an heuristic to distinguish between Objective-C expressions
1965     // followed by an `a->b` expression, such as:
1966     // ([obj func:arg] + a->b)
1967     // Otherwise the code below would parse as a lambda.
1968     //
1969     // FIXME: This heuristic is incorrect for C++20 generic lambdas with
1970     // explicit template lists: []<bool b = true && false>(U &&u){}
1971     case tok::plus:
1972     case tok::minus:
1973     case tok::exclaim:
1974     case tok::tilde:
1975     case tok::slash:
1976     case tok::percent:
1977     case tok::lessless:
1978     case tok::pipe:
1979     case tok::pipepipe:
1980     case tok::ampamp:
1981     case tok::caret:
1982     case tok::equalequal:
1983     case tok::exclaimequal:
1984     case tok::greaterequal:
1985     case tok::lessequal:
1986     case tok::question:
1987     case tok::colon:
1988     case tok::ellipsis:
1989     case tok::kw_true:
1990     case tok::kw_false:
1991       if (SeenArrow || InTemplateParameterList) {
1992         nextToken();
1993         break;
1994       }
1995       return true;
1996     case tok::arrow:
1997       // This might or might not actually be a lambda arrow (this could be an
1998       // ObjC method invocation followed by a dereferencing arrow). We might
1999       // reset this back to TT_Unknown in TokenAnnotator.
2000       FormatTok->setType(TT_LambdaArrow);
2001       SeenArrow = true;
2002       nextToken();
2003       break;
2004     default:
2005       return true;
2006     }
2007   }
2008   FormatTok->setType(TT_LambdaLBrace);
2009   LSquare.setType(TT_LambdaLSquare);
2010   parseChildBlock();
2011   return true;
2012 }
2013 
2014 bool UnwrappedLineParser::tryToParseLambdaIntroducer() {
2015   const FormatToken *Previous = FormatTok->Previous;
2016   if (Previous &&
2017       (Previous->isOneOf(tok::identifier, tok::kw_operator, tok::kw_new,
2018                          tok::kw_delete, tok::l_square) ||
2019        FormatTok->isCppStructuredBinding(Style) || Previous->closesScope() ||
2020        Previous->isSimpleTypeSpecifier())) {
2021     nextToken();
2022     return false;
2023   }
2024   nextToken();
2025   if (FormatTok->is(tok::l_square))
2026     return false;
2027   parseSquare(/*LambdaIntroducer=*/true);
2028   return true;
2029 }
2030 
2031 void UnwrappedLineParser::tryToParseJSFunction() {
2032   assert(FormatTok->is(Keywords.kw_function) ||
2033          FormatTok->startsSequence(Keywords.kw_async, Keywords.kw_function));
2034   if (FormatTok->is(Keywords.kw_async))
2035     nextToken();
2036   // Consume "function".
2037   nextToken();
2038 
2039   // Consume * (generator function). Treat it like C++'s overloaded operators.
2040   if (FormatTok->is(tok::star)) {
2041     FormatTok->setType(TT_OverloadedOperator);
2042     nextToken();
2043   }
2044 
2045   // Consume function name.
2046   if (FormatTok->is(tok::identifier))
2047     nextToken();
2048 
2049   if (FormatTok->isNot(tok::l_paren))
2050     return;
2051 
2052   // Parse formal parameter list.
2053   parseParens();
2054 
2055   if (FormatTok->is(tok::colon)) {
2056     // Parse a type definition.
2057     nextToken();
2058 
2059     // Eat the type declaration. For braced inline object types, balance braces,
2060     // otherwise just parse until finding an l_brace for the function body.
2061     if (FormatTok->is(tok::l_brace))
2062       tryToParseBracedList();
2063     else
2064       while (!FormatTok->isOneOf(tok::l_brace, tok::semi) && !eof())
2065         nextToken();
2066   }
2067 
2068   if (FormatTok->is(tok::semi))
2069     return;
2070 
2071   parseChildBlock();
2072 }
2073 
2074 bool UnwrappedLineParser::tryToParseBracedList() {
2075   if (FormatTok->is(BK_Unknown))
2076     calculateBraceTypes();
2077   assert(FormatTok->isNot(BK_Unknown));
2078   if (FormatTok->is(BK_Block))
2079     return false;
2080   nextToken();
2081   parseBracedList();
2082   return true;
2083 }
2084 
2085 bool UnwrappedLineParser::tryToParseChildBlock() {
2086   assert(Style.isJavaScript() || Style.isCSharp());
2087   assert(FormatTok->is(TT_FatArrow));
2088   // Fat arrows (=>) have tok::TokenKind tok::equal but TokenType TT_FatArrow.
2089   // They always start an expression or a child block if followed by a curly
2090   // brace.
2091   nextToken();
2092   if (FormatTok->isNot(tok::l_brace))
2093     return false;
2094   parseChildBlock();
2095   return true;
2096 }
2097 
2098 bool UnwrappedLineParser::parseBracedList(bool ContinueOnSemicolons,
2099                                           bool IsEnum,
2100                                           tok::TokenKind ClosingBraceKind) {
2101   bool HasError = false;
2102 
2103   // FIXME: Once we have an expression parser in the UnwrappedLineParser,
2104   // replace this by using parseAssignmentExpression() inside.
2105   do {
2106     if (Style.isCSharp() && FormatTok->is(TT_FatArrow) &&
2107         tryToParseChildBlock())
2108       continue;
2109     if (Style.isJavaScript()) {
2110       if (FormatTok->is(Keywords.kw_function) ||
2111           FormatTok->startsSequence(Keywords.kw_async, Keywords.kw_function)) {
2112         tryToParseJSFunction();
2113         continue;
2114       }
2115       if (FormatTok->is(tok::l_brace)) {
2116         // Could be a method inside of a braced list `{a() { return 1; }}`.
2117         if (tryToParseBracedList())
2118           continue;
2119         parseChildBlock();
2120       }
2121     }
2122     if (FormatTok->Tok.getKind() == ClosingBraceKind) {
2123       if (IsEnum && !Style.AllowShortEnumsOnASingleLine)
2124         addUnwrappedLine();
2125       nextToken();
2126       return !HasError;
2127     }
2128     switch (FormatTok->Tok.getKind()) {
2129     case tok::l_square:
2130       if (Style.isCSharp())
2131         parseSquare();
2132       else
2133         tryToParseLambda();
2134       break;
2135     case tok::l_paren:
2136       parseParens();
2137       // JavaScript can just have free standing methods and getters/setters in
2138       // object literals. Detect them by a "{" following ")".
2139       if (Style.isJavaScript()) {
2140         if (FormatTok->is(tok::l_brace))
2141           parseChildBlock();
2142         break;
2143       }
2144       break;
2145     case tok::l_brace:
2146       // Assume there are no blocks inside a braced init list apart
2147       // from the ones we explicitly parse out (like lambdas).
2148       FormatTok->setBlockKind(BK_BracedInit);
2149       nextToken();
2150       parseBracedList();
2151       break;
2152     case tok::less:
2153       if (Style.Language == FormatStyle::LK_Proto) {
2154         nextToken();
2155         parseBracedList(/*ContinueOnSemicolons=*/false, /*IsEnum=*/false,
2156                         /*ClosingBraceKind=*/tok::greater);
2157       } else {
2158         nextToken();
2159       }
2160       break;
2161     case tok::semi:
2162       // JavaScript (or more precisely TypeScript) can have semicolons in braced
2163       // lists (in so-called TypeMemberLists). Thus, the semicolon cannot be
2164       // used for error recovery if we have otherwise determined that this is
2165       // a braced list.
2166       if (Style.isJavaScript()) {
2167         nextToken();
2168         break;
2169       }
2170       HasError = true;
2171       if (!ContinueOnSemicolons)
2172         return !HasError;
2173       nextToken();
2174       break;
2175     case tok::comma:
2176       nextToken();
2177       if (IsEnum && !Style.AllowShortEnumsOnASingleLine)
2178         addUnwrappedLine();
2179       break;
2180     default:
2181       nextToken();
2182       break;
2183     }
2184   } while (!eof());
2185   return false;
2186 }
2187 
2188 /// \brief Parses a pair of parentheses (and everything between them).
2189 /// \param AmpAmpTokenType If different than TT_Unknown sets this type for all
2190 /// double ampersands. This only counts for the current parens scope.
2191 void UnwrappedLineParser::parseParens(TokenType AmpAmpTokenType) {
2192   assert(FormatTok->is(tok::l_paren) && "'(' expected.");
2193   nextToken();
2194   do {
2195     switch (FormatTok->Tok.getKind()) {
2196     case tok::l_paren:
2197       parseParens();
2198       if (Style.Language == FormatStyle::LK_Java && FormatTok->is(tok::l_brace))
2199         parseChildBlock();
2200       break;
2201     case tok::r_paren:
2202       nextToken();
2203       return;
2204     case tok::r_brace:
2205       // A "}" inside parenthesis is an error if there wasn't a matching "{".
2206       return;
2207     case tok::l_square:
2208       tryToParseLambda();
2209       break;
2210     case tok::l_brace:
2211       if (!tryToParseBracedList())
2212         parseChildBlock();
2213       break;
2214     case tok::at:
2215       nextToken();
2216       if (FormatTok->is(tok::l_brace)) {
2217         nextToken();
2218         parseBracedList();
2219       }
2220       break;
2221     case tok::equal:
2222       if (Style.isCSharp() && FormatTok->is(TT_FatArrow))
2223         tryToParseChildBlock();
2224       else
2225         nextToken();
2226       break;
2227     case tok::kw_class:
2228       if (Style.isJavaScript())
2229         parseRecord(/*ParseAsExpr=*/true);
2230       else
2231         nextToken();
2232       break;
2233     case tok::identifier:
2234       if (Style.isJavaScript() &&
2235           (FormatTok->is(Keywords.kw_function) ||
2236            FormatTok->startsSequence(Keywords.kw_async, Keywords.kw_function)))
2237         tryToParseJSFunction();
2238       else
2239         nextToken();
2240       break;
2241     case tok::kw_requires: {
2242       auto RequiresToken = FormatTok;
2243       nextToken();
2244       parseRequiresExpression(RequiresToken);
2245       break;
2246     }
2247     case tok::ampamp:
2248       if (AmpAmpTokenType != TT_Unknown)
2249         FormatTok->setType(AmpAmpTokenType);
2250       LLVM_FALLTHROUGH;
2251     default:
2252       nextToken();
2253       break;
2254     }
2255   } while (!eof());
2256 }
2257 
2258 void UnwrappedLineParser::parseSquare(bool LambdaIntroducer) {
2259   if (!LambdaIntroducer) {
2260     assert(FormatTok->is(tok::l_square) && "'[' expected.");
2261     if (tryToParseLambda())
2262       return;
2263   }
2264   do {
2265     switch (FormatTok->Tok.getKind()) {
2266     case tok::l_paren:
2267       parseParens();
2268       break;
2269     case tok::r_square:
2270       nextToken();
2271       return;
2272     case tok::r_brace:
2273       // A "}" inside parenthesis is an error if there wasn't a matching "{".
2274       return;
2275     case tok::l_square:
2276       parseSquare();
2277       break;
2278     case tok::l_brace: {
2279       if (!tryToParseBracedList())
2280         parseChildBlock();
2281       break;
2282     }
2283     case tok::at:
2284       nextToken();
2285       if (FormatTok->is(tok::l_brace)) {
2286         nextToken();
2287         parseBracedList();
2288       }
2289       break;
2290     default:
2291       nextToken();
2292       break;
2293     }
2294   } while (!eof());
2295 }
2296 
2297 void UnwrappedLineParser::keepAncestorBraces() {
2298   if (!Style.RemoveBracesLLVM)
2299     return;
2300 
2301   const int MaxNestingLevels = 2;
2302   const int Size = NestedTooDeep.size();
2303   if (Size >= MaxNestingLevels)
2304     NestedTooDeep[Size - MaxNestingLevels] = true;
2305   NestedTooDeep.push_back(false);
2306 }
2307 
2308 static FormatToken *getLastNonComment(const UnwrappedLine &Line) {
2309   for (const auto &Token : llvm::reverse(Line.Tokens))
2310     if (Token.Tok->isNot(tok::comment))
2311       return Token.Tok;
2312 
2313   return nullptr;
2314 }
2315 
2316 void UnwrappedLineParser::parseUnbracedBody(bool CheckEOF) {
2317   FormatToken *Tok = nullptr;
2318 
2319   if (Style.InsertBraces && !Line->InPPDirective && !Line->Tokens.empty() &&
2320       PreprocessorDirectives.empty()) {
2321     Tok = getLastNonComment(*Line);
2322     assert(Tok);
2323     if (Tok->BraceCount < 0) {
2324       assert(Tok->BraceCount == -1);
2325       Tok = nullptr;
2326     } else {
2327       Tok->BraceCount = -1;
2328     }
2329   }
2330 
2331   addUnwrappedLine();
2332   ++Line->Level;
2333   parseStructuralElement();
2334 
2335   if (Tok) {
2336     assert(!Line->InPPDirective);
2337     Tok = nullptr;
2338     for (const auto &L : llvm::reverse(*CurrentLines)) {
2339       if (!L.InPPDirective) {
2340         Tok = getLastNonComment(L);
2341         if (Tok)
2342           break;
2343       }
2344     }
2345     assert(Tok);
2346     ++Tok->BraceCount;
2347   }
2348 
2349   if (CheckEOF && FormatTok->is(tok::eof))
2350     addUnwrappedLine();
2351 
2352   --Line->Level;
2353 }
2354 
2355 static void markOptionalBraces(FormatToken *LeftBrace) {
2356   if (!LeftBrace)
2357     return;
2358 
2359   assert(LeftBrace->is(tok::l_brace));
2360 
2361   FormatToken *RightBrace = LeftBrace->MatchingParen;
2362   if (!RightBrace) {
2363     assert(!LeftBrace->Optional);
2364     return;
2365   }
2366 
2367   assert(RightBrace->is(tok::r_brace));
2368   assert(RightBrace->MatchingParen == LeftBrace);
2369   assert(LeftBrace->Optional == RightBrace->Optional);
2370 
2371   LeftBrace->Optional = true;
2372   RightBrace->Optional = true;
2373 }
2374 
2375 FormatToken *UnwrappedLineParser::parseIfThenElse(IfStmtKind *IfKind,
2376                                                   bool KeepBraces) {
2377   auto HandleAttributes = [this]() {
2378     // Handle AttributeMacro, e.g. `if (x) UNLIKELY`.
2379     if (FormatTok->is(TT_AttributeMacro))
2380       nextToken();
2381     // Handle [[likely]] / [[unlikely]] attributes.
2382     if (FormatTok->is(tok::l_square) && tryToParseSimpleAttribute())
2383       parseSquare();
2384   };
2385 
2386   assert(FormatTok->is(tok::kw_if) && "'if' expected");
2387   nextToken();
2388   if (FormatTok->isOneOf(tok::kw_constexpr, tok::identifier))
2389     nextToken();
2390   if (FormatTok->is(tok::l_paren))
2391     parseParens();
2392   HandleAttributes();
2393 
2394   bool NeedsUnwrappedLine = false;
2395   keepAncestorBraces();
2396 
2397   FormatToken *IfLeftBrace = nullptr;
2398   IfStmtKind IfBlockKind = IfStmtKind::NotIf;
2399 
2400   if (FormatTok->is(tok::l_brace)) {
2401     IfLeftBrace = FormatTok;
2402     CompoundStatementIndenter Indenter(this, Style, Line->Level);
2403     IfBlockKind = parseBlock();
2404     if (Style.BraceWrapping.BeforeElse)
2405       addUnwrappedLine();
2406     else
2407       NeedsUnwrappedLine = true;
2408   } else {
2409     parseUnbracedBody();
2410   }
2411 
2412   bool KeepIfBraces = false;
2413   if (Style.RemoveBracesLLVM) {
2414     assert(!NestedTooDeep.empty());
2415     KeepIfBraces = (IfLeftBrace && !IfLeftBrace->MatchingParen) ||
2416                    NestedTooDeep.back() || IfBlockKind == IfStmtKind::IfOnly ||
2417                    IfBlockKind == IfStmtKind::IfElseIf;
2418   }
2419 
2420   FormatToken *ElseLeftBrace = nullptr;
2421   IfStmtKind Kind = IfStmtKind::IfOnly;
2422 
2423   if (FormatTok->is(tok::kw_else)) {
2424     if (Style.RemoveBracesLLVM) {
2425       NestedTooDeep.back() = false;
2426       Kind = IfStmtKind::IfElse;
2427     }
2428     nextToken();
2429     HandleAttributes();
2430     if (FormatTok->is(tok::l_brace)) {
2431       ElseLeftBrace = FormatTok;
2432       CompoundStatementIndenter Indenter(this, Style, Line->Level);
2433       if (parseBlock() == IfStmtKind::IfOnly)
2434         Kind = IfStmtKind::IfElseIf;
2435       addUnwrappedLine();
2436     } else if (FormatTok->is(tok::kw_if)) {
2437       FormatToken *Previous = Tokens->getPreviousToken();
2438       const bool IsPrecededByComment = Previous && Previous->is(tok::comment);
2439       if (IsPrecededByComment) {
2440         addUnwrappedLine();
2441         ++Line->Level;
2442       }
2443       bool TooDeep = true;
2444       if (Style.RemoveBracesLLVM) {
2445         Kind = IfStmtKind::IfElseIf;
2446         TooDeep = NestedTooDeep.pop_back_val();
2447       }
2448       ElseLeftBrace =
2449           parseIfThenElse(/*IfKind=*/nullptr, KeepBraces || KeepIfBraces);
2450       if (Style.RemoveBracesLLVM)
2451         NestedTooDeep.push_back(TooDeep);
2452       if (IsPrecededByComment)
2453         --Line->Level;
2454     } else {
2455       parseUnbracedBody(/*CheckEOF=*/true);
2456     }
2457   } else {
2458     if (Style.RemoveBracesLLVM)
2459       KeepIfBraces = KeepIfBraces || IfBlockKind == IfStmtKind::IfElse;
2460     if (NeedsUnwrappedLine)
2461       addUnwrappedLine();
2462   }
2463 
2464   if (!Style.RemoveBracesLLVM)
2465     return nullptr;
2466 
2467   assert(!NestedTooDeep.empty());
2468   const bool KeepElseBraces =
2469       (ElseLeftBrace && !ElseLeftBrace->MatchingParen) || NestedTooDeep.back();
2470 
2471   NestedTooDeep.pop_back();
2472 
2473   if (!KeepBraces && !KeepIfBraces && !KeepElseBraces) {
2474     markOptionalBraces(IfLeftBrace);
2475     markOptionalBraces(ElseLeftBrace);
2476   } else if (IfLeftBrace) {
2477     FormatToken *IfRightBrace = IfLeftBrace->MatchingParen;
2478     if (IfRightBrace) {
2479       assert(IfRightBrace->MatchingParen == IfLeftBrace);
2480       assert(!IfLeftBrace->Optional);
2481       assert(!IfRightBrace->Optional);
2482       IfLeftBrace->MatchingParen = nullptr;
2483       IfRightBrace->MatchingParen = nullptr;
2484     }
2485   }
2486 
2487   if (IfKind)
2488     *IfKind = Kind;
2489 
2490   return IfLeftBrace;
2491 }
2492 
2493 void UnwrappedLineParser::parseTryCatch() {
2494   assert(FormatTok->isOneOf(tok::kw_try, tok::kw___try) && "'try' expected");
2495   nextToken();
2496   bool NeedsUnwrappedLine = false;
2497   if (FormatTok->is(tok::colon)) {
2498     // We are in a function try block, what comes is an initializer list.
2499     nextToken();
2500 
2501     // In case identifiers were removed by clang-tidy, what might follow is
2502     // multiple commas in sequence - before the first identifier.
2503     while (FormatTok->is(tok::comma))
2504       nextToken();
2505 
2506     while (FormatTok->is(tok::identifier)) {
2507       nextToken();
2508       if (FormatTok->is(tok::l_paren))
2509         parseParens();
2510       if (FormatTok->Previous && FormatTok->Previous->is(tok::identifier) &&
2511           FormatTok->is(tok::l_brace)) {
2512         do {
2513           nextToken();
2514         } while (!FormatTok->is(tok::r_brace));
2515         nextToken();
2516       }
2517 
2518       // In case identifiers were removed by clang-tidy, what might follow is
2519       // multiple commas in sequence - after the first identifier.
2520       while (FormatTok->is(tok::comma))
2521         nextToken();
2522     }
2523   }
2524   // Parse try with resource.
2525   if (Style.Language == FormatStyle::LK_Java && FormatTok->is(tok::l_paren))
2526     parseParens();
2527 
2528   keepAncestorBraces();
2529 
2530   if (FormatTok->is(tok::l_brace)) {
2531     CompoundStatementIndenter Indenter(this, Style, Line->Level);
2532     parseBlock();
2533     if (Style.BraceWrapping.BeforeCatch)
2534       addUnwrappedLine();
2535     else
2536       NeedsUnwrappedLine = true;
2537   } else if (!FormatTok->is(tok::kw_catch)) {
2538     // The C++ standard requires a compound-statement after a try.
2539     // If there's none, we try to assume there's a structuralElement
2540     // and try to continue.
2541     addUnwrappedLine();
2542     ++Line->Level;
2543     parseStructuralElement();
2544     --Line->Level;
2545   }
2546   while (true) {
2547     if (FormatTok->is(tok::at))
2548       nextToken();
2549     if (!(FormatTok->isOneOf(tok::kw_catch, Keywords.kw___except,
2550                              tok::kw___finally) ||
2551           ((Style.Language == FormatStyle::LK_Java || Style.isJavaScript()) &&
2552            FormatTok->is(Keywords.kw_finally)) ||
2553           (FormatTok->isObjCAtKeyword(tok::objc_catch) ||
2554            FormatTok->isObjCAtKeyword(tok::objc_finally))))
2555       break;
2556     nextToken();
2557     while (FormatTok->isNot(tok::l_brace)) {
2558       if (FormatTok->is(tok::l_paren)) {
2559         parseParens();
2560         continue;
2561       }
2562       if (FormatTok->isOneOf(tok::semi, tok::r_brace, tok::eof)) {
2563         if (Style.RemoveBracesLLVM)
2564           NestedTooDeep.pop_back();
2565         return;
2566       }
2567       nextToken();
2568     }
2569     NeedsUnwrappedLine = false;
2570     CompoundStatementIndenter Indenter(this, Style, Line->Level);
2571     parseBlock();
2572     if (Style.BraceWrapping.BeforeCatch)
2573       addUnwrappedLine();
2574     else
2575       NeedsUnwrappedLine = true;
2576   }
2577 
2578   if (Style.RemoveBracesLLVM)
2579     NestedTooDeep.pop_back();
2580 
2581   if (NeedsUnwrappedLine)
2582     addUnwrappedLine();
2583 }
2584 
2585 void UnwrappedLineParser::parseNamespace() {
2586   assert(FormatTok->isOneOf(tok::kw_namespace, TT_NamespaceMacro) &&
2587          "'namespace' expected");
2588 
2589   const FormatToken &InitialToken = *FormatTok;
2590   nextToken();
2591   if (InitialToken.is(TT_NamespaceMacro)) {
2592     parseParens();
2593   } else {
2594     while (FormatTok->isOneOf(tok::identifier, tok::coloncolon, tok::kw_inline,
2595                               tok::l_square, tok::period) ||
2596            (Style.isCSharp() && FormatTok->is(tok::kw_union)))
2597       if (FormatTok->is(tok::l_square))
2598         parseSquare();
2599       else
2600         nextToken();
2601   }
2602   if (FormatTok->is(tok::l_brace)) {
2603     if (ShouldBreakBeforeBrace(Style, InitialToken))
2604       addUnwrappedLine();
2605 
2606     unsigned AddLevels =
2607         Style.NamespaceIndentation == FormatStyle::NI_All ||
2608                 (Style.NamespaceIndentation == FormatStyle::NI_Inner &&
2609                  DeclarationScopeStack.size() > 1)
2610             ? 1u
2611             : 0u;
2612     bool ManageWhitesmithsBraces =
2613         AddLevels == 0u &&
2614         Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths;
2615 
2616     // If we're in Whitesmiths mode, indent the brace if we're not indenting
2617     // the whole block.
2618     if (ManageWhitesmithsBraces)
2619       ++Line->Level;
2620 
2621     parseBlock(/*MustBeDeclaration=*/true, AddLevels,
2622                /*MunchSemi=*/true,
2623                /*UnindentWhitesmithsBraces=*/ManageWhitesmithsBraces);
2624 
2625     // Munch the semicolon after a namespace. This is more common than one would
2626     // think. Putting the semicolon into its own line is very ugly.
2627     if (FormatTok->is(tok::semi))
2628       nextToken();
2629 
2630     addUnwrappedLine(AddLevels > 0 ? LineLevel::Remove : LineLevel::Keep);
2631 
2632     if (ManageWhitesmithsBraces)
2633       --Line->Level;
2634   }
2635   // FIXME: Add error handling.
2636 }
2637 
2638 void UnwrappedLineParser::parseNew() {
2639   assert(FormatTok->is(tok::kw_new) && "'new' expected");
2640   nextToken();
2641 
2642   if (Style.isCSharp()) {
2643     do {
2644       if (FormatTok->is(tok::l_brace))
2645         parseBracedList();
2646 
2647       if (FormatTok->isOneOf(tok::semi, tok::comma))
2648         return;
2649 
2650       nextToken();
2651     } while (!eof());
2652   }
2653 
2654   if (Style.Language != FormatStyle::LK_Java)
2655     return;
2656 
2657   // In Java, we can parse everything up to the parens, which aren't optional.
2658   do {
2659     // There should not be a ;, { or } before the new's open paren.
2660     if (FormatTok->isOneOf(tok::semi, tok::l_brace, tok::r_brace))
2661       return;
2662 
2663     // Consume the parens.
2664     if (FormatTok->is(tok::l_paren)) {
2665       parseParens();
2666 
2667       // If there is a class body of an anonymous class, consume that as child.
2668       if (FormatTok->is(tok::l_brace))
2669         parseChildBlock();
2670       return;
2671     }
2672     nextToken();
2673   } while (!eof());
2674 }
2675 
2676 void UnwrappedLineParser::parseForOrWhileLoop() {
2677   assert(FormatTok->isOneOf(tok::kw_for, tok::kw_while, TT_ForEachMacro) &&
2678          "'for', 'while' or foreach macro expected");
2679   nextToken();
2680   // JS' for await ( ...
2681   if (Style.isJavaScript() && FormatTok->is(Keywords.kw_await))
2682     nextToken();
2683   if (Style.isCpp() && FormatTok->is(tok::kw_co_await))
2684     nextToken();
2685   if (FormatTok->is(tok::l_paren))
2686     parseParens();
2687 
2688   keepAncestorBraces();
2689 
2690   if (FormatTok->is(tok::l_brace)) {
2691     FormatToken *LeftBrace = FormatTok;
2692     CompoundStatementIndenter Indenter(this, Style, Line->Level);
2693     parseBlock();
2694     if (Style.RemoveBracesLLVM) {
2695       assert(!NestedTooDeep.empty());
2696       if (!NestedTooDeep.back())
2697         markOptionalBraces(LeftBrace);
2698     }
2699     addUnwrappedLine();
2700   } else {
2701     parseUnbracedBody();
2702   }
2703 
2704   if (Style.RemoveBracesLLVM)
2705     NestedTooDeep.pop_back();
2706 }
2707 
2708 void UnwrappedLineParser::parseDoWhile() {
2709   assert(FormatTok->is(tok::kw_do) && "'do' expected");
2710   nextToken();
2711 
2712   keepAncestorBraces();
2713 
2714   if (FormatTok->is(tok::l_brace)) {
2715     CompoundStatementIndenter Indenter(this, Style, Line->Level);
2716     parseBlock();
2717     if (Style.BraceWrapping.BeforeWhile)
2718       addUnwrappedLine();
2719   } else {
2720     parseUnbracedBody();
2721   }
2722 
2723   if (Style.RemoveBracesLLVM)
2724     NestedTooDeep.pop_back();
2725 
2726   // FIXME: Add error handling.
2727   if (!FormatTok->is(tok::kw_while)) {
2728     addUnwrappedLine();
2729     return;
2730   }
2731 
2732   // If in Whitesmiths mode, the line with the while() needs to be indented
2733   // to the same level as the block.
2734   if (Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths)
2735     ++Line->Level;
2736 
2737   nextToken();
2738   parseStructuralElement();
2739 }
2740 
2741 void UnwrappedLineParser::parseLabel(bool LeftAlignLabel) {
2742   nextToken();
2743   unsigned OldLineLevel = Line->Level;
2744   if (Line->Level > 1 || (!Line->InPPDirective && Line->Level > 0))
2745     --Line->Level;
2746   if (LeftAlignLabel)
2747     Line->Level = 0;
2748 
2749   if (!Style.IndentCaseBlocks && CommentsBeforeNextToken.empty() &&
2750       FormatTok->is(tok::l_brace)) {
2751 
2752     CompoundStatementIndenter Indenter(this, Line->Level,
2753                                        Style.BraceWrapping.AfterCaseLabel,
2754                                        Style.BraceWrapping.IndentBraces);
2755     parseBlock();
2756     if (FormatTok->is(tok::kw_break)) {
2757       if (Style.BraceWrapping.AfterControlStatement ==
2758           FormatStyle::BWACS_Always) {
2759         addUnwrappedLine();
2760         if (!Style.IndentCaseBlocks &&
2761             Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths)
2762           ++Line->Level;
2763       }
2764       parseStructuralElement();
2765     }
2766     addUnwrappedLine();
2767   } else {
2768     if (FormatTok->is(tok::semi))
2769       nextToken();
2770     addUnwrappedLine();
2771   }
2772   Line->Level = OldLineLevel;
2773   if (FormatTok->isNot(tok::l_brace)) {
2774     parseStructuralElement();
2775     addUnwrappedLine();
2776   }
2777 }
2778 
2779 void UnwrappedLineParser::parseCaseLabel() {
2780   assert(FormatTok->is(tok::kw_case) && "'case' expected");
2781 
2782   // FIXME: fix handling of complex expressions here.
2783   do {
2784     nextToken();
2785   } while (!eof() && !FormatTok->is(tok::colon));
2786   parseLabel();
2787 }
2788 
2789 void UnwrappedLineParser::parseSwitch() {
2790   assert(FormatTok->is(tok::kw_switch) && "'switch' expected");
2791   nextToken();
2792   if (FormatTok->is(tok::l_paren))
2793     parseParens();
2794 
2795   keepAncestorBraces();
2796 
2797   if (FormatTok->is(tok::l_brace)) {
2798     CompoundStatementIndenter Indenter(this, Style, Line->Level);
2799     parseBlock();
2800     addUnwrappedLine();
2801   } else {
2802     addUnwrappedLine();
2803     ++Line->Level;
2804     parseStructuralElement();
2805     --Line->Level;
2806   }
2807 
2808   if (Style.RemoveBracesLLVM)
2809     NestedTooDeep.pop_back();
2810 }
2811 
2812 void UnwrappedLineParser::parseAccessSpecifier() {
2813   FormatToken *AccessSpecifierCandidate = FormatTok;
2814   nextToken();
2815   // Understand Qt's slots.
2816   if (FormatTok->isOneOf(Keywords.kw_slots, Keywords.kw_qslots))
2817     nextToken();
2818   // Otherwise, we don't know what it is, and we'd better keep the next token.
2819   if (FormatTok->is(tok::colon)) {
2820     nextToken();
2821     addUnwrappedLine();
2822   } else if (!FormatTok->is(tok::coloncolon) &&
2823              !std::binary_search(COperatorsFollowingVar.begin(),
2824                                  COperatorsFollowingVar.end(),
2825                                  FormatTok->Tok.getKind())) {
2826     // Not a variable name nor namespace name.
2827     addUnwrappedLine();
2828   } else if (AccessSpecifierCandidate) {
2829     // Consider the access specifier to be a C identifier.
2830     AccessSpecifierCandidate->Tok.setKind(tok::identifier);
2831   }
2832 }
2833 
2834 /// \brief Parses a concept definition.
2835 /// \pre The current token has to be the concept keyword.
2836 ///
2837 /// Returns if either the concept has been completely parsed, or if it detects
2838 /// that the concept definition is incorrect.
2839 void UnwrappedLineParser::parseConcept() {
2840   assert(FormatTok->is(tok::kw_concept) && "'concept' expected");
2841   nextToken();
2842   if (!FormatTok->is(tok::identifier))
2843     return;
2844   nextToken();
2845   if (!FormatTok->is(tok::equal))
2846     return;
2847   nextToken();
2848   parseConstraintExpression();
2849   if (FormatTok->is(tok::semi))
2850     nextToken();
2851   addUnwrappedLine();
2852 }
2853 
2854 /// \brief Parses a requires, decides if it is a clause or an expression.
2855 /// \pre The current token has to be the requires keyword.
2856 /// \returns true if it parsed a clause.
2857 bool clang::format::UnwrappedLineParser::parseRequires() {
2858   assert(FormatTok->is(tok::kw_requires) && "'requires' expected");
2859   auto RequiresToken = FormatTok;
2860 
2861   // We try to guess if it is a requires clause, or a requires expression. For
2862   // that we first consume the keyword and check the next token.
2863   nextToken();
2864 
2865   switch (FormatTok->Tok.getKind()) {
2866   case tok::l_brace:
2867     // This can only be an expression, never a clause.
2868     parseRequiresExpression(RequiresToken);
2869     return false;
2870   case tok::l_paren:
2871     // Clauses and expression can start with a paren, it's unclear what we have.
2872     break;
2873   default:
2874     // All other tokens can only be a clause.
2875     parseRequiresClause(RequiresToken);
2876     return true;
2877   }
2878 
2879   // Looking forward we would have to decide if there are function declaration
2880   // like arguments to the requires expression:
2881   // requires (T t) {
2882   // Or there is a constraint expression for the requires clause:
2883   // requires (C<T> && ...
2884 
2885   // But first let's look behind.
2886   auto *PreviousNonComment = RequiresToken->getPreviousNonComment();
2887 
2888   if (!PreviousNonComment ||
2889       PreviousNonComment->is(TT_RequiresExpressionLBrace)) {
2890     // If there is no token, or an expression left brace, we are a requires
2891     // clause within a requires expression.
2892     parseRequiresClause(RequiresToken);
2893     return true;
2894   }
2895 
2896   switch (PreviousNonComment->Tok.getKind()) {
2897   case tok::greater:
2898   case tok::r_paren:
2899   case tok::kw_noexcept:
2900   case tok::kw_const:
2901     // This is a requires clause.
2902     parseRequiresClause(RequiresToken);
2903     return true;
2904   case tok::amp:
2905   case tok::ampamp: {
2906     // This can be either:
2907     // if (... && requires (T t) ...)
2908     // Or
2909     // void member(...) && requires (C<T> ...
2910     // We check the one token before that for a const:
2911     // void member(...) const && requires (C<T> ...
2912     auto PrevPrev = PreviousNonComment->getPreviousNonComment();
2913     if (PrevPrev && PrevPrev->is(tok::kw_const)) {
2914       parseRequiresClause(RequiresToken);
2915       return true;
2916     }
2917     break;
2918   }
2919   default:
2920     // It's an expression.
2921     parseRequiresExpression(RequiresToken);
2922     return false;
2923   }
2924 
2925   // Now we look forward and try to check if the paren content is a parameter
2926   // list. The parameters can be cv-qualified and contain references or
2927   // pointers.
2928   // So we want basically to check for TYPE NAME, but TYPE can contain all kinds
2929   // of stuff: typename, const, *, &, &&, ::, identifiers.
2930 
2931   int NextTokenOffset = 1;
2932   auto NextToken = Tokens->peekNextToken(NextTokenOffset);
2933   auto PeekNext = [&NextTokenOffset, &NextToken, this] {
2934     ++NextTokenOffset;
2935     NextToken = Tokens->peekNextToken(NextTokenOffset);
2936   };
2937 
2938   bool FoundType = false;
2939   bool LastWasColonColon = false;
2940   int OpenAngles = 0;
2941 
2942   for (; NextTokenOffset < 50; PeekNext()) {
2943     switch (NextToken->Tok.getKind()) {
2944     case tok::kw_volatile:
2945     case tok::kw_const:
2946     case tok::comma:
2947       parseRequiresExpression(RequiresToken);
2948       return false;
2949     case tok::r_paren:
2950     case tok::pipepipe:
2951       parseRequiresClause(RequiresToken);
2952       return true;
2953     case tok::eof:
2954       // Break out of the loop.
2955       NextTokenOffset = 50;
2956       break;
2957     case tok::coloncolon:
2958       LastWasColonColon = true;
2959       break;
2960     case tok::identifier:
2961       if (FoundType && !LastWasColonColon && OpenAngles == 0) {
2962         parseRequiresExpression(RequiresToken);
2963         return false;
2964       }
2965       FoundType = true;
2966       LastWasColonColon = false;
2967       break;
2968     case tok::less:
2969       ++OpenAngles;
2970       break;
2971     case tok::greater:
2972       --OpenAngles;
2973       break;
2974     default:
2975       if (NextToken->isSimpleTypeSpecifier()) {
2976         parseRequiresExpression(RequiresToken);
2977         return false;
2978       }
2979       break;
2980     }
2981   }
2982 
2983   // This seems to be a complicated expression, just assume it's a clause.
2984   parseRequiresClause(RequiresToken);
2985   return true;
2986 }
2987 
2988 /// \brief Parses a requires clause.
2989 /// \param RequiresToken The requires keyword token, which starts this clause.
2990 /// \pre We need to be on the next token after the requires keyword.
2991 /// \sa parseRequiresExpression
2992 ///
2993 /// Returns if it either has finished parsing the clause, or it detects, that
2994 /// the clause is incorrect.
2995 void UnwrappedLineParser::parseRequiresClause(FormatToken *RequiresToken) {
2996   assert(FormatTok->getPreviousNonComment() == RequiresToken);
2997   assert(RequiresToken->is(tok::kw_requires) && "'requires' expected");
2998   assert(RequiresToken->getType() == TT_Unknown);
2999 
3000   // If there is no previous token, we are within a requires expression,
3001   // otherwise we will always have the template or function declaration in front
3002   // of it.
3003   bool InRequiresExpression =
3004       !RequiresToken->Previous ||
3005       RequiresToken->Previous->is(TT_RequiresExpressionLBrace);
3006 
3007   RequiresToken->setType(InRequiresExpression
3008                              ? TT_RequiresClauseInARequiresExpression
3009                              : TT_RequiresClause);
3010 
3011   parseConstraintExpression();
3012 
3013   if (!InRequiresExpression)
3014     FormatTok->Previous->ClosesRequiresClause = true;
3015 }
3016 
3017 /// \brief Parses a requires expression.
3018 /// \param RequiresToken The requires keyword token, which starts this clause.
3019 /// \pre We need to be on the next token after the requires keyword.
3020 /// \sa parseRequiresClause
3021 ///
3022 /// Returns if it either has finished parsing the expression, or it detects,
3023 /// that the expression is incorrect.
3024 void UnwrappedLineParser::parseRequiresExpression(FormatToken *RequiresToken) {
3025   assert(FormatTok->getPreviousNonComment() == RequiresToken);
3026   assert(RequiresToken->is(tok::kw_requires) && "'requires' expected");
3027   assert(RequiresToken->getType() == TT_Unknown);
3028 
3029   RequiresToken->setType(TT_RequiresExpression);
3030 
3031   if (FormatTok->is(tok::l_paren)) {
3032     FormatTok->setType(TT_RequiresExpressionLParen);
3033     parseParens();
3034   }
3035 
3036   if (FormatTok->is(tok::l_brace)) {
3037     FormatTok->setType(TT_RequiresExpressionLBrace);
3038     parseChildBlock(/*CanContainBracedList=*/false,
3039                     /*NextLBracesType=*/TT_CompoundRequirementLBrace);
3040   }
3041 }
3042 
3043 /// \brief Parses a constraint expression.
3044 ///
3045 /// This is either the definition of a concept, or the body of a requires
3046 /// clause. It returns, when the parsing is complete, or the expression is
3047 /// incorrect.
3048 void UnwrappedLineParser::parseConstraintExpression() {
3049   // The special handling for lambdas is needed since tryToParseLambda() eats a
3050   // token and if a requires expression is the last part of a requires clause
3051   // and followed by an attribute like [[nodiscard]] the ClosesRequiresClause is
3052   // not set on the correct token. Thus we need to be aware if we even expect a
3053   // lambda to be possible.
3054   // template <typename T> requires requires { ... } [[nodiscard]] ...;
3055   bool LambdaNextTimeAllowed = true;
3056   do {
3057     bool LambdaThisTimeAllowed = std::exchange(LambdaNextTimeAllowed, false);
3058 
3059     switch (FormatTok->Tok.getKind()) {
3060     case tok::kw_requires: {
3061       auto RequiresToken = FormatTok;
3062       nextToken();
3063       parseRequiresExpression(RequiresToken);
3064       break;
3065     }
3066 
3067     case tok::l_paren:
3068       parseParens(/*AmpAmpTokenType=*/TT_BinaryOperator);
3069       break;
3070 
3071     case tok::l_square:
3072       if (!LambdaThisTimeAllowed || !tryToParseLambda())
3073         return;
3074       break;
3075 
3076     case tok::identifier:
3077       // We need to differentiate identifiers for a template deduction guide,
3078       // variables, or function return types (the constraint expression has
3079       // ended before that), and basically all other cases. But it's easier to
3080       // check the other way around.
3081       assert(FormatTok->Previous);
3082       switch (FormatTok->Previous->Tok.getKind()) {
3083       case tok::coloncolon:  // Nested identifier.
3084       case tok::ampamp:      // Start of a function or variable for the
3085       case tok::pipepipe:    // constraint expression.
3086       case tok::kw_requires: // Initial identifier of a requires clause.
3087       case tok::equal:       // Initial identifier of a concept declaration.
3088         break;
3089       default:
3090         return;
3091       }
3092 
3093       // Read identifier with optional template declaration.
3094       nextToken();
3095       if (FormatTok->is(tok::less))
3096         parseBracedList(/*ContinueOnSemicolons=*/false, /*IsEnum=*/false,
3097                         /*ClosingBraceKind=*/tok::greater);
3098       break;
3099 
3100     case tok::kw_const:
3101     case tok::semi:
3102     case tok::kw_class:
3103     case tok::kw_struct:
3104     case tok::kw_union:
3105       return;
3106 
3107     case tok::l_brace:
3108       // Potential function body.
3109       return;
3110 
3111     case tok::ampamp:
3112     case tok::pipepipe:
3113       FormatTok->setType(TT_BinaryOperator);
3114       nextToken();
3115       LambdaNextTimeAllowed = true;
3116       break;
3117 
3118     case tok::comma:
3119     case tok::comment:
3120       LambdaNextTimeAllowed = LambdaThisTimeAllowed;
3121       nextToken();
3122       break;
3123 
3124     case tok::kw_sizeof:
3125     case tok::greater:
3126     case tok::greaterequal:
3127     case tok::greatergreater:
3128     case tok::less:
3129     case tok::lessequal:
3130     case tok::lessless:
3131     case tok::equalequal:
3132     case tok::exclaim:
3133     case tok::exclaimequal:
3134     case tok::plus:
3135     case tok::minus:
3136     case tok::star:
3137     case tok::slash:
3138     case tok::kw_decltype:
3139       LambdaNextTimeAllowed = true;
3140       // Just eat them.
3141       nextToken();
3142       break;
3143 
3144     case tok::numeric_constant:
3145     case tok::coloncolon:
3146     case tok::kw_true:
3147     case tok::kw_false:
3148       // Just eat them.
3149       nextToken();
3150       break;
3151 
3152     case tok::kw_static_cast:
3153     case tok::kw_const_cast:
3154     case tok::kw_reinterpret_cast:
3155     case tok::kw_dynamic_cast:
3156       nextToken();
3157       if (!FormatTok->is(tok::less))
3158         return;
3159 
3160       parseBracedList(/*ContinueOnSemicolons=*/false, /*IsEnum=*/false,
3161                       /*ClosingBraceKind=*/tok::greater);
3162       break;
3163 
3164     case tok::kw_bool:
3165       // bool is only allowed if it is directly followed by a paren for a cast:
3166       // concept C = bool(...);
3167       // and bool is the only type, all other types as cast must be inside a
3168       // cast to bool an thus are handled by the other cases.
3169       nextToken();
3170       if (FormatTok->isNot(tok::l_paren))
3171         return;
3172       parseParens();
3173       break;
3174 
3175     default:
3176       return;
3177     }
3178   } while (!eof());
3179 }
3180 
3181 bool UnwrappedLineParser::parseEnum() {
3182   const FormatToken &InitialToken = *FormatTok;
3183 
3184   // Won't be 'enum' for NS_ENUMs.
3185   if (FormatTok->is(tok::kw_enum))
3186     nextToken();
3187 
3188   // In TypeScript, "enum" can also be used as property name, e.g. in interface
3189   // declarations. An "enum" keyword followed by a colon would be a syntax
3190   // error and thus assume it is just an identifier.
3191   if (Style.isJavaScript() && FormatTok->isOneOf(tok::colon, tok::question))
3192     return false;
3193 
3194   // In protobuf, "enum" can be used as a field name.
3195   if (Style.Language == FormatStyle::LK_Proto && FormatTok->is(tok::equal))
3196     return false;
3197 
3198   // Eat up enum class ...
3199   if (FormatTok->isOneOf(tok::kw_class, tok::kw_struct))
3200     nextToken();
3201 
3202   while (FormatTok->Tok.getIdentifierInfo() ||
3203          FormatTok->isOneOf(tok::colon, tok::coloncolon, tok::less,
3204                             tok::greater, tok::comma, tok::question)) {
3205     nextToken();
3206     // We can have macros or attributes in between 'enum' and the enum name.
3207     if (FormatTok->is(tok::l_paren))
3208       parseParens();
3209     if (FormatTok->is(tok::identifier)) {
3210       nextToken();
3211       // If there are two identifiers in a row, this is likely an elaborate
3212       // return type. In Java, this can be "implements", etc.
3213       if (Style.isCpp() && FormatTok->is(tok::identifier))
3214         return false;
3215     }
3216   }
3217 
3218   // Just a declaration or something is wrong.
3219   if (FormatTok->isNot(tok::l_brace))
3220     return true;
3221   FormatTok->setType(TT_EnumLBrace);
3222   FormatTok->setBlockKind(BK_Block);
3223 
3224   if (Style.Language == FormatStyle::LK_Java) {
3225     // Java enums are different.
3226     parseJavaEnumBody();
3227     return true;
3228   }
3229   if (Style.Language == FormatStyle::LK_Proto) {
3230     parseBlock(/*MustBeDeclaration=*/true);
3231     return true;
3232   }
3233 
3234   if (!Style.AllowShortEnumsOnASingleLine &&
3235       ShouldBreakBeforeBrace(Style, InitialToken))
3236     addUnwrappedLine();
3237   // Parse enum body.
3238   nextToken();
3239   if (!Style.AllowShortEnumsOnASingleLine) {
3240     addUnwrappedLine();
3241     Line->Level += 1;
3242   }
3243   bool HasError = !parseBracedList(/*ContinueOnSemicolons=*/true,
3244                                    /*IsEnum=*/true);
3245   if (!Style.AllowShortEnumsOnASingleLine)
3246     Line->Level -= 1;
3247   if (HasError) {
3248     if (FormatTok->is(tok::semi))
3249       nextToken();
3250     addUnwrappedLine();
3251   }
3252   return true;
3253 
3254   // There is no addUnwrappedLine() here so that we fall through to parsing a
3255   // structural element afterwards. Thus, in "enum A {} n, m;",
3256   // "} n, m;" will end up in one unwrapped line.
3257 }
3258 
3259 bool UnwrappedLineParser::parseStructLike() {
3260   // parseRecord falls through and does not yet add an unwrapped line as a
3261   // record declaration or definition can start a structural element.
3262   parseRecord();
3263   // This does not apply to Java, JavaScript and C#.
3264   if (Style.Language == FormatStyle::LK_Java || Style.isJavaScript() ||
3265       Style.isCSharp()) {
3266     if (FormatTok->is(tok::semi))
3267       nextToken();
3268     addUnwrappedLine();
3269     return true;
3270   }
3271   return false;
3272 }
3273 
3274 namespace {
3275 // A class used to set and restore the Token position when peeking
3276 // ahead in the token source.
3277 class ScopedTokenPosition {
3278   unsigned StoredPosition;
3279   FormatTokenSource *Tokens;
3280 
3281 public:
3282   ScopedTokenPosition(FormatTokenSource *Tokens) : Tokens(Tokens) {
3283     assert(Tokens && "Tokens expected to not be null");
3284     StoredPosition = Tokens->getPosition();
3285   }
3286 
3287   ~ScopedTokenPosition() { Tokens->setPosition(StoredPosition); }
3288 };
3289 } // namespace
3290 
3291 // Look to see if we have [[ by looking ahead, if
3292 // its not then rewind to the original position.
3293 bool UnwrappedLineParser::tryToParseSimpleAttribute() {
3294   ScopedTokenPosition AutoPosition(Tokens);
3295   FormatToken *Tok = Tokens->getNextToken();
3296   // We already read the first [ check for the second.
3297   if (!Tok->is(tok::l_square))
3298     return false;
3299   // Double check that the attribute is just something
3300   // fairly simple.
3301   while (Tok->isNot(tok::eof)) {
3302     if (Tok->is(tok::r_square))
3303       break;
3304     Tok = Tokens->getNextToken();
3305   }
3306   if (Tok->is(tok::eof))
3307     return false;
3308   Tok = Tokens->getNextToken();
3309   if (!Tok->is(tok::r_square))
3310     return false;
3311   Tok = Tokens->getNextToken();
3312   if (Tok->is(tok::semi))
3313     return false;
3314   return true;
3315 }
3316 
3317 void UnwrappedLineParser::parseJavaEnumBody() {
3318   // Determine whether the enum is simple, i.e. does not have a semicolon or
3319   // constants with class bodies. Simple enums can be formatted like braced
3320   // lists, contracted to a single line, etc.
3321   unsigned StoredPosition = Tokens->getPosition();
3322   bool IsSimple = true;
3323   FormatToken *Tok = Tokens->getNextToken();
3324   while (!Tok->is(tok::eof)) {
3325     if (Tok->is(tok::r_brace))
3326       break;
3327     if (Tok->isOneOf(tok::l_brace, tok::semi)) {
3328       IsSimple = false;
3329       break;
3330     }
3331     // FIXME: This will also mark enums with braces in the arguments to enum
3332     // constants as "not simple". This is probably fine in practice, though.
3333     Tok = Tokens->getNextToken();
3334   }
3335   FormatTok = Tokens->setPosition(StoredPosition);
3336 
3337   if (IsSimple) {
3338     nextToken();
3339     parseBracedList();
3340     addUnwrappedLine();
3341     return;
3342   }
3343 
3344   // Parse the body of a more complex enum.
3345   // First add a line for everything up to the "{".
3346   nextToken();
3347   addUnwrappedLine();
3348   ++Line->Level;
3349 
3350   // Parse the enum constants.
3351   while (FormatTok) {
3352     if (FormatTok->is(tok::l_brace)) {
3353       // Parse the constant's class body.
3354       parseBlock(/*MustBeDeclaration=*/true, /*AddLevels=*/1u,
3355                  /*MunchSemi=*/false);
3356     } else if (FormatTok->is(tok::l_paren)) {
3357       parseParens();
3358     } else if (FormatTok->is(tok::comma)) {
3359       nextToken();
3360       addUnwrappedLine();
3361     } else if (FormatTok->is(tok::semi)) {
3362       nextToken();
3363       addUnwrappedLine();
3364       break;
3365     } else if (FormatTok->is(tok::r_brace)) {
3366       addUnwrappedLine();
3367       break;
3368     } else {
3369       nextToken();
3370     }
3371   }
3372 
3373   // Parse the class body after the enum's ";" if any.
3374   parseLevel(/*HasOpeningBrace=*/true, /*CanContainBracedList=*/true);
3375   nextToken();
3376   --Line->Level;
3377   addUnwrappedLine();
3378 }
3379 
3380 void UnwrappedLineParser::parseRecord(bool ParseAsExpr) {
3381   const FormatToken &InitialToken = *FormatTok;
3382   nextToken();
3383 
3384   // The actual identifier can be a nested name specifier, and in macros
3385   // it is often token-pasted.
3386   // An [[attribute]] can be before the identifier.
3387   while (FormatTok->isOneOf(tok::identifier, tok::coloncolon, tok::hashhash,
3388                             tok::kw___attribute, tok::kw___declspec,
3389                             tok::kw_alignas, tok::l_square, tok::r_square) ||
3390          ((Style.Language == FormatStyle::LK_Java || Style.isJavaScript()) &&
3391           FormatTok->isOneOf(tok::period, tok::comma))) {
3392     if (Style.isJavaScript() &&
3393         FormatTok->isOneOf(Keywords.kw_extends, Keywords.kw_implements)) {
3394       // JavaScript/TypeScript supports inline object types in
3395       // extends/implements positions:
3396       //     class Foo implements {bar: number} { }
3397       nextToken();
3398       if (FormatTok->is(tok::l_brace)) {
3399         tryToParseBracedList();
3400         continue;
3401       }
3402     }
3403     bool IsNonMacroIdentifier =
3404         FormatTok->is(tok::identifier) &&
3405         FormatTok->TokenText != FormatTok->TokenText.upper();
3406     nextToken();
3407     // We can have macros or attributes in between 'class' and the class name.
3408     if (!IsNonMacroIdentifier) {
3409       if (FormatTok->is(tok::l_paren)) {
3410         parseParens();
3411       } else if (FormatTok->is(TT_AttributeSquare)) {
3412         parseSquare();
3413         // Consume the closing TT_AttributeSquare.
3414         if (FormatTok->Next && FormatTok->is(TT_AttributeSquare))
3415           nextToken();
3416       }
3417     }
3418   }
3419 
3420   // Note that parsing away template declarations here leads to incorrectly
3421   // accepting function declarations as record declarations.
3422   // In general, we cannot solve this problem. Consider:
3423   // class A<int> B() {}
3424   // which can be a function definition or a class definition when B() is a
3425   // macro. If we find enough real-world cases where this is a problem, we
3426   // can parse for the 'template' keyword in the beginning of the statement,
3427   // and thus rule out the record production in case there is no template
3428   // (this would still leave us with an ambiguity between template function
3429   // and class declarations).
3430   if (FormatTok->isOneOf(tok::colon, tok::less)) {
3431     while (!eof()) {
3432       if (FormatTok->is(tok::l_brace)) {
3433         calculateBraceTypes(/*ExpectClassBody=*/true);
3434         if (!tryToParseBracedList())
3435           break;
3436       }
3437       if (FormatTok->is(tok::l_square)) {
3438         FormatToken *Previous = FormatTok->Previous;
3439         if (!Previous ||
3440             !(Previous->is(tok::r_paren) || Previous->isTypeOrIdentifier())) {
3441           // Don't try parsing a lambda if we had a closing parenthesis before,
3442           // it was probably a pointer to an array: int (*)[].
3443           if (!tryToParseLambda())
3444             break;
3445         }
3446       }
3447       if (FormatTok->is(tok::semi))
3448         return;
3449       if (Style.isCSharp() && FormatTok->is(Keywords.kw_where)) {
3450         addUnwrappedLine();
3451         nextToken();
3452         parseCSharpGenericTypeConstraint();
3453         break;
3454       }
3455       nextToken();
3456     }
3457   }
3458 
3459   auto GetBraceType = [](const FormatToken &RecordTok) {
3460     switch (RecordTok.Tok.getKind()) {
3461     case tok::kw_class:
3462       return TT_ClassLBrace;
3463     case tok::kw_struct:
3464       return TT_StructLBrace;
3465     case tok::kw_union:
3466       return TT_UnionLBrace;
3467     default:
3468       // Useful for e.g. interface.
3469       return TT_RecordLBrace;
3470     }
3471   };
3472   if (FormatTok->is(tok::l_brace)) {
3473     FormatTok->setType(GetBraceType(InitialToken));
3474     if (ParseAsExpr) {
3475       parseChildBlock();
3476     } else {
3477       if (ShouldBreakBeforeBrace(Style, InitialToken))
3478         addUnwrappedLine();
3479 
3480       unsigned AddLevels = Style.IndentAccessModifiers ? 2u : 1u;
3481       parseBlock(/*MustBeDeclaration=*/true, AddLevels, /*MunchSemi=*/false);
3482     }
3483   }
3484   // There is no addUnwrappedLine() here so that we fall through to parsing a
3485   // structural element afterwards. Thus, in "class A {} n, m;",
3486   // "} n, m;" will end up in one unwrapped line.
3487 }
3488 
3489 void UnwrappedLineParser::parseObjCMethod() {
3490   assert(FormatTok->isOneOf(tok::l_paren, tok::identifier) &&
3491          "'(' or identifier expected.");
3492   do {
3493     if (FormatTok->is(tok::semi)) {
3494       nextToken();
3495       addUnwrappedLine();
3496       return;
3497     } else if (FormatTok->is(tok::l_brace)) {
3498       if (Style.BraceWrapping.AfterFunction)
3499         addUnwrappedLine();
3500       parseBlock();
3501       addUnwrappedLine();
3502       return;
3503     } else {
3504       nextToken();
3505     }
3506   } while (!eof());
3507 }
3508 
3509 void UnwrappedLineParser::parseObjCProtocolList() {
3510   assert(FormatTok->is(tok::less) && "'<' expected.");
3511   do {
3512     nextToken();
3513     // Early exit in case someone forgot a close angle.
3514     if (FormatTok->isOneOf(tok::semi, tok::l_brace) ||
3515         FormatTok->isObjCAtKeyword(tok::objc_end))
3516       return;
3517   } while (!eof() && FormatTok->isNot(tok::greater));
3518   nextToken(); // Skip '>'.
3519 }
3520 
3521 void UnwrappedLineParser::parseObjCUntilAtEnd() {
3522   do {
3523     if (FormatTok->isObjCAtKeyword(tok::objc_end)) {
3524       nextToken();
3525       addUnwrappedLine();
3526       break;
3527     }
3528     if (FormatTok->is(tok::l_brace)) {
3529       parseBlock();
3530       // In ObjC interfaces, nothing should be following the "}".
3531       addUnwrappedLine();
3532     } else if (FormatTok->is(tok::r_brace)) {
3533       // Ignore stray "}". parseStructuralElement doesn't consume them.
3534       nextToken();
3535       addUnwrappedLine();
3536     } else if (FormatTok->isOneOf(tok::minus, tok::plus)) {
3537       nextToken();
3538       parseObjCMethod();
3539     } else {
3540       parseStructuralElement();
3541     }
3542   } while (!eof());
3543 }
3544 
3545 void UnwrappedLineParser::parseObjCInterfaceOrImplementation() {
3546   assert(FormatTok->Tok.getObjCKeywordID() == tok::objc_interface ||
3547          FormatTok->Tok.getObjCKeywordID() == tok::objc_implementation);
3548   nextToken();
3549   nextToken(); // interface name
3550 
3551   // @interface can be followed by a lightweight generic
3552   // specialization list, then either a base class or a category.
3553   if (FormatTok->is(tok::less))
3554     parseObjCLightweightGenerics();
3555   if (FormatTok->is(tok::colon)) {
3556     nextToken();
3557     nextToken(); // base class name
3558     // The base class can also have lightweight generics applied to it.
3559     if (FormatTok->is(tok::less))
3560       parseObjCLightweightGenerics();
3561   } else if (FormatTok->is(tok::l_paren))
3562     // Skip category, if present.
3563     parseParens();
3564 
3565   if (FormatTok->is(tok::less))
3566     parseObjCProtocolList();
3567 
3568   if (FormatTok->is(tok::l_brace)) {
3569     if (Style.BraceWrapping.AfterObjCDeclaration)
3570       addUnwrappedLine();
3571     parseBlock(/*MustBeDeclaration=*/true);
3572   }
3573 
3574   // With instance variables, this puts '}' on its own line.  Without instance
3575   // variables, this ends the @interface line.
3576   addUnwrappedLine();
3577 
3578   parseObjCUntilAtEnd();
3579 }
3580 
3581 void UnwrappedLineParser::parseObjCLightweightGenerics() {
3582   assert(FormatTok->is(tok::less));
3583   // Unlike protocol lists, generic parameterizations support
3584   // nested angles:
3585   //
3586   // @interface Foo<ValueType : id <NSCopying, NSSecureCoding>> :
3587   //     NSObject <NSCopying, NSSecureCoding>
3588   //
3589   // so we need to count how many open angles we have left.
3590   unsigned NumOpenAngles = 1;
3591   do {
3592     nextToken();
3593     // Early exit in case someone forgot a close angle.
3594     if (FormatTok->isOneOf(tok::semi, tok::l_brace) ||
3595         FormatTok->isObjCAtKeyword(tok::objc_end))
3596       break;
3597     if (FormatTok->is(tok::less))
3598       ++NumOpenAngles;
3599     else if (FormatTok->is(tok::greater)) {
3600       assert(NumOpenAngles > 0 && "'>' makes NumOpenAngles negative");
3601       --NumOpenAngles;
3602     }
3603   } while (!eof() && NumOpenAngles != 0);
3604   nextToken(); // Skip '>'.
3605 }
3606 
3607 // Returns true for the declaration/definition form of @protocol,
3608 // false for the expression form.
3609 bool UnwrappedLineParser::parseObjCProtocol() {
3610   assert(FormatTok->Tok.getObjCKeywordID() == tok::objc_protocol);
3611   nextToken();
3612 
3613   if (FormatTok->is(tok::l_paren))
3614     // The expression form of @protocol, e.g. "Protocol* p = @protocol(foo);".
3615     return false;
3616 
3617   // The definition/declaration form,
3618   // @protocol Foo
3619   // - (int)someMethod;
3620   // @end
3621 
3622   nextToken(); // protocol name
3623 
3624   if (FormatTok->is(tok::less))
3625     parseObjCProtocolList();
3626 
3627   // Check for protocol declaration.
3628   if (FormatTok->is(tok::semi)) {
3629     nextToken();
3630     addUnwrappedLine();
3631     return true;
3632   }
3633 
3634   addUnwrappedLine();
3635   parseObjCUntilAtEnd();
3636   return true;
3637 }
3638 
3639 void UnwrappedLineParser::parseJavaScriptEs6ImportExport() {
3640   bool IsImport = FormatTok->is(Keywords.kw_import);
3641   assert(IsImport || FormatTok->is(tok::kw_export));
3642   nextToken();
3643 
3644   // Consume the "default" in "export default class/function".
3645   if (FormatTok->is(tok::kw_default))
3646     nextToken();
3647 
3648   // Consume "async function", "function" and "default function", so that these
3649   // get parsed as free-standing JS functions, i.e. do not require a trailing
3650   // semicolon.
3651   if (FormatTok->is(Keywords.kw_async))
3652     nextToken();
3653   if (FormatTok->is(Keywords.kw_function)) {
3654     nextToken();
3655     return;
3656   }
3657 
3658   // For imports, `export *`, `export {...}`, consume the rest of the line up
3659   // to the terminating `;`. For everything else, just return and continue
3660   // parsing the structural element, i.e. the declaration or expression for
3661   // `export default`.
3662   if (!IsImport && !FormatTok->isOneOf(tok::l_brace, tok::star) &&
3663       !FormatTok->isStringLiteral())
3664     return;
3665 
3666   while (!eof()) {
3667     if (FormatTok->is(tok::semi))
3668       return;
3669     if (Line->Tokens.empty()) {
3670       // Common issue: Automatic Semicolon Insertion wrapped the line, so the
3671       // import statement should terminate.
3672       return;
3673     }
3674     if (FormatTok->is(tok::l_brace)) {
3675       FormatTok->setBlockKind(BK_Block);
3676       nextToken();
3677       parseBracedList();
3678     } else {
3679       nextToken();
3680     }
3681   }
3682 }
3683 
3684 void UnwrappedLineParser::parseStatementMacro() {
3685   nextToken();
3686   if (FormatTok->is(tok::l_paren))
3687     parseParens();
3688   if (FormatTok->is(tok::semi))
3689     nextToken();
3690   addUnwrappedLine();
3691 }
3692 
3693 LLVM_ATTRIBUTE_UNUSED static void printDebugInfo(const UnwrappedLine &Line,
3694                                                  StringRef Prefix = "") {
3695   llvm::dbgs() << Prefix << "Line(" << Line.Level
3696                << ", FSC=" << Line.FirstStartColumn << ")"
3697                << (Line.InPPDirective ? " MACRO" : "") << ": ";
3698   for (const auto &Node : Line.Tokens) {
3699     llvm::dbgs() << Node.Tok->Tok.getName() << "["
3700                  << "T=" << static_cast<unsigned>(Node.Tok->getType())
3701                  << ", OC=" << Node.Tok->OriginalColumn << "] ";
3702   }
3703   for (const auto &Node : Line.Tokens)
3704     for (const auto &ChildNode : Node.Children)
3705       printDebugInfo(ChildNode, "\nChild: ");
3706 
3707   llvm::dbgs() << "\n";
3708 }
3709 
3710 void UnwrappedLineParser::addUnwrappedLine(LineLevel AdjustLevel) {
3711   if (Line->Tokens.empty())
3712     return;
3713   LLVM_DEBUG({
3714     if (CurrentLines == &Lines)
3715       printDebugInfo(*Line);
3716   });
3717 
3718   // If this line closes a block when in Whitesmiths mode, remember that
3719   // information so that the level can be decreased after the line is added.
3720   // This has to happen after the addition of the line since the line itself
3721   // needs to be indented.
3722   bool ClosesWhitesmithsBlock =
3723       Line->MatchingOpeningBlockLineIndex != UnwrappedLine::kInvalidIndex &&
3724       Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths;
3725 
3726   CurrentLines->push_back(std::move(*Line));
3727   Line->Tokens.clear();
3728   Line->MatchingOpeningBlockLineIndex = UnwrappedLine::kInvalidIndex;
3729   Line->FirstStartColumn = 0;
3730 
3731   if (ClosesWhitesmithsBlock && AdjustLevel == LineLevel::Remove)
3732     --Line->Level;
3733   if (CurrentLines == &Lines && !PreprocessorDirectives.empty()) {
3734     CurrentLines->append(
3735         std::make_move_iterator(PreprocessorDirectives.begin()),
3736         std::make_move_iterator(PreprocessorDirectives.end()));
3737     PreprocessorDirectives.clear();
3738   }
3739   // Disconnect the current token from the last token on the previous line.
3740   FormatTok->Previous = nullptr;
3741 }
3742 
3743 bool UnwrappedLineParser::eof() const { return FormatTok->is(tok::eof); }
3744 
3745 bool UnwrappedLineParser::isOnNewLine(const FormatToken &FormatTok) {
3746   return (Line->InPPDirective || FormatTok.HasUnescapedNewline) &&
3747          FormatTok.NewlinesBefore > 0;
3748 }
3749 
3750 // Checks if \p FormatTok is a line comment that continues the line comment
3751 // section on \p Line.
3752 static bool
3753 continuesLineCommentSection(const FormatToken &FormatTok,
3754                             const UnwrappedLine &Line,
3755                             const llvm::Regex &CommentPragmasRegex) {
3756   if (Line.Tokens.empty())
3757     return false;
3758 
3759   StringRef IndentContent = FormatTok.TokenText;
3760   if (FormatTok.TokenText.startswith("//") ||
3761       FormatTok.TokenText.startswith("/*"))
3762     IndentContent = FormatTok.TokenText.substr(2);
3763   if (CommentPragmasRegex.match(IndentContent))
3764     return false;
3765 
3766   // If Line starts with a line comment, then FormatTok continues the comment
3767   // section if its original column is greater or equal to the original start
3768   // column of the line.
3769   //
3770   // Define the min column token of a line as follows: if a line ends in '{' or
3771   // contains a '{' followed by a line comment, then the min column token is
3772   // that '{'. Otherwise, the min column token of the line is the first token of
3773   // the line.
3774   //
3775   // If Line starts with a token other than a line comment, then FormatTok
3776   // continues the comment section if its original column is greater than the
3777   // original start column of the min column token of the line.
3778   //
3779   // For example, the second line comment continues the first in these cases:
3780   //
3781   // // first line
3782   // // second line
3783   //
3784   // and:
3785   //
3786   // // first line
3787   //  // second line
3788   //
3789   // and:
3790   //
3791   // int i; // first line
3792   //  // second line
3793   //
3794   // and:
3795   //
3796   // do { // first line
3797   //      // second line
3798   //   int i;
3799   // } while (true);
3800   //
3801   // and:
3802   //
3803   // enum {
3804   //   a, // first line
3805   //    // second line
3806   //   b
3807   // };
3808   //
3809   // The second line comment doesn't continue the first in these cases:
3810   //
3811   //   // first line
3812   //  // second line
3813   //
3814   // and:
3815   //
3816   // int i; // first line
3817   // // second line
3818   //
3819   // and:
3820   //
3821   // do { // first line
3822   //   // second line
3823   //   int i;
3824   // } while (true);
3825   //
3826   // and:
3827   //
3828   // enum {
3829   //   a, // first line
3830   //   // second line
3831   // };
3832   const FormatToken *MinColumnToken = Line.Tokens.front().Tok;
3833 
3834   // Scan for '{//'. If found, use the column of '{' as a min column for line
3835   // comment section continuation.
3836   const FormatToken *PreviousToken = nullptr;
3837   for (const UnwrappedLineNode &Node : Line.Tokens) {
3838     if (PreviousToken && PreviousToken->is(tok::l_brace) &&
3839         isLineComment(*Node.Tok)) {
3840       MinColumnToken = PreviousToken;
3841       break;
3842     }
3843     PreviousToken = Node.Tok;
3844 
3845     // Grab the last newline preceding a token in this unwrapped line.
3846     if (Node.Tok->NewlinesBefore > 0)
3847       MinColumnToken = Node.Tok;
3848   }
3849   if (PreviousToken && PreviousToken->is(tok::l_brace))
3850     MinColumnToken = PreviousToken;
3851 
3852   return continuesLineComment(FormatTok, /*Previous=*/Line.Tokens.back().Tok,
3853                               MinColumnToken);
3854 }
3855 
3856 void UnwrappedLineParser::flushComments(bool NewlineBeforeNext) {
3857   bool JustComments = Line->Tokens.empty();
3858   for (FormatToken *Tok : CommentsBeforeNextToken) {
3859     // Line comments that belong to the same line comment section are put on the
3860     // same line since later we might want to reflow content between them.
3861     // Additional fine-grained breaking of line comment sections is controlled
3862     // by the class BreakableLineCommentSection in case it is desirable to keep
3863     // several line comment sections in the same unwrapped line.
3864     //
3865     // FIXME: Consider putting separate line comment sections as children to the
3866     // unwrapped line instead.
3867     Tok->ContinuesLineCommentSection =
3868         continuesLineCommentSection(*Tok, *Line, CommentPragmasRegex);
3869     if (isOnNewLine(*Tok) && JustComments && !Tok->ContinuesLineCommentSection)
3870       addUnwrappedLine();
3871     pushToken(Tok);
3872   }
3873   if (NewlineBeforeNext && JustComments)
3874     addUnwrappedLine();
3875   CommentsBeforeNextToken.clear();
3876 }
3877 
3878 void UnwrappedLineParser::nextToken(int LevelDifference) {
3879   if (eof())
3880     return;
3881   flushComments(isOnNewLine(*FormatTok));
3882   pushToken(FormatTok);
3883   FormatToken *Previous = FormatTok;
3884   if (!Style.isJavaScript())
3885     readToken(LevelDifference);
3886   else
3887     readTokenWithJavaScriptASI();
3888   FormatTok->Previous = Previous;
3889 }
3890 
3891 void UnwrappedLineParser::distributeComments(
3892     const SmallVectorImpl<FormatToken *> &Comments,
3893     const FormatToken *NextTok) {
3894   // Whether or not a line comment token continues a line is controlled by
3895   // the method continuesLineCommentSection, with the following caveat:
3896   //
3897   // Define a trail of Comments to be a nonempty proper postfix of Comments such
3898   // that each comment line from the trail is aligned with the next token, if
3899   // the next token exists. If a trail exists, the beginning of the maximal
3900   // trail is marked as a start of a new comment section.
3901   //
3902   // For example in this code:
3903   //
3904   // int a; // line about a
3905   //   // line 1 about b
3906   //   // line 2 about b
3907   //   int b;
3908   //
3909   // the two lines about b form a maximal trail, so there are two sections, the
3910   // first one consisting of the single comment "// line about a" and the
3911   // second one consisting of the next two comments.
3912   if (Comments.empty())
3913     return;
3914   bool ShouldPushCommentsInCurrentLine = true;
3915   bool HasTrailAlignedWithNextToken = false;
3916   unsigned StartOfTrailAlignedWithNextToken = 0;
3917   if (NextTok) {
3918     // We are skipping the first element intentionally.
3919     for (unsigned i = Comments.size() - 1; i > 0; --i) {
3920       if (Comments[i]->OriginalColumn == NextTok->OriginalColumn) {
3921         HasTrailAlignedWithNextToken = true;
3922         StartOfTrailAlignedWithNextToken = i;
3923       }
3924     }
3925   }
3926   for (unsigned i = 0, e = Comments.size(); i < e; ++i) {
3927     FormatToken *FormatTok = Comments[i];
3928     if (HasTrailAlignedWithNextToken && i == StartOfTrailAlignedWithNextToken) {
3929       FormatTok->ContinuesLineCommentSection = false;
3930     } else {
3931       FormatTok->ContinuesLineCommentSection =
3932           continuesLineCommentSection(*FormatTok, *Line, CommentPragmasRegex);
3933     }
3934     if (!FormatTok->ContinuesLineCommentSection &&
3935         (isOnNewLine(*FormatTok) || FormatTok->IsFirst))
3936       ShouldPushCommentsInCurrentLine = false;
3937     if (ShouldPushCommentsInCurrentLine)
3938       pushToken(FormatTok);
3939     else
3940       CommentsBeforeNextToken.push_back(FormatTok);
3941   }
3942 }
3943 
3944 void UnwrappedLineParser::readToken(int LevelDifference) {
3945   SmallVector<FormatToken *, 1> Comments;
3946   bool PreviousWasComment = false;
3947   bool FirstNonCommentOnLine = false;
3948   do {
3949     FormatTok = Tokens->getNextToken();
3950     assert(FormatTok);
3951     while (FormatTok->getType() == TT_ConflictStart ||
3952            FormatTok->getType() == TT_ConflictEnd ||
3953            FormatTok->getType() == TT_ConflictAlternative) {
3954       if (FormatTok->getType() == TT_ConflictStart)
3955         conditionalCompilationStart(/*Unreachable=*/false);
3956       else if (FormatTok->getType() == TT_ConflictAlternative)
3957         conditionalCompilationAlternative();
3958       else if (FormatTok->getType() == TT_ConflictEnd)
3959         conditionalCompilationEnd();
3960       FormatTok = Tokens->getNextToken();
3961       FormatTok->MustBreakBefore = true;
3962     }
3963 
3964     auto IsFirstNonCommentOnLine = [](bool FirstNonCommentOnLine,
3965                                       const FormatToken &Tok,
3966                                       bool PreviousWasComment) {
3967       auto IsFirstOnLine = [](const FormatToken &Tok) {
3968         return Tok.HasUnescapedNewline || Tok.IsFirst;
3969       };
3970 
3971       // Consider preprocessor directives preceded by block comments as first
3972       // on line.
3973       if (PreviousWasComment)
3974         return FirstNonCommentOnLine || IsFirstOnLine(Tok);
3975       return IsFirstOnLine(Tok);
3976     };
3977 
3978     FirstNonCommentOnLine = IsFirstNonCommentOnLine(
3979         FirstNonCommentOnLine, *FormatTok, PreviousWasComment);
3980     PreviousWasComment = FormatTok->is(tok::comment);
3981 
3982     while (!Line->InPPDirective && FormatTok->is(tok::hash) &&
3983            FirstNonCommentOnLine) {
3984       distributeComments(Comments, FormatTok);
3985       Comments.clear();
3986       // If there is an unfinished unwrapped line, we flush the preprocessor
3987       // directives only after that unwrapped line was finished later.
3988       bool SwitchToPreprocessorLines = !Line->Tokens.empty();
3989       ScopedLineState BlockState(*this, SwitchToPreprocessorLines);
3990       assert((LevelDifference >= 0 ||
3991               static_cast<unsigned>(-LevelDifference) <= Line->Level) &&
3992              "LevelDifference makes Line->Level negative");
3993       Line->Level += LevelDifference;
3994       // Comments stored before the preprocessor directive need to be output
3995       // before the preprocessor directive, at the same level as the
3996       // preprocessor directive, as we consider them to apply to the directive.
3997       if (Style.IndentPPDirectives == FormatStyle::PPDIS_BeforeHash &&
3998           PPBranchLevel > 0)
3999         Line->Level += PPBranchLevel;
4000       flushComments(isOnNewLine(*FormatTok));
4001       parsePPDirective();
4002       PreviousWasComment = FormatTok->is(tok::comment);
4003       FirstNonCommentOnLine = IsFirstNonCommentOnLine(
4004           FirstNonCommentOnLine, *FormatTok, PreviousWasComment);
4005     }
4006 
4007     if (!PPStack.empty() && (PPStack.back().Kind == PP_Unreachable) &&
4008         !Line->InPPDirective)
4009       continue;
4010 
4011     if (!FormatTok->is(tok::comment)) {
4012       distributeComments(Comments, FormatTok);
4013       Comments.clear();
4014       return;
4015     }
4016 
4017     Comments.push_back(FormatTok);
4018   } while (!eof());
4019 
4020   distributeComments(Comments, nullptr);
4021   Comments.clear();
4022 }
4023 
4024 void UnwrappedLineParser::pushToken(FormatToken *Tok) {
4025   Line->Tokens.push_back(UnwrappedLineNode(Tok));
4026   if (MustBreakBeforeNextToken) {
4027     Line->Tokens.back().Tok->MustBreakBefore = true;
4028     MustBreakBeforeNextToken = false;
4029   }
4030 }
4031 
4032 } // end namespace format
4033 } // end namespace clang
4034