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