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->setFinalizedType(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->setFinalizedType(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->setFinalizedType(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->setFinalizedType(TT_InlineASMBrace);
1329       nextToken();
1330       while (FormatTok && FormatTok->isNot(tok::eof)) {
1331         if (FormatTok->is(tok::r_brace)) {
1332           FormatTok->setFinalizedType(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->setFinalizedType(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->setFinalizedType(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->setFinalizedType(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->setFinalizedType(TT_LambdaArrow);
2001       SeenArrow = true;
2002       nextToken();
2003       break;
2004     default:
2005       return true;
2006     }
2007   }
2008   FormatTok->setFinalizedType(TT_LambdaLBrace);
2009   LSquare.setFinalizedType(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->setFinalizedType(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->setFinalizedType(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 && getLastNonComment(L)) {
2340         Tok = L.Tokens.back().Tok;
2341         break;
2342       }
2343     }
2344     assert(Tok);
2345     ++Tok->BraceCount;
2346   }
2347 
2348   if (CheckEOF && FormatTok->is(tok::eof))
2349     addUnwrappedLine();
2350 
2351   --Line->Level;
2352 }
2353 
2354 static void markOptionalBraces(FormatToken *LeftBrace) {
2355   if (!LeftBrace)
2356     return;
2357 
2358   assert(LeftBrace->is(tok::l_brace));
2359 
2360   FormatToken *RightBrace = LeftBrace->MatchingParen;
2361   if (!RightBrace) {
2362     assert(!LeftBrace->Optional);
2363     return;
2364   }
2365 
2366   assert(RightBrace->is(tok::r_brace));
2367   assert(RightBrace->MatchingParen == LeftBrace);
2368   assert(LeftBrace->Optional == RightBrace->Optional);
2369 
2370   LeftBrace->Optional = true;
2371   RightBrace->Optional = true;
2372 }
2373 
2374 FormatToken *UnwrappedLineParser::parseIfThenElse(IfStmtKind *IfKind,
2375                                                   bool KeepBraces) {
2376   auto HandleAttributes = [this]() {
2377     // Handle AttributeMacro, e.g. `if (x) UNLIKELY`.
2378     if (FormatTok->is(TT_AttributeMacro))
2379       nextToken();
2380     // Handle [[likely]] / [[unlikely]] attributes.
2381     if (FormatTok->is(tok::l_square) && tryToParseSimpleAttribute())
2382       parseSquare();
2383   };
2384 
2385   assert(FormatTok->is(tok::kw_if) && "'if' expected");
2386   nextToken();
2387   if (FormatTok->is(tok::exclaim))
2388     nextToken();
2389   if (FormatTok->is(tok::kw_consteval)) {
2390     nextToken();
2391   } else {
2392     if (FormatTok->isOneOf(tok::kw_constexpr, tok::identifier))
2393       nextToken();
2394     if (FormatTok->is(tok::l_paren))
2395       parseParens();
2396   }
2397   HandleAttributes();
2398 
2399   bool NeedsUnwrappedLine = false;
2400   keepAncestorBraces();
2401 
2402   FormatToken *IfLeftBrace = nullptr;
2403   IfStmtKind IfBlockKind = IfStmtKind::NotIf;
2404 
2405   if (FormatTok->is(tok::l_brace)) {
2406     IfLeftBrace = FormatTok;
2407     CompoundStatementIndenter Indenter(this, Style, Line->Level);
2408     IfBlockKind = parseBlock();
2409     if (Style.BraceWrapping.BeforeElse)
2410       addUnwrappedLine();
2411     else
2412       NeedsUnwrappedLine = true;
2413   } else {
2414     parseUnbracedBody();
2415   }
2416 
2417   bool KeepIfBraces = false;
2418   if (Style.RemoveBracesLLVM) {
2419     assert(!NestedTooDeep.empty());
2420     KeepIfBraces = (IfLeftBrace && !IfLeftBrace->MatchingParen) ||
2421                    NestedTooDeep.back() || IfBlockKind == IfStmtKind::IfOnly ||
2422                    IfBlockKind == IfStmtKind::IfElseIf;
2423   }
2424 
2425   FormatToken *ElseLeftBrace = nullptr;
2426   IfStmtKind Kind = IfStmtKind::IfOnly;
2427 
2428   if (FormatTok->is(tok::kw_else)) {
2429     if (Style.RemoveBracesLLVM) {
2430       NestedTooDeep.back() = false;
2431       Kind = IfStmtKind::IfElse;
2432     }
2433     nextToken();
2434     HandleAttributes();
2435     if (FormatTok->is(tok::l_brace)) {
2436       ElseLeftBrace = FormatTok;
2437       CompoundStatementIndenter Indenter(this, Style, Line->Level);
2438       if (parseBlock() == IfStmtKind::IfOnly)
2439         Kind = IfStmtKind::IfElseIf;
2440       addUnwrappedLine();
2441     } else if (FormatTok->is(tok::kw_if)) {
2442       FormatToken *Previous = Tokens->getPreviousToken();
2443       const bool IsPrecededByComment = Previous && Previous->is(tok::comment);
2444       if (IsPrecededByComment) {
2445         addUnwrappedLine();
2446         ++Line->Level;
2447       }
2448       bool TooDeep = true;
2449       if (Style.RemoveBracesLLVM) {
2450         Kind = IfStmtKind::IfElseIf;
2451         TooDeep = NestedTooDeep.pop_back_val();
2452       }
2453       ElseLeftBrace =
2454           parseIfThenElse(/*IfKind=*/nullptr, KeepBraces || KeepIfBraces);
2455       if (Style.RemoveBracesLLVM)
2456         NestedTooDeep.push_back(TooDeep);
2457       if (IsPrecededByComment)
2458         --Line->Level;
2459     } else {
2460       parseUnbracedBody(/*CheckEOF=*/true);
2461     }
2462   } else {
2463     if (Style.RemoveBracesLLVM)
2464       KeepIfBraces = KeepIfBraces || IfBlockKind == IfStmtKind::IfElse;
2465     if (NeedsUnwrappedLine)
2466       addUnwrappedLine();
2467   }
2468 
2469   if (!Style.RemoveBracesLLVM)
2470     return nullptr;
2471 
2472   assert(!NestedTooDeep.empty());
2473   const bool KeepElseBraces =
2474       (ElseLeftBrace && !ElseLeftBrace->MatchingParen) || NestedTooDeep.back();
2475 
2476   NestedTooDeep.pop_back();
2477 
2478   if (!KeepBraces && !KeepIfBraces && !KeepElseBraces) {
2479     markOptionalBraces(IfLeftBrace);
2480     markOptionalBraces(ElseLeftBrace);
2481   } else if (IfLeftBrace) {
2482     FormatToken *IfRightBrace = IfLeftBrace->MatchingParen;
2483     if (IfRightBrace) {
2484       assert(IfRightBrace->MatchingParen == IfLeftBrace);
2485       assert(!IfLeftBrace->Optional);
2486       assert(!IfRightBrace->Optional);
2487       IfLeftBrace->MatchingParen = nullptr;
2488       IfRightBrace->MatchingParen = nullptr;
2489     }
2490   }
2491 
2492   if (IfKind)
2493     *IfKind = Kind;
2494 
2495   return IfLeftBrace;
2496 }
2497 
2498 void UnwrappedLineParser::parseTryCatch() {
2499   assert(FormatTok->isOneOf(tok::kw_try, tok::kw___try) && "'try' expected");
2500   nextToken();
2501   bool NeedsUnwrappedLine = false;
2502   if (FormatTok->is(tok::colon)) {
2503     // We are in a function try block, what comes is an initializer list.
2504     nextToken();
2505 
2506     // In case identifiers were removed by clang-tidy, what might follow is
2507     // multiple commas in sequence - before the first identifier.
2508     while (FormatTok->is(tok::comma))
2509       nextToken();
2510 
2511     while (FormatTok->is(tok::identifier)) {
2512       nextToken();
2513       if (FormatTok->is(tok::l_paren))
2514         parseParens();
2515       if (FormatTok->Previous && FormatTok->Previous->is(tok::identifier) &&
2516           FormatTok->is(tok::l_brace)) {
2517         do {
2518           nextToken();
2519         } while (!FormatTok->is(tok::r_brace));
2520         nextToken();
2521       }
2522 
2523       // In case identifiers were removed by clang-tidy, what might follow is
2524       // multiple commas in sequence - after the first identifier.
2525       while (FormatTok->is(tok::comma))
2526         nextToken();
2527     }
2528   }
2529   // Parse try with resource.
2530   if (Style.Language == FormatStyle::LK_Java && FormatTok->is(tok::l_paren))
2531     parseParens();
2532 
2533   keepAncestorBraces();
2534 
2535   if (FormatTok->is(tok::l_brace)) {
2536     CompoundStatementIndenter Indenter(this, Style, Line->Level);
2537     parseBlock();
2538     if (Style.BraceWrapping.BeforeCatch)
2539       addUnwrappedLine();
2540     else
2541       NeedsUnwrappedLine = true;
2542   } else if (!FormatTok->is(tok::kw_catch)) {
2543     // The C++ standard requires a compound-statement after a try.
2544     // If there's none, we try to assume there's a structuralElement
2545     // and try to continue.
2546     addUnwrappedLine();
2547     ++Line->Level;
2548     parseStructuralElement();
2549     --Line->Level;
2550   }
2551   while (true) {
2552     if (FormatTok->is(tok::at))
2553       nextToken();
2554     if (!(FormatTok->isOneOf(tok::kw_catch, Keywords.kw___except,
2555                              tok::kw___finally) ||
2556           ((Style.Language == FormatStyle::LK_Java || Style.isJavaScript()) &&
2557            FormatTok->is(Keywords.kw_finally)) ||
2558           (FormatTok->isObjCAtKeyword(tok::objc_catch) ||
2559            FormatTok->isObjCAtKeyword(tok::objc_finally))))
2560       break;
2561     nextToken();
2562     while (FormatTok->isNot(tok::l_brace)) {
2563       if (FormatTok->is(tok::l_paren)) {
2564         parseParens();
2565         continue;
2566       }
2567       if (FormatTok->isOneOf(tok::semi, tok::r_brace, tok::eof)) {
2568         if (Style.RemoveBracesLLVM)
2569           NestedTooDeep.pop_back();
2570         return;
2571       }
2572       nextToken();
2573     }
2574     NeedsUnwrappedLine = false;
2575     CompoundStatementIndenter Indenter(this, Style, Line->Level);
2576     parseBlock();
2577     if (Style.BraceWrapping.BeforeCatch)
2578       addUnwrappedLine();
2579     else
2580       NeedsUnwrappedLine = true;
2581   }
2582 
2583   if (Style.RemoveBracesLLVM)
2584     NestedTooDeep.pop_back();
2585 
2586   if (NeedsUnwrappedLine)
2587     addUnwrappedLine();
2588 }
2589 
2590 void UnwrappedLineParser::parseNamespace() {
2591   assert(FormatTok->isOneOf(tok::kw_namespace, TT_NamespaceMacro) &&
2592          "'namespace' expected");
2593 
2594   const FormatToken &InitialToken = *FormatTok;
2595   nextToken();
2596   if (InitialToken.is(TT_NamespaceMacro)) {
2597     parseParens();
2598   } else {
2599     while (FormatTok->isOneOf(tok::identifier, tok::coloncolon, tok::kw_inline,
2600                               tok::l_square, tok::period, tok::l_paren) ||
2601            (Style.isCSharp() && FormatTok->is(tok::kw_union)))
2602       if (FormatTok->is(tok::l_square))
2603         parseSquare();
2604       else if (FormatTok->is(tok::l_paren))
2605         parseParens();
2606       else
2607         nextToken();
2608   }
2609   if (FormatTok->is(tok::l_brace)) {
2610     if (ShouldBreakBeforeBrace(Style, InitialToken))
2611       addUnwrappedLine();
2612 
2613     unsigned AddLevels =
2614         Style.NamespaceIndentation == FormatStyle::NI_All ||
2615                 (Style.NamespaceIndentation == FormatStyle::NI_Inner &&
2616                  DeclarationScopeStack.size() > 1)
2617             ? 1u
2618             : 0u;
2619     bool ManageWhitesmithsBraces =
2620         AddLevels == 0u &&
2621         Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths;
2622 
2623     // If we're in Whitesmiths mode, indent the brace if we're not indenting
2624     // the whole block.
2625     if (ManageWhitesmithsBraces)
2626       ++Line->Level;
2627 
2628     parseBlock(/*MustBeDeclaration=*/true, AddLevels,
2629                /*MunchSemi=*/true,
2630                /*UnindentWhitesmithsBraces=*/ManageWhitesmithsBraces);
2631 
2632     // Munch the semicolon after a namespace. This is more common than one would
2633     // think. Putting the semicolon into its own line is very ugly.
2634     if (FormatTok->is(tok::semi))
2635       nextToken();
2636 
2637     addUnwrappedLine(AddLevels > 0 ? LineLevel::Remove : LineLevel::Keep);
2638 
2639     if (ManageWhitesmithsBraces)
2640       --Line->Level;
2641   }
2642   // FIXME: Add error handling.
2643 }
2644 
2645 void UnwrappedLineParser::parseNew() {
2646   assert(FormatTok->is(tok::kw_new) && "'new' expected");
2647   nextToken();
2648 
2649   if (Style.isCSharp()) {
2650     do {
2651       if (FormatTok->is(tok::l_brace))
2652         parseBracedList();
2653 
2654       if (FormatTok->isOneOf(tok::semi, tok::comma))
2655         return;
2656 
2657       nextToken();
2658     } while (!eof());
2659   }
2660 
2661   if (Style.Language != FormatStyle::LK_Java)
2662     return;
2663 
2664   // In Java, we can parse everything up to the parens, which aren't optional.
2665   do {
2666     // There should not be a ;, { or } before the new's open paren.
2667     if (FormatTok->isOneOf(tok::semi, tok::l_brace, tok::r_brace))
2668       return;
2669 
2670     // Consume the parens.
2671     if (FormatTok->is(tok::l_paren)) {
2672       parseParens();
2673 
2674       // If there is a class body of an anonymous class, consume that as child.
2675       if (FormatTok->is(tok::l_brace))
2676         parseChildBlock();
2677       return;
2678     }
2679     nextToken();
2680   } while (!eof());
2681 }
2682 
2683 void UnwrappedLineParser::parseForOrWhileLoop() {
2684   assert(FormatTok->isOneOf(tok::kw_for, tok::kw_while, TT_ForEachMacro) &&
2685          "'for', 'while' or foreach macro expected");
2686   nextToken();
2687   // JS' for await ( ...
2688   if (Style.isJavaScript() && FormatTok->is(Keywords.kw_await))
2689     nextToken();
2690   if (Style.isCpp() && FormatTok->is(tok::kw_co_await))
2691     nextToken();
2692   if (FormatTok->is(tok::l_paren))
2693     parseParens();
2694 
2695   keepAncestorBraces();
2696 
2697   if (FormatTok->is(tok::l_brace)) {
2698     FormatToken *LeftBrace = FormatTok;
2699     CompoundStatementIndenter Indenter(this, Style, Line->Level);
2700     parseBlock();
2701     if (Style.RemoveBracesLLVM) {
2702       assert(!NestedTooDeep.empty());
2703       if (!NestedTooDeep.back())
2704         markOptionalBraces(LeftBrace);
2705     }
2706     addUnwrappedLine();
2707   } else {
2708     parseUnbracedBody();
2709   }
2710 
2711   if (Style.RemoveBracesLLVM)
2712     NestedTooDeep.pop_back();
2713 }
2714 
2715 void UnwrappedLineParser::parseDoWhile() {
2716   assert(FormatTok->is(tok::kw_do) && "'do' expected");
2717   nextToken();
2718 
2719   keepAncestorBraces();
2720 
2721   if (FormatTok->is(tok::l_brace)) {
2722     CompoundStatementIndenter Indenter(this, Style, Line->Level);
2723     parseBlock();
2724     if (Style.BraceWrapping.BeforeWhile)
2725       addUnwrappedLine();
2726   } else {
2727     parseUnbracedBody();
2728   }
2729 
2730   if (Style.RemoveBracesLLVM)
2731     NestedTooDeep.pop_back();
2732 
2733   // FIXME: Add error handling.
2734   if (!FormatTok->is(tok::kw_while)) {
2735     addUnwrappedLine();
2736     return;
2737   }
2738 
2739   // If in Whitesmiths mode, the line with the while() needs to be indented
2740   // to the same level as the block.
2741   if (Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths)
2742     ++Line->Level;
2743 
2744   nextToken();
2745   parseStructuralElement();
2746 }
2747 
2748 void UnwrappedLineParser::parseLabel(bool LeftAlignLabel) {
2749   nextToken();
2750   unsigned OldLineLevel = Line->Level;
2751   if (Line->Level > 1 || (!Line->InPPDirective && Line->Level > 0))
2752     --Line->Level;
2753   if (LeftAlignLabel)
2754     Line->Level = 0;
2755 
2756   if (!Style.IndentCaseBlocks && CommentsBeforeNextToken.empty() &&
2757       FormatTok->is(tok::l_brace)) {
2758 
2759     CompoundStatementIndenter Indenter(this, Line->Level,
2760                                        Style.BraceWrapping.AfterCaseLabel,
2761                                        Style.BraceWrapping.IndentBraces);
2762     parseBlock();
2763     if (FormatTok->is(tok::kw_break)) {
2764       if (Style.BraceWrapping.AfterControlStatement ==
2765           FormatStyle::BWACS_Always) {
2766         addUnwrappedLine();
2767         if (!Style.IndentCaseBlocks &&
2768             Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths)
2769           ++Line->Level;
2770       }
2771       parseStructuralElement();
2772     }
2773     addUnwrappedLine();
2774   } else {
2775     if (FormatTok->is(tok::semi))
2776       nextToken();
2777     addUnwrappedLine();
2778   }
2779   Line->Level = OldLineLevel;
2780   if (FormatTok->isNot(tok::l_brace)) {
2781     parseStructuralElement();
2782     addUnwrappedLine();
2783   }
2784 }
2785 
2786 void UnwrappedLineParser::parseCaseLabel() {
2787   assert(FormatTok->is(tok::kw_case) && "'case' expected");
2788 
2789   // FIXME: fix handling of complex expressions here.
2790   do {
2791     nextToken();
2792   } while (!eof() && !FormatTok->is(tok::colon));
2793   parseLabel();
2794 }
2795 
2796 void UnwrappedLineParser::parseSwitch() {
2797   assert(FormatTok->is(tok::kw_switch) && "'switch' expected");
2798   nextToken();
2799   if (FormatTok->is(tok::l_paren))
2800     parseParens();
2801 
2802   keepAncestorBraces();
2803 
2804   if (FormatTok->is(tok::l_brace)) {
2805     CompoundStatementIndenter Indenter(this, Style, Line->Level);
2806     parseBlock();
2807     addUnwrappedLine();
2808   } else {
2809     addUnwrappedLine();
2810     ++Line->Level;
2811     parseStructuralElement();
2812     --Line->Level;
2813   }
2814 
2815   if (Style.RemoveBracesLLVM)
2816     NestedTooDeep.pop_back();
2817 }
2818 
2819 void UnwrappedLineParser::parseAccessSpecifier() {
2820   FormatToken *AccessSpecifierCandidate = FormatTok;
2821   nextToken();
2822   // Understand Qt's slots.
2823   if (FormatTok->isOneOf(Keywords.kw_slots, Keywords.kw_qslots))
2824     nextToken();
2825   // Otherwise, we don't know what it is, and we'd better keep the next token.
2826   if (FormatTok->is(tok::colon)) {
2827     nextToken();
2828     addUnwrappedLine();
2829   } else if (!FormatTok->is(tok::coloncolon) &&
2830              !std::binary_search(COperatorsFollowingVar.begin(),
2831                                  COperatorsFollowingVar.end(),
2832                                  FormatTok->Tok.getKind())) {
2833     // Not a variable name nor namespace name.
2834     addUnwrappedLine();
2835   } else if (AccessSpecifierCandidate) {
2836     // Consider the access specifier to be a C identifier.
2837     AccessSpecifierCandidate->Tok.setKind(tok::identifier);
2838   }
2839 }
2840 
2841 /// \brief Parses a concept definition.
2842 /// \pre The current token has to be the concept keyword.
2843 ///
2844 /// Returns if either the concept has been completely parsed, or if it detects
2845 /// that the concept definition is incorrect.
2846 void UnwrappedLineParser::parseConcept() {
2847   assert(FormatTok->is(tok::kw_concept) && "'concept' expected");
2848   nextToken();
2849   if (!FormatTok->is(tok::identifier))
2850     return;
2851   nextToken();
2852   if (!FormatTok->is(tok::equal))
2853     return;
2854   nextToken();
2855   parseConstraintExpression();
2856   if (FormatTok->is(tok::semi))
2857     nextToken();
2858   addUnwrappedLine();
2859 }
2860 
2861 /// \brief Parses a requires, decides if it is a clause or an expression.
2862 /// \pre The current token has to be the requires keyword.
2863 /// \returns true if it parsed a clause.
2864 bool clang::format::UnwrappedLineParser::parseRequires() {
2865   assert(FormatTok->is(tok::kw_requires) && "'requires' expected");
2866   auto RequiresToken = FormatTok;
2867 
2868   // We try to guess if it is a requires clause, or a requires expression. For
2869   // that we first consume the keyword and check the next token.
2870   nextToken();
2871 
2872   switch (FormatTok->Tok.getKind()) {
2873   case tok::l_brace:
2874     // This can only be an expression, never a clause.
2875     parseRequiresExpression(RequiresToken);
2876     return false;
2877   case tok::l_paren:
2878     // Clauses and expression can start with a paren, it's unclear what we have.
2879     break;
2880   default:
2881     // All other tokens can only be a clause.
2882     parseRequiresClause(RequiresToken);
2883     return true;
2884   }
2885 
2886   // Looking forward we would have to decide if there are function declaration
2887   // like arguments to the requires expression:
2888   // requires (T t) {
2889   // Or there is a constraint expression for the requires clause:
2890   // requires (C<T> && ...
2891 
2892   // But first let's look behind.
2893   auto *PreviousNonComment = RequiresToken->getPreviousNonComment();
2894 
2895   if (!PreviousNonComment ||
2896       PreviousNonComment->is(TT_RequiresExpressionLBrace)) {
2897     // If there is no token, or an expression left brace, we are a requires
2898     // clause within a requires expression.
2899     parseRequiresClause(RequiresToken);
2900     return true;
2901   }
2902 
2903   switch (PreviousNonComment->Tok.getKind()) {
2904   case tok::greater:
2905   case tok::r_paren:
2906   case tok::kw_noexcept:
2907   case tok::kw_const:
2908     // This is a requires clause.
2909     parseRequiresClause(RequiresToken);
2910     return true;
2911   case tok::amp:
2912   case tok::ampamp: {
2913     // This can be either:
2914     // if (... && requires (T t) ...)
2915     // Or
2916     // void member(...) && requires (C<T> ...
2917     // We check the one token before that for a const:
2918     // void member(...) const && requires (C<T> ...
2919     auto PrevPrev = PreviousNonComment->getPreviousNonComment();
2920     if (PrevPrev && PrevPrev->is(tok::kw_const)) {
2921       parseRequiresClause(RequiresToken);
2922       return true;
2923     }
2924     break;
2925   }
2926   default:
2927     // It's an expression.
2928     parseRequiresExpression(RequiresToken);
2929     return false;
2930   }
2931 
2932   // Now we look forward and try to check if the paren content is a parameter
2933   // list. The parameters can be cv-qualified and contain references or
2934   // pointers.
2935   // So we want basically to check for TYPE NAME, but TYPE can contain all kinds
2936   // of stuff: typename, const, *, &, &&, ::, identifiers.
2937 
2938   int NextTokenOffset = 1;
2939   auto NextToken = Tokens->peekNextToken(NextTokenOffset);
2940   auto PeekNext = [&NextTokenOffset, &NextToken, this] {
2941     ++NextTokenOffset;
2942     NextToken = Tokens->peekNextToken(NextTokenOffset);
2943   };
2944 
2945   bool FoundType = false;
2946   bool LastWasColonColon = false;
2947   int OpenAngles = 0;
2948 
2949   for (; NextTokenOffset < 50; PeekNext()) {
2950     switch (NextToken->Tok.getKind()) {
2951     case tok::kw_volatile:
2952     case tok::kw_const:
2953     case tok::comma:
2954       parseRequiresExpression(RequiresToken);
2955       return false;
2956     case tok::r_paren:
2957     case tok::pipepipe:
2958       parseRequiresClause(RequiresToken);
2959       return true;
2960     case tok::eof:
2961       // Break out of the loop.
2962       NextTokenOffset = 50;
2963       break;
2964     case tok::coloncolon:
2965       LastWasColonColon = true;
2966       break;
2967     case tok::identifier:
2968       if (FoundType && !LastWasColonColon && OpenAngles == 0) {
2969         parseRequiresExpression(RequiresToken);
2970         return false;
2971       }
2972       FoundType = true;
2973       LastWasColonColon = false;
2974       break;
2975     case tok::less:
2976       ++OpenAngles;
2977       break;
2978     case tok::greater:
2979       --OpenAngles;
2980       break;
2981     default:
2982       if (NextToken->isSimpleTypeSpecifier()) {
2983         parseRequiresExpression(RequiresToken);
2984         return false;
2985       }
2986       break;
2987     }
2988   }
2989 
2990   // This seems to be a complicated expression, just assume it's a clause.
2991   parseRequiresClause(RequiresToken);
2992   return true;
2993 }
2994 
2995 /// \brief Parses a requires clause.
2996 /// \param RequiresToken The requires keyword token, which starts this clause.
2997 /// \pre We need to be on the next token after the requires keyword.
2998 /// \sa parseRequiresExpression
2999 ///
3000 /// Returns if it either has finished parsing the clause, or it detects, that
3001 /// the clause is incorrect.
3002 void UnwrappedLineParser::parseRequiresClause(FormatToken *RequiresToken) {
3003   assert(FormatTok->getPreviousNonComment() == RequiresToken);
3004   assert(RequiresToken->is(tok::kw_requires) && "'requires' expected");
3005 
3006   // If there is no previous token, we are within a requires expression,
3007   // otherwise we will always have the template or function declaration in front
3008   // of it.
3009   bool InRequiresExpression =
3010       !RequiresToken->Previous ||
3011       RequiresToken->Previous->is(TT_RequiresExpressionLBrace);
3012 
3013   RequiresToken->setFinalizedType(InRequiresExpression
3014                                       ? TT_RequiresClauseInARequiresExpression
3015                                       : TT_RequiresClause);
3016 
3017   parseConstraintExpression();
3018 
3019   if (!InRequiresExpression)
3020     FormatTok->Previous->ClosesRequiresClause = true;
3021 }
3022 
3023 /// \brief Parses a requires expression.
3024 /// \param RequiresToken The requires keyword token, which starts this clause.
3025 /// \pre We need to be on the next token after the requires keyword.
3026 /// \sa parseRequiresClause
3027 ///
3028 /// Returns if it either has finished parsing the expression, or it detects,
3029 /// that the expression is incorrect.
3030 void UnwrappedLineParser::parseRequiresExpression(FormatToken *RequiresToken) {
3031   assert(FormatTok->getPreviousNonComment() == RequiresToken);
3032   assert(RequiresToken->is(tok::kw_requires) && "'requires' expected");
3033 
3034   RequiresToken->setFinalizedType(TT_RequiresExpression);
3035 
3036   if (FormatTok->is(tok::l_paren)) {
3037     FormatTok->setFinalizedType(TT_RequiresExpressionLParen);
3038     parseParens();
3039   }
3040 
3041   if (FormatTok->is(tok::l_brace)) {
3042     FormatTok->setFinalizedType(TT_RequiresExpressionLBrace);
3043     parseChildBlock(/*CanContainBracedList=*/false,
3044                     /*NextLBracesType=*/TT_CompoundRequirementLBrace);
3045   }
3046 }
3047 
3048 /// \brief Parses a constraint expression.
3049 ///
3050 /// This is either the definition of a concept, or the body of a requires
3051 /// clause. It returns, when the parsing is complete, or the expression is
3052 /// incorrect.
3053 void UnwrappedLineParser::parseConstraintExpression() {
3054   // The special handling for lambdas is needed since tryToParseLambda() eats a
3055   // token and if a requires expression is the last part of a requires clause
3056   // and followed by an attribute like [[nodiscard]] the ClosesRequiresClause is
3057   // not set on the correct token. Thus we need to be aware if we even expect a
3058   // lambda to be possible.
3059   // template <typename T> requires requires { ... } [[nodiscard]] ...;
3060   bool LambdaNextTimeAllowed = true;
3061   do {
3062     bool LambdaThisTimeAllowed = std::exchange(LambdaNextTimeAllowed, false);
3063 
3064     switch (FormatTok->Tok.getKind()) {
3065     case tok::kw_requires: {
3066       auto RequiresToken = FormatTok;
3067       nextToken();
3068       parseRequiresExpression(RequiresToken);
3069       break;
3070     }
3071 
3072     case tok::l_paren:
3073       parseParens(/*AmpAmpTokenType=*/TT_BinaryOperator);
3074       break;
3075 
3076     case tok::l_square:
3077       if (!LambdaThisTimeAllowed || !tryToParseLambda())
3078         return;
3079       break;
3080 
3081     case tok::identifier:
3082       // We need to differentiate identifiers for a template deduction guide,
3083       // variables, or function return types (the constraint expression has
3084       // ended before that), and basically all other cases. But it's easier to
3085       // check the other way around.
3086       assert(FormatTok->Previous);
3087       switch (FormatTok->Previous->Tok.getKind()) {
3088       case tok::coloncolon:  // Nested identifier.
3089       case tok::ampamp:      // Start of a function or variable for the
3090       case tok::pipepipe:    // constraint expression.
3091       case tok::kw_requires: // Initial identifier of a requires clause.
3092       case tok::equal:       // Initial identifier of a concept declaration.
3093         break;
3094       default:
3095         return;
3096       }
3097 
3098       // Read identifier with optional template declaration.
3099       nextToken();
3100       if (FormatTok->is(tok::less))
3101         parseBracedList(/*ContinueOnSemicolons=*/false, /*IsEnum=*/false,
3102                         /*ClosingBraceKind=*/tok::greater);
3103       break;
3104 
3105     case tok::kw_const:
3106     case tok::semi:
3107     case tok::kw_class:
3108     case tok::kw_struct:
3109     case tok::kw_union:
3110       return;
3111 
3112     case tok::l_brace:
3113       // Potential function body.
3114       return;
3115 
3116     case tok::ampamp:
3117     case tok::pipepipe:
3118       FormatTok->setFinalizedType(TT_BinaryOperator);
3119       nextToken();
3120       LambdaNextTimeAllowed = true;
3121       break;
3122 
3123     case tok::comma:
3124     case tok::comment:
3125       LambdaNextTimeAllowed = LambdaThisTimeAllowed;
3126       nextToken();
3127       break;
3128 
3129     case tok::kw_sizeof:
3130     case tok::greater:
3131     case tok::greaterequal:
3132     case tok::greatergreater:
3133     case tok::less:
3134     case tok::lessequal:
3135     case tok::lessless:
3136     case tok::equalequal:
3137     case tok::exclaim:
3138     case tok::exclaimequal:
3139     case tok::plus:
3140     case tok::minus:
3141     case tok::star:
3142     case tok::slash:
3143     case tok::kw_decltype:
3144       LambdaNextTimeAllowed = true;
3145       // Just eat them.
3146       nextToken();
3147       break;
3148 
3149     case tok::numeric_constant:
3150     case tok::coloncolon:
3151     case tok::kw_true:
3152     case tok::kw_false:
3153       // Just eat them.
3154       nextToken();
3155       break;
3156 
3157     case tok::kw_static_cast:
3158     case tok::kw_const_cast:
3159     case tok::kw_reinterpret_cast:
3160     case tok::kw_dynamic_cast:
3161       nextToken();
3162       if (!FormatTok->is(tok::less))
3163         return;
3164 
3165       parseBracedList(/*ContinueOnSemicolons=*/false, /*IsEnum=*/false,
3166                       /*ClosingBraceKind=*/tok::greater);
3167       break;
3168 
3169     case tok::kw_bool:
3170       // bool is only allowed if it is directly followed by a paren for a cast:
3171       // concept C = bool(...);
3172       // and bool is the only type, all other types as cast must be inside a
3173       // cast to bool an thus are handled by the other cases.
3174       nextToken();
3175       if (FormatTok->isNot(tok::l_paren))
3176         return;
3177       parseParens();
3178       break;
3179 
3180     default:
3181       return;
3182     }
3183   } while (!eof());
3184 }
3185 
3186 bool UnwrappedLineParser::parseEnum() {
3187   const FormatToken &InitialToken = *FormatTok;
3188 
3189   // Won't be 'enum' for NS_ENUMs.
3190   if (FormatTok->is(tok::kw_enum))
3191     nextToken();
3192 
3193   // In TypeScript, "enum" can also be used as property name, e.g. in interface
3194   // declarations. An "enum" keyword followed by a colon would be a syntax
3195   // error and thus assume it is just an identifier.
3196   if (Style.isJavaScript() && FormatTok->isOneOf(tok::colon, tok::question))
3197     return false;
3198 
3199   // In protobuf, "enum" can be used as a field name.
3200   if (Style.Language == FormatStyle::LK_Proto && FormatTok->is(tok::equal))
3201     return false;
3202 
3203   // Eat up enum class ...
3204   if (FormatTok->isOneOf(tok::kw_class, tok::kw_struct))
3205     nextToken();
3206 
3207   while (FormatTok->Tok.getIdentifierInfo() ||
3208          FormatTok->isOneOf(tok::colon, tok::coloncolon, tok::less,
3209                             tok::greater, tok::comma, tok::question)) {
3210     nextToken();
3211     // We can have macros or attributes in between 'enum' and the enum name.
3212     if (FormatTok->is(tok::l_paren))
3213       parseParens();
3214     if (FormatTok->is(tok::identifier)) {
3215       nextToken();
3216       // If there are two identifiers in a row, this is likely an elaborate
3217       // return type. In Java, this can be "implements", etc.
3218       if (Style.isCpp() && FormatTok->is(tok::identifier))
3219         return false;
3220     }
3221   }
3222 
3223   // Just a declaration or something is wrong.
3224   if (FormatTok->isNot(tok::l_brace))
3225     return true;
3226   FormatTok->setFinalizedType(TT_EnumLBrace);
3227   FormatTok->setBlockKind(BK_Block);
3228 
3229   if (Style.Language == FormatStyle::LK_Java) {
3230     // Java enums are different.
3231     parseJavaEnumBody();
3232     return true;
3233   }
3234   if (Style.Language == FormatStyle::LK_Proto) {
3235     parseBlock(/*MustBeDeclaration=*/true);
3236     return true;
3237   }
3238 
3239   if (!Style.AllowShortEnumsOnASingleLine &&
3240       ShouldBreakBeforeBrace(Style, InitialToken))
3241     addUnwrappedLine();
3242   // Parse enum body.
3243   nextToken();
3244   if (!Style.AllowShortEnumsOnASingleLine) {
3245     addUnwrappedLine();
3246     Line->Level += 1;
3247   }
3248   bool HasError = !parseBracedList(/*ContinueOnSemicolons=*/true,
3249                                    /*IsEnum=*/true);
3250   if (!Style.AllowShortEnumsOnASingleLine)
3251     Line->Level -= 1;
3252   if (HasError) {
3253     if (FormatTok->is(tok::semi))
3254       nextToken();
3255     addUnwrappedLine();
3256   }
3257   return true;
3258 
3259   // There is no addUnwrappedLine() here so that we fall through to parsing a
3260   // structural element afterwards. Thus, in "enum A {} n, m;",
3261   // "} n, m;" will end up in one unwrapped line.
3262 }
3263 
3264 bool UnwrappedLineParser::parseStructLike() {
3265   // parseRecord falls through and does not yet add an unwrapped line as a
3266   // record declaration or definition can start a structural element.
3267   parseRecord();
3268   // This does not apply to Java, JavaScript and C#.
3269   if (Style.Language == FormatStyle::LK_Java || Style.isJavaScript() ||
3270       Style.isCSharp()) {
3271     if (FormatTok->is(tok::semi))
3272       nextToken();
3273     addUnwrappedLine();
3274     return true;
3275   }
3276   return false;
3277 }
3278 
3279 namespace {
3280 // A class used to set and restore the Token position when peeking
3281 // ahead in the token source.
3282 class ScopedTokenPosition {
3283   unsigned StoredPosition;
3284   FormatTokenSource *Tokens;
3285 
3286 public:
3287   ScopedTokenPosition(FormatTokenSource *Tokens) : Tokens(Tokens) {
3288     assert(Tokens && "Tokens expected to not be null");
3289     StoredPosition = Tokens->getPosition();
3290   }
3291 
3292   ~ScopedTokenPosition() { Tokens->setPosition(StoredPosition); }
3293 };
3294 } // namespace
3295 
3296 // Look to see if we have [[ by looking ahead, if
3297 // its not then rewind to the original position.
3298 bool UnwrappedLineParser::tryToParseSimpleAttribute() {
3299   ScopedTokenPosition AutoPosition(Tokens);
3300   FormatToken *Tok = Tokens->getNextToken();
3301   // We already read the first [ check for the second.
3302   if (!Tok->is(tok::l_square))
3303     return false;
3304   // Double check that the attribute is just something
3305   // fairly simple.
3306   while (Tok->isNot(tok::eof)) {
3307     if (Tok->is(tok::r_square))
3308       break;
3309     Tok = Tokens->getNextToken();
3310   }
3311   if (Tok->is(tok::eof))
3312     return false;
3313   Tok = Tokens->getNextToken();
3314   if (!Tok->is(tok::r_square))
3315     return false;
3316   Tok = Tokens->getNextToken();
3317   if (Tok->is(tok::semi))
3318     return false;
3319   return true;
3320 }
3321 
3322 void UnwrappedLineParser::parseJavaEnumBody() {
3323   // Determine whether the enum is simple, i.e. does not have a semicolon or
3324   // constants with class bodies. Simple enums can be formatted like braced
3325   // lists, contracted to a single line, etc.
3326   unsigned StoredPosition = Tokens->getPosition();
3327   bool IsSimple = true;
3328   FormatToken *Tok = Tokens->getNextToken();
3329   while (!Tok->is(tok::eof)) {
3330     if (Tok->is(tok::r_brace))
3331       break;
3332     if (Tok->isOneOf(tok::l_brace, tok::semi)) {
3333       IsSimple = false;
3334       break;
3335     }
3336     // FIXME: This will also mark enums with braces in the arguments to enum
3337     // constants as "not simple". This is probably fine in practice, though.
3338     Tok = Tokens->getNextToken();
3339   }
3340   FormatTok = Tokens->setPosition(StoredPosition);
3341 
3342   if (IsSimple) {
3343     nextToken();
3344     parseBracedList();
3345     addUnwrappedLine();
3346     return;
3347   }
3348 
3349   // Parse the body of a more complex enum.
3350   // First add a line for everything up to the "{".
3351   nextToken();
3352   addUnwrappedLine();
3353   ++Line->Level;
3354 
3355   // Parse the enum constants.
3356   while (FormatTok) {
3357     if (FormatTok->is(tok::l_brace)) {
3358       // Parse the constant's class body.
3359       parseBlock(/*MustBeDeclaration=*/true, /*AddLevels=*/1u,
3360                  /*MunchSemi=*/false);
3361     } else if (FormatTok->is(tok::l_paren)) {
3362       parseParens();
3363     } else if (FormatTok->is(tok::comma)) {
3364       nextToken();
3365       addUnwrappedLine();
3366     } else if (FormatTok->is(tok::semi)) {
3367       nextToken();
3368       addUnwrappedLine();
3369       break;
3370     } else if (FormatTok->is(tok::r_brace)) {
3371       addUnwrappedLine();
3372       break;
3373     } else {
3374       nextToken();
3375     }
3376   }
3377 
3378   // Parse the class body after the enum's ";" if any.
3379   parseLevel(/*HasOpeningBrace=*/true, /*CanContainBracedList=*/true);
3380   nextToken();
3381   --Line->Level;
3382   addUnwrappedLine();
3383 }
3384 
3385 void UnwrappedLineParser::parseRecord(bool ParseAsExpr) {
3386   const FormatToken &InitialToken = *FormatTok;
3387   nextToken();
3388 
3389   // The actual identifier can be a nested name specifier, and in macros
3390   // it is often token-pasted.
3391   // An [[attribute]] can be before the identifier.
3392   while (FormatTok->isOneOf(tok::identifier, tok::coloncolon, tok::hashhash,
3393                             tok::kw___attribute, tok::kw___declspec,
3394                             tok::kw_alignas, tok::l_square, tok::r_square) ||
3395          ((Style.Language == FormatStyle::LK_Java || Style.isJavaScript()) &&
3396           FormatTok->isOneOf(tok::period, tok::comma))) {
3397     if (Style.isJavaScript() &&
3398         FormatTok->isOneOf(Keywords.kw_extends, Keywords.kw_implements)) {
3399       // JavaScript/TypeScript supports inline object types in
3400       // extends/implements positions:
3401       //     class Foo implements {bar: number} { }
3402       nextToken();
3403       if (FormatTok->is(tok::l_brace)) {
3404         tryToParseBracedList();
3405         continue;
3406       }
3407     }
3408     bool IsNonMacroIdentifier =
3409         FormatTok->is(tok::identifier) &&
3410         FormatTok->TokenText != FormatTok->TokenText.upper();
3411     nextToken();
3412     // We can have macros or attributes in between 'class' and the class name.
3413     if (!IsNonMacroIdentifier) {
3414       if (FormatTok->is(tok::l_paren)) {
3415         parseParens();
3416       } else if (FormatTok->is(TT_AttributeSquare)) {
3417         parseSquare();
3418         // Consume the closing TT_AttributeSquare.
3419         if (FormatTok->Next && FormatTok->is(TT_AttributeSquare))
3420           nextToken();
3421       }
3422     }
3423   }
3424 
3425   // Note that parsing away template declarations here leads to incorrectly
3426   // accepting function declarations as record declarations.
3427   // In general, we cannot solve this problem. Consider:
3428   // class A<int> B() {}
3429   // which can be a function definition or a class definition when B() is a
3430   // macro. If we find enough real-world cases where this is a problem, we
3431   // can parse for the 'template' keyword in the beginning of the statement,
3432   // and thus rule out the record production in case there is no template
3433   // (this would still leave us with an ambiguity between template function
3434   // and class declarations).
3435   if (FormatTok->isOneOf(tok::colon, tok::less)) {
3436     while (!eof()) {
3437       if (FormatTok->is(tok::l_brace)) {
3438         calculateBraceTypes(/*ExpectClassBody=*/true);
3439         if (!tryToParseBracedList())
3440           break;
3441       }
3442       if (FormatTok->is(tok::l_square)) {
3443         FormatToken *Previous = FormatTok->Previous;
3444         if (!Previous ||
3445             !(Previous->is(tok::r_paren) || Previous->isTypeOrIdentifier())) {
3446           // Don't try parsing a lambda if we had a closing parenthesis before,
3447           // it was probably a pointer to an array: int (*)[].
3448           if (!tryToParseLambda())
3449             break;
3450         }
3451       }
3452       if (FormatTok->is(tok::semi))
3453         return;
3454       if (Style.isCSharp() && FormatTok->is(Keywords.kw_where)) {
3455         addUnwrappedLine();
3456         nextToken();
3457         parseCSharpGenericTypeConstraint();
3458         break;
3459       }
3460       nextToken();
3461     }
3462   }
3463 
3464   auto GetBraceType = [](const FormatToken &RecordTok) {
3465     switch (RecordTok.Tok.getKind()) {
3466     case tok::kw_class:
3467       return TT_ClassLBrace;
3468     case tok::kw_struct:
3469       return TT_StructLBrace;
3470     case tok::kw_union:
3471       return TT_UnionLBrace;
3472     default:
3473       // Useful for e.g. interface.
3474       return TT_RecordLBrace;
3475     }
3476   };
3477   if (FormatTok->is(tok::l_brace)) {
3478     FormatTok->setFinalizedType(GetBraceType(InitialToken));
3479     if (ParseAsExpr) {
3480       parseChildBlock();
3481     } else {
3482       if (ShouldBreakBeforeBrace(Style, InitialToken))
3483         addUnwrappedLine();
3484 
3485       unsigned AddLevels = Style.IndentAccessModifiers ? 2u : 1u;
3486       parseBlock(/*MustBeDeclaration=*/true, AddLevels, /*MunchSemi=*/false);
3487     }
3488   }
3489   // There is no addUnwrappedLine() here so that we fall through to parsing a
3490   // structural element afterwards. Thus, in "class A {} n, m;",
3491   // "} n, m;" will end up in one unwrapped line.
3492 }
3493 
3494 void UnwrappedLineParser::parseObjCMethod() {
3495   assert(FormatTok->isOneOf(tok::l_paren, tok::identifier) &&
3496          "'(' or identifier expected.");
3497   do {
3498     if (FormatTok->is(tok::semi)) {
3499       nextToken();
3500       addUnwrappedLine();
3501       return;
3502     } else if (FormatTok->is(tok::l_brace)) {
3503       if (Style.BraceWrapping.AfterFunction)
3504         addUnwrappedLine();
3505       parseBlock();
3506       addUnwrappedLine();
3507       return;
3508     } else {
3509       nextToken();
3510     }
3511   } while (!eof());
3512 }
3513 
3514 void UnwrappedLineParser::parseObjCProtocolList() {
3515   assert(FormatTok->is(tok::less) && "'<' expected.");
3516   do {
3517     nextToken();
3518     // Early exit in case someone forgot a close angle.
3519     if (FormatTok->isOneOf(tok::semi, tok::l_brace) ||
3520         FormatTok->isObjCAtKeyword(tok::objc_end))
3521       return;
3522   } while (!eof() && FormatTok->isNot(tok::greater));
3523   nextToken(); // Skip '>'.
3524 }
3525 
3526 void UnwrappedLineParser::parseObjCUntilAtEnd() {
3527   do {
3528     if (FormatTok->isObjCAtKeyword(tok::objc_end)) {
3529       nextToken();
3530       addUnwrappedLine();
3531       break;
3532     }
3533     if (FormatTok->is(tok::l_brace)) {
3534       parseBlock();
3535       // In ObjC interfaces, nothing should be following the "}".
3536       addUnwrappedLine();
3537     } else if (FormatTok->is(tok::r_brace)) {
3538       // Ignore stray "}". parseStructuralElement doesn't consume them.
3539       nextToken();
3540       addUnwrappedLine();
3541     } else if (FormatTok->isOneOf(tok::minus, tok::plus)) {
3542       nextToken();
3543       parseObjCMethod();
3544     } else {
3545       parseStructuralElement();
3546     }
3547   } while (!eof());
3548 }
3549 
3550 void UnwrappedLineParser::parseObjCInterfaceOrImplementation() {
3551   assert(FormatTok->Tok.getObjCKeywordID() == tok::objc_interface ||
3552          FormatTok->Tok.getObjCKeywordID() == tok::objc_implementation);
3553   nextToken();
3554   nextToken(); // interface name
3555 
3556   // @interface can be followed by a lightweight generic
3557   // specialization list, then either a base class or a category.
3558   if (FormatTok->is(tok::less))
3559     parseObjCLightweightGenerics();
3560   if (FormatTok->is(tok::colon)) {
3561     nextToken();
3562     nextToken(); // base class name
3563     // The base class can also have lightweight generics applied to it.
3564     if (FormatTok->is(tok::less))
3565       parseObjCLightweightGenerics();
3566   } else if (FormatTok->is(tok::l_paren))
3567     // Skip category, if present.
3568     parseParens();
3569 
3570   if (FormatTok->is(tok::less))
3571     parseObjCProtocolList();
3572 
3573   if (FormatTok->is(tok::l_brace)) {
3574     if (Style.BraceWrapping.AfterObjCDeclaration)
3575       addUnwrappedLine();
3576     parseBlock(/*MustBeDeclaration=*/true);
3577   }
3578 
3579   // With instance variables, this puts '}' on its own line.  Without instance
3580   // variables, this ends the @interface line.
3581   addUnwrappedLine();
3582 
3583   parseObjCUntilAtEnd();
3584 }
3585 
3586 void UnwrappedLineParser::parseObjCLightweightGenerics() {
3587   assert(FormatTok->is(tok::less));
3588   // Unlike protocol lists, generic parameterizations support
3589   // nested angles:
3590   //
3591   // @interface Foo<ValueType : id <NSCopying, NSSecureCoding>> :
3592   //     NSObject <NSCopying, NSSecureCoding>
3593   //
3594   // so we need to count how many open angles we have left.
3595   unsigned NumOpenAngles = 1;
3596   do {
3597     nextToken();
3598     // Early exit in case someone forgot a close angle.
3599     if (FormatTok->isOneOf(tok::semi, tok::l_brace) ||
3600         FormatTok->isObjCAtKeyword(tok::objc_end))
3601       break;
3602     if (FormatTok->is(tok::less))
3603       ++NumOpenAngles;
3604     else if (FormatTok->is(tok::greater)) {
3605       assert(NumOpenAngles > 0 && "'>' makes NumOpenAngles negative");
3606       --NumOpenAngles;
3607     }
3608   } while (!eof() && NumOpenAngles != 0);
3609   nextToken(); // Skip '>'.
3610 }
3611 
3612 // Returns true for the declaration/definition form of @protocol,
3613 // false for the expression form.
3614 bool UnwrappedLineParser::parseObjCProtocol() {
3615   assert(FormatTok->Tok.getObjCKeywordID() == tok::objc_protocol);
3616   nextToken();
3617 
3618   if (FormatTok->is(tok::l_paren))
3619     // The expression form of @protocol, e.g. "Protocol* p = @protocol(foo);".
3620     return false;
3621 
3622   // The definition/declaration form,
3623   // @protocol Foo
3624   // - (int)someMethod;
3625   // @end
3626 
3627   nextToken(); // protocol name
3628 
3629   if (FormatTok->is(tok::less))
3630     parseObjCProtocolList();
3631 
3632   // Check for protocol declaration.
3633   if (FormatTok->is(tok::semi)) {
3634     nextToken();
3635     addUnwrappedLine();
3636     return true;
3637   }
3638 
3639   addUnwrappedLine();
3640   parseObjCUntilAtEnd();
3641   return true;
3642 }
3643 
3644 void UnwrappedLineParser::parseJavaScriptEs6ImportExport() {
3645   bool IsImport = FormatTok->is(Keywords.kw_import);
3646   assert(IsImport || FormatTok->is(tok::kw_export));
3647   nextToken();
3648 
3649   // Consume the "default" in "export default class/function".
3650   if (FormatTok->is(tok::kw_default))
3651     nextToken();
3652 
3653   // Consume "async function", "function" and "default function", so that these
3654   // get parsed as free-standing JS functions, i.e. do not require a trailing
3655   // semicolon.
3656   if (FormatTok->is(Keywords.kw_async))
3657     nextToken();
3658   if (FormatTok->is(Keywords.kw_function)) {
3659     nextToken();
3660     return;
3661   }
3662 
3663   // For imports, `export *`, `export {...}`, consume the rest of the line up
3664   // to the terminating `;`. For everything else, just return and continue
3665   // parsing the structural element, i.e. the declaration or expression for
3666   // `export default`.
3667   if (!IsImport && !FormatTok->isOneOf(tok::l_brace, tok::star) &&
3668       !FormatTok->isStringLiteral())
3669     return;
3670 
3671   while (!eof()) {
3672     if (FormatTok->is(tok::semi))
3673       return;
3674     if (Line->Tokens.empty()) {
3675       // Common issue: Automatic Semicolon Insertion wrapped the line, so the
3676       // import statement should terminate.
3677       return;
3678     }
3679     if (FormatTok->is(tok::l_brace)) {
3680       FormatTok->setBlockKind(BK_Block);
3681       nextToken();
3682       parseBracedList();
3683     } else {
3684       nextToken();
3685     }
3686   }
3687 }
3688 
3689 void UnwrappedLineParser::parseStatementMacro() {
3690   nextToken();
3691   if (FormatTok->is(tok::l_paren))
3692     parseParens();
3693   if (FormatTok->is(tok::semi))
3694     nextToken();
3695   addUnwrappedLine();
3696 }
3697 
3698 LLVM_ATTRIBUTE_UNUSED static void printDebugInfo(const UnwrappedLine &Line,
3699                                                  StringRef Prefix = "") {
3700   llvm::dbgs() << Prefix << "Line(" << Line.Level
3701                << ", FSC=" << Line.FirstStartColumn << ")"
3702                << (Line.InPPDirective ? " MACRO" : "") << ": ";
3703   for (const auto &Node : Line.Tokens) {
3704     llvm::dbgs() << Node.Tok->Tok.getName() << "["
3705                  << "T=" << static_cast<unsigned>(Node.Tok->getType())
3706                  << ", OC=" << Node.Tok->OriginalColumn << "] ";
3707   }
3708   for (const auto &Node : Line.Tokens)
3709     for (const auto &ChildNode : Node.Children)
3710       printDebugInfo(ChildNode, "\nChild: ");
3711 
3712   llvm::dbgs() << "\n";
3713 }
3714 
3715 void UnwrappedLineParser::addUnwrappedLine(LineLevel AdjustLevel) {
3716   if (Line->Tokens.empty())
3717     return;
3718   LLVM_DEBUG({
3719     if (CurrentLines == &Lines)
3720       printDebugInfo(*Line);
3721   });
3722 
3723   // If this line closes a block when in Whitesmiths mode, remember that
3724   // information so that the level can be decreased after the line is added.
3725   // This has to happen after the addition of the line since the line itself
3726   // needs to be indented.
3727   bool ClosesWhitesmithsBlock =
3728       Line->MatchingOpeningBlockLineIndex != UnwrappedLine::kInvalidIndex &&
3729       Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths;
3730 
3731   CurrentLines->push_back(std::move(*Line));
3732   Line->Tokens.clear();
3733   Line->MatchingOpeningBlockLineIndex = UnwrappedLine::kInvalidIndex;
3734   Line->FirstStartColumn = 0;
3735 
3736   if (ClosesWhitesmithsBlock && AdjustLevel == LineLevel::Remove)
3737     --Line->Level;
3738   if (CurrentLines == &Lines && !PreprocessorDirectives.empty()) {
3739     CurrentLines->append(
3740         std::make_move_iterator(PreprocessorDirectives.begin()),
3741         std::make_move_iterator(PreprocessorDirectives.end()));
3742     PreprocessorDirectives.clear();
3743   }
3744   // Disconnect the current token from the last token on the previous line.
3745   FormatTok->Previous = nullptr;
3746 }
3747 
3748 bool UnwrappedLineParser::eof() const { return FormatTok->is(tok::eof); }
3749 
3750 bool UnwrappedLineParser::isOnNewLine(const FormatToken &FormatTok) {
3751   return (Line->InPPDirective || FormatTok.HasUnescapedNewline) &&
3752          FormatTok.NewlinesBefore > 0;
3753 }
3754 
3755 // Checks if \p FormatTok is a line comment that continues the line comment
3756 // section on \p Line.
3757 static bool
3758 continuesLineCommentSection(const FormatToken &FormatTok,
3759                             const UnwrappedLine &Line,
3760                             const llvm::Regex &CommentPragmasRegex) {
3761   if (Line.Tokens.empty())
3762     return false;
3763 
3764   StringRef IndentContent = FormatTok.TokenText;
3765   if (FormatTok.TokenText.startswith("//") ||
3766       FormatTok.TokenText.startswith("/*"))
3767     IndentContent = FormatTok.TokenText.substr(2);
3768   if (CommentPragmasRegex.match(IndentContent))
3769     return false;
3770 
3771   // If Line starts with a line comment, then FormatTok continues the comment
3772   // section if its original column is greater or equal to the original start
3773   // column of the line.
3774   //
3775   // Define the min column token of a line as follows: if a line ends in '{' or
3776   // contains a '{' followed by a line comment, then the min column token is
3777   // that '{'. Otherwise, the min column token of the line is the first token of
3778   // the line.
3779   //
3780   // If Line starts with a token other than a line comment, then FormatTok
3781   // continues the comment section if its original column is greater than the
3782   // original start column of the min column token of the line.
3783   //
3784   // For example, the second line comment continues the first in these cases:
3785   //
3786   // // first line
3787   // // second line
3788   //
3789   // and:
3790   //
3791   // // first line
3792   //  // second line
3793   //
3794   // and:
3795   //
3796   // int i; // first line
3797   //  // second line
3798   //
3799   // and:
3800   //
3801   // do { // first line
3802   //      // second line
3803   //   int i;
3804   // } while (true);
3805   //
3806   // and:
3807   //
3808   // enum {
3809   //   a, // first line
3810   //    // second line
3811   //   b
3812   // };
3813   //
3814   // The second line comment doesn't continue the first in these cases:
3815   //
3816   //   // first line
3817   //  // second line
3818   //
3819   // and:
3820   //
3821   // int i; // first line
3822   // // second line
3823   //
3824   // and:
3825   //
3826   // do { // first line
3827   //   // second line
3828   //   int i;
3829   // } while (true);
3830   //
3831   // and:
3832   //
3833   // enum {
3834   //   a, // first line
3835   //   // second line
3836   // };
3837   const FormatToken *MinColumnToken = Line.Tokens.front().Tok;
3838 
3839   // Scan for '{//'. If found, use the column of '{' as a min column for line
3840   // comment section continuation.
3841   const FormatToken *PreviousToken = nullptr;
3842   for (const UnwrappedLineNode &Node : Line.Tokens) {
3843     if (PreviousToken && PreviousToken->is(tok::l_brace) &&
3844         isLineComment(*Node.Tok)) {
3845       MinColumnToken = PreviousToken;
3846       break;
3847     }
3848     PreviousToken = Node.Tok;
3849 
3850     // Grab the last newline preceding a token in this unwrapped line.
3851     if (Node.Tok->NewlinesBefore > 0)
3852       MinColumnToken = Node.Tok;
3853   }
3854   if (PreviousToken && PreviousToken->is(tok::l_brace))
3855     MinColumnToken = PreviousToken;
3856 
3857   return continuesLineComment(FormatTok, /*Previous=*/Line.Tokens.back().Tok,
3858                               MinColumnToken);
3859 }
3860 
3861 void UnwrappedLineParser::flushComments(bool NewlineBeforeNext) {
3862   bool JustComments = Line->Tokens.empty();
3863   for (FormatToken *Tok : CommentsBeforeNextToken) {
3864     // Line comments that belong to the same line comment section are put on the
3865     // same line since later we might want to reflow content between them.
3866     // Additional fine-grained breaking of line comment sections is controlled
3867     // by the class BreakableLineCommentSection in case it is desirable to keep
3868     // several line comment sections in the same unwrapped line.
3869     //
3870     // FIXME: Consider putting separate line comment sections as children to the
3871     // unwrapped line instead.
3872     Tok->ContinuesLineCommentSection =
3873         continuesLineCommentSection(*Tok, *Line, CommentPragmasRegex);
3874     if (isOnNewLine(*Tok) && JustComments && !Tok->ContinuesLineCommentSection)
3875       addUnwrappedLine();
3876     pushToken(Tok);
3877   }
3878   if (NewlineBeforeNext && JustComments)
3879     addUnwrappedLine();
3880   CommentsBeforeNextToken.clear();
3881 }
3882 
3883 void UnwrappedLineParser::nextToken(int LevelDifference) {
3884   if (eof())
3885     return;
3886   flushComments(isOnNewLine(*FormatTok));
3887   pushToken(FormatTok);
3888   FormatToken *Previous = FormatTok;
3889   if (!Style.isJavaScript())
3890     readToken(LevelDifference);
3891   else
3892     readTokenWithJavaScriptASI();
3893   FormatTok->Previous = Previous;
3894 }
3895 
3896 void UnwrappedLineParser::distributeComments(
3897     const SmallVectorImpl<FormatToken *> &Comments,
3898     const FormatToken *NextTok) {
3899   // Whether or not a line comment token continues a line is controlled by
3900   // the method continuesLineCommentSection, with the following caveat:
3901   //
3902   // Define a trail of Comments to be a nonempty proper postfix of Comments such
3903   // that each comment line from the trail is aligned with the next token, if
3904   // the next token exists. If a trail exists, the beginning of the maximal
3905   // trail is marked as a start of a new comment section.
3906   //
3907   // For example in this code:
3908   //
3909   // int a; // line about a
3910   //   // line 1 about b
3911   //   // line 2 about b
3912   //   int b;
3913   //
3914   // the two lines about b form a maximal trail, so there are two sections, the
3915   // first one consisting of the single comment "// line about a" and the
3916   // second one consisting of the next two comments.
3917   if (Comments.empty())
3918     return;
3919   bool ShouldPushCommentsInCurrentLine = true;
3920   bool HasTrailAlignedWithNextToken = false;
3921   unsigned StartOfTrailAlignedWithNextToken = 0;
3922   if (NextTok) {
3923     // We are skipping the first element intentionally.
3924     for (unsigned i = Comments.size() - 1; i > 0; --i) {
3925       if (Comments[i]->OriginalColumn == NextTok->OriginalColumn) {
3926         HasTrailAlignedWithNextToken = true;
3927         StartOfTrailAlignedWithNextToken = i;
3928       }
3929     }
3930   }
3931   for (unsigned i = 0, e = Comments.size(); i < e; ++i) {
3932     FormatToken *FormatTok = Comments[i];
3933     if (HasTrailAlignedWithNextToken && i == StartOfTrailAlignedWithNextToken) {
3934       FormatTok->ContinuesLineCommentSection = false;
3935     } else {
3936       FormatTok->ContinuesLineCommentSection =
3937           continuesLineCommentSection(*FormatTok, *Line, CommentPragmasRegex);
3938     }
3939     if (!FormatTok->ContinuesLineCommentSection &&
3940         (isOnNewLine(*FormatTok) || FormatTok->IsFirst))
3941       ShouldPushCommentsInCurrentLine = false;
3942     if (ShouldPushCommentsInCurrentLine)
3943       pushToken(FormatTok);
3944     else
3945       CommentsBeforeNextToken.push_back(FormatTok);
3946   }
3947 }
3948 
3949 void UnwrappedLineParser::readToken(int LevelDifference) {
3950   SmallVector<FormatToken *, 1> Comments;
3951   bool PreviousWasComment = false;
3952   bool FirstNonCommentOnLine = false;
3953   do {
3954     FormatTok = Tokens->getNextToken();
3955     assert(FormatTok);
3956     while (FormatTok->getType() == TT_ConflictStart ||
3957            FormatTok->getType() == TT_ConflictEnd ||
3958            FormatTok->getType() == TT_ConflictAlternative) {
3959       if (FormatTok->getType() == TT_ConflictStart)
3960         conditionalCompilationStart(/*Unreachable=*/false);
3961       else if (FormatTok->getType() == TT_ConflictAlternative)
3962         conditionalCompilationAlternative();
3963       else if (FormatTok->getType() == TT_ConflictEnd)
3964         conditionalCompilationEnd();
3965       FormatTok = Tokens->getNextToken();
3966       FormatTok->MustBreakBefore = true;
3967     }
3968 
3969     auto IsFirstNonCommentOnLine = [](bool FirstNonCommentOnLine,
3970                                       const FormatToken &Tok,
3971                                       bool PreviousWasComment) {
3972       auto IsFirstOnLine = [](const FormatToken &Tok) {
3973         return Tok.HasUnescapedNewline || Tok.IsFirst;
3974       };
3975 
3976       // Consider preprocessor directives preceded by block comments as first
3977       // on line.
3978       if (PreviousWasComment)
3979         return FirstNonCommentOnLine || IsFirstOnLine(Tok);
3980       return IsFirstOnLine(Tok);
3981     };
3982 
3983     FirstNonCommentOnLine = IsFirstNonCommentOnLine(
3984         FirstNonCommentOnLine, *FormatTok, PreviousWasComment);
3985     PreviousWasComment = FormatTok->is(tok::comment);
3986 
3987     while (!Line->InPPDirective && FormatTok->is(tok::hash) &&
3988            FirstNonCommentOnLine) {
3989       distributeComments(Comments, FormatTok);
3990       Comments.clear();
3991       // If there is an unfinished unwrapped line, we flush the preprocessor
3992       // directives only after that unwrapped line was finished later.
3993       bool SwitchToPreprocessorLines = !Line->Tokens.empty();
3994       ScopedLineState BlockState(*this, SwitchToPreprocessorLines);
3995       assert((LevelDifference >= 0 ||
3996               static_cast<unsigned>(-LevelDifference) <= Line->Level) &&
3997              "LevelDifference makes Line->Level negative");
3998       Line->Level += LevelDifference;
3999       // Comments stored before the preprocessor directive need to be output
4000       // before the preprocessor directive, at the same level as the
4001       // preprocessor directive, as we consider them to apply to the directive.
4002       if (Style.IndentPPDirectives == FormatStyle::PPDIS_BeforeHash &&
4003           PPBranchLevel > 0)
4004         Line->Level += PPBranchLevel;
4005       flushComments(isOnNewLine(*FormatTok));
4006       parsePPDirective();
4007       PreviousWasComment = FormatTok->is(tok::comment);
4008       FirstNonCommentOnLine = IsFirstNonCommentOnLine(
4009           FirstNonCommentOnLine, *FormatTok, PreviousWasComment);
4010     }
4011 
4012     if (!PPStack.empty() && (PPStack.back().Kind == PP_Unreachable) &&
4013         !Line->InPPDirective)
4014       continue;
4015 
4016     if (!FormatTok->is(tok::comment)) {
4017       distributeComments(Comments, FormatTok);
4018       Comments.clear();
4019       return;
4020     }
4021 
4022     Comments.push_back(FormatTok);
4023   } while (!eof());
4024 
4025   distributeComments(Comments, nullptr);
4026   Comments.clear();
4027 }
4028 
4029 void UnwrappedLineParser::pushToken(FormatToken *Tok) {
4030   Line->Tokens.push_back(UnwrappedLineNode(Tok));
4031   if (MustBreakBeforeNextToken) {
4032     Line->Tokens.back().Tok->MustBreakBefore = true;
4033     MustBreakBeforeNextToken = false;
4034   }
4035 }
4036 
4037 } // end namespace format
4038 } // end namespace clang
4039