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