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();
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->BlockKind = BK_BracedInit;
476         else if (PrevTok->is(tok::r_paren))
477           // `) { }` can only occur in function or method declarations in JS.
478           Tok->BlockKind = BK_Block;
479       } else {
480         Tok->BlockKind = 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()->BlockKind == 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->BlockKind = BK_BracedInit;
528           LBraceStack.back()->BlockKind = BK_BracedInit;
529         } else {
530           Tok->BlockKind = BK_Block;
531           LBraceStack.back()->BlockKind = 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()->BlockKind == BK_Unknown)
549         LBraceStack.back()->BlockKind = 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]->BlockKind == BK_Unknown)
561       LBraceStack[i]->BlockKind = 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, bool AddLevel,
583                                      bool MunchSemi) {
584   assert(FormatTok->isOneOf(tok::l_brace, TT_MacroBlockBegin) &&
585          "'{' or macro block token expected");
586   const bool MacroBlock = FormatTok->is(TT_MacroBlockBegin);
587   FormatTok->BlockKind = BK_Block;
588 
589   size_t PPStartHash = computePPHash();
590 
591   unsigned InitialLevel = Line->Level;
592   nextToken(/*LevelDifference=*/AddLevel ? 1 : 0);
593 
594   if (MacroBlock && FormatTok->is(tok::l_paren))
595     parseParens();
596 
597   size_t NbPreprocessorDirectives =
598       CurrentLines == &Lines ? PreprocessorDirectives.size() : 0;
599   addUnwrappedLine();
600   size_t OpeningLineIndex =
601       CurrentLines->empty()
602           ? (UnwrappedLine::kInvalidIndex)
603           : (CurrentLines->size() - 1 - NbPreprocessorDirectives);
604 
605   ScopedDeclarationState DeclarationState(*Line, DeclarationScopeStack,
606                                           MustBeDeclaration);
607   if (AddLevel)
608     ++Line->Level;
609   parseLevel(/*HasOpeningBrace=*/true);
610 
611   if (eof())
612     return;
613 
614   if (MacroBlock ? !FormatTok->is(TT_MacroBlockEnd)
615                  : !FormatTok->is(tok::r_brace)) {
616     Line->Level = InitialLevel;
617     FormatTok->BlockKind = BK_Block;
618     return;
619   }
620 
621   size_t PPEndHash = computePPHash();
622 
623   // Munch the closing brace.
624   nextToken(/*LevelDifference=*/AddLevel ? -1 : 0);
625 
626   if (MacroBlock && FormatTok->is(tok::l_paren))
627     parseParens();
628 
629   if (MunchSemi && FormatTok->Tok.is(tok::semi))
630     nextToken();
631   Line->Level = InitialLevel;
632 
633   if (PPStartHash == PPEndHash) {
634     Line->MatchingOpeningBlockLineIndex = OpeningLineIndex;
635     if (OpeningLineIndex != UnwrappedLine::kInvalidIndex) {
636       // Update the opening line to add the forward reference as well
637       (*CurrentLines)[OpeningLineIndex].MatchingClosingBlockLineIndex =
638           CurrentLines->size() - 1;
639     }
640   }
641 }
642 
643 static bool isGoogScope(const UnwrappedLine &Line) {
644   // FIXME: Closure-library specific stuff should not be hard-coded but be
645   // configurable.
646   if (Line.Tokens.size() < 4)
647     return false;
648   auto I = Line.Tokens.begin();
649   if (I->Tok->TokenText != "goog")
650     return false;
651   ++I;
652   if (I->Tok->isNot(tok::period))
653     return false;
654   ++I;
655   if (I->Tok->TokenText != "scope")
656     return false;
657   ++I;
658   return I->Tok->is(tok::l_paren);
659 }
660 
661 static bool isIIFE(const UnwrappedLine &Line,
662                    const AdditionalKeywords &Keywords) {
663   // Look for the start of an immediately invoked anonymous function.
664   // https://en.wikipedia.org/wiki/Immediately-invoked_function_expression
665   // This is commonly done in JavaScript to create a new, anonymous scope.
666   // Example: (function() { ... })()
667   if (Line.Tokens.size() < 3)
668     return false;
669   auto I = Line.Tokens.begin();
670   if (I->Tok->isNot(tok::l_paren))
671     return false;
672   ++I;
673   if (I->Tok->isNot(Keywords.kw_function))
674     return false;
675   ++I;
676   return I->Tok->is(tok::l_paren);
677 }
678 
679 static bool ShouldBreakBeforeBrace(const FormatStyle &Style,
680                                    const FormatToken &InitialToken) {
681   if (InitialToken.isOneOf(tok::kw_namespace, TT_NamespaceMacro))
682     return Style.BraceWrapping.AfterNamespace;
683   if (InitialToken.is(tok::kw_class))
684     return Style.BraceWrapping.AfterClass;
685   if (InitialToken.is(tok::kw_union))
686     return Style.BraceWrapping.AfterUnion;
687   if (InitialToken.is(tok::kw_struct))
688     return Style.BraceWrapping.AfterStruct;
689   return false;
690 }
691 
692 void UnwrappedLineParser::parseChildBlock() {
693   FormatTok->BlockKind = BK_Block;
694   nextToken();
695   {
696     bool SkipIndent = (Style.Language == FormatStyle::LK_JavaScript &&
697                        (isGoogScope(*Line) || isIIFE(*Line, Keywords)));
698     ScopedLineState LineState(*this);
699     ScopedDeclarationState DeclarationState(*Line, DeclarationScopeStack,
700                                             /*MustBeDeclaration=*/false);
701     Line->Level += SkipIndent ? 0 : 1;
702     parseLevel(/*HasOpeningBrace=*/true);
703     flushComments(isOnNewLine(*FormatTok));
704     Line->Level -= SkipIndent ? 0 : 1;
705   }
706   nextToken();
707 }
708 
709 void UnwrappedLineParser::parsePPDirective() {
710   assert(FormatTok->Tok.is(tok::hash) && "'#' expected");
711   ScopedMacroState MacroState(*Line, Tokens, FormatTok);
712 
713   nextToken();
714 
715   if (!FormatTok->Tok.getIdentifierInfo()) {
716     parsePPUnknown();
717     return;
718   }
719 
720   switch (FormatTok->Tok.getIdentifierInfo()->getPPKeywordID()) {
721   case tok::pp_define:
722     parsePPDefine();
723     return;
724   case tok::pp_if:
725     parsePPIf(/*IfDef=*/false);
726     break;
727   case tok::pp_ifdef:
728   case tok::pp_ifndef:
729     parsePPIf(/*IfDef=*/true);
730     break;
731   case tok::pp_else:
732     parsePPElse();
733     break;
734   case tok::pp_elif:
735     parsePPElIf();
736     break;
737   case tok::pp_endif:
738     parsePPEndIf();
739     break;
740   default:
741     parsePPUnknown();
742     break;
743   }
744 }
745 
746 void UnwrappedLineParser::conditionalCompilationCondition(bool Unreachable) {
747   size_t Line = CurrentLines->size();
748   if (CurrentLines == &PreprocessorDirectives)
749     Line += Lines.size();
750 
751   if (Unreachable ||
752       (!PPStack.empty() && PPStack.back().Kind == PP_Unreachable))
753     PPStack.push_back({PP_Unreachable, Line});
754   else
755     PPStack.push_back({PP_Conditional, Line});
756 }
757 
758 void UnwrappedLineParser::conditionalCompilationStart(bool Unreachable) {
759   ++PPBranchLevel;
760   assert(PPBranchLevel >= 0 && PPBranchLevel <= (int)PPLevelBranchIndex.size());
761   if (PPBranchLevel == (int)PPLevelBranchIndex.size()) {
762     PPLevelBranchIndex.push_back(0);
763     PPLevelBranchCount.push_back(0);
764   }
765   PPChainBranchIndex.push(0);
766   bool Skip = PPLevelBranchIndex[PPBranchLevel] > 0;
767   conditionalCompilationCondition(Unreachable || Skip);
768 }
769 
770 void UnwrappedLineParser::conditionalCompilationAlternative() {
771   if (!PPStack.empty())
772     PPStack.pop_back();
773   assert(PPBranchLevel < (int)PPLevelBranchIndex.size());
774   if (!PPChainBranchIndex.empty())
775     ++PPChainBranchIndex.top();
776   conditionalCompilationCondition(
777       PPBranchLevel >= 0 && !PPChainBranchIndex.empty() &&
778       PPLevelBranchIndex[PPBranchLevel] != PPChainBranchIndex.top());
779 }
780 
781 void UnwrappedLineParser::conditionalCompilationEnd() {
782   assert(PPBranchLevel < (int)PPLevelBranchIndex.size());
783   if (PPBranchLevel >= 0 && !PPChainBranchIndex.empty()) {
784     if (PPChainBranchIndex.top() + 1 > PPLevelBranchCount[PPBranchLevel]) {
785       PPLevelBranchCount[PPBranchLevel] = PPChainBranchIndex.top() + 1;
786     }
787   }
788   // Guard against #endif's without #if.
789   if (PPBranchLevel > -1)
790     --PPBranchLevel;
791   if (!PPChainBranchIndex.empty())
792     PPChainBranchIndex.pop();
793   if (!PPStack.empty())
794     PPStack.pop_back();
795 }
796 
797 void UnwrappedLineParser::parsePPIf(bool IfDef) {
798   bool IfNDef = FormatTok->is(tok::pp_ifndef);
799   nextToken();
800   bool Unreachable = false;
801   if (!IfDef && (FormatTok->is(tok::kw_false) || FormatTok->TokenText == "0"))
802     Unreachable = true;
803   if (IfDef && !IfNDef && FormatTok->TokenText == "SWIG")
804     Unreachable = true;
805   conditionalCompilationStart(Unreachable);
806   FormatToken *IfCondition = FormatTok;
807   // If there's a #ifndef on the first line, and the only lines before it are
808   // comments, it could be an include guard.
809   bool MaybeIncludeGuard = IfNDef;
810   if (IncludeGuard == IG_Inited && MaybeIncludeGuard)
811     for (auto &Line : Lines) {
812       if (!Line.Tokens.front().Tok->is(tok::comment)) {
813         MaybeIncludeGuard = false;
814         IncludeGuard = IG_Rejected;
815         break;
816       }
817     }
818   --PPBranchLevel;
819   parsePPUnknown();
820   ++PPBranchLevel;
821   if (IncludeGuard == IG_Inited && MaybeIncludeGuard) {
822     IncludeGuard = IG_IfNdefed;
823     IncludeGuardToken = IfCondition;
824   }
825 }
826 
827 void UnwrappedLineParser::parsePPElse() {
828   // If a potential include guard has an #else, it's not an include guard.
829   if (IncludeGuard == IG_Defined && PPBranchLevel == 0)
830     IncludeGuard = IG_Rejected;
831   conditionalCompilationAlternative();
832   if (PPBranchLevel > -1)
833     --PPBranchLevel;
834   parsePPUnknown();
835   ++PPBranchLevel;
836 }
837 
838 void UnwrappedLineParser::parsePPElIf() { parsePPElse(); }
839 
840 void UnwrappedLineParser::parsePPEndIf() {
841   conditionalCompilationEnd();
842   parsePPUnknown();
843   // If the #endif of a potential include guard is the last thing in the file,
844   // then we found an include guard.
845   unsigned TokenPosition = Tokens->getPosition();
846   FormatToken *PeekNext = AllTokens[TokenPosition];
847   if (IncludeGuard == IG_Defined && PPBranchLevel == -1 &&
848       PeekNext->is(tok::eof) &&
849       Style.IndentPPDirectives != FormatStyle::PPDIS_None)
850     IncludeGuard = IG_Found;
851 }
852 
853 void UnwrappedLineParser::parsePPDefine() {
854   nextToken();
855 
856   if (!FormatTok->Tok.getIdentifierInfo()) {
857     IncludeGuard = IG_Rejected;
858     IncludeGuardToken = nullptr;
859     parsePPUnknown();
860     return;
861   }
862 
863   if (IncludeGuard == IG_IfNdefed &&
864       IncludeGuardToken->TokenText == FormatTok->TokenText) {
865     IncludeGuard = IG_Defined;
866     IncludeGuardToken = nullptr;
867     for (auto &Line : Lines) {
868       if (!Line.Tokens.front().Tok->isOneOf(tok::comment, tok::hash)) {
869         IncludeGuard = IG_Rejected;
870         break;
871       }
872     }
873   }
874 
875   nextToken();
876   if (FormatTok->Tok.getKind() == tok::l_paren &&
877       FormatTok->WhitespaceRange.getBegin() ==
878           FormatTok->WhitespaceRange.getEnd()) {
879     parseParens();
880   }
881   if (Style.IndentPPDirectives != FormatStyle::PPDIS_None)
882     Line->Level += PPBranchLevel + 1;
883   addUnwrappedLine();
884   ++Line->Level;
885 
886   // Errors during a preprocessor directive can only affect the layout of the
887   // preprocessor directive, and thus we ignore them. An alternative approach
888   // would be to use the same approach we use on the file level (no
889   // re-indentation if there was a structural error) within the macro
890   // definition.
891   parseFile();
892 }
893 
894 void UnwrappedLineParser::parsePPUnknown() {
895   do {
896     nextToken();
897   } while (!eof());
898   if (Style.IndentPPDirectives != FormatStyle::PPDIS_None)
899     Line->Level += PPBranchLevel + 1;
900   addUnwrappedLine();
901 }
902 
903 // Here we blacklist certain tokens that are not usually the first token in an
904 // unwrapped line. This is used in attempt to distinguish macro calls without
905 // trailing semicolons from other constructs split to several lines.
906 static bool tokenCanStartNewLine(const clang::Token &Tok) {
907   // Semicolon can be a null-statement, l_square can be a start of a macro or
908   // a C++11 attribute, but this doesn't seem to be common.
909   return Tok.isNot(tok::semi) && Tok.isNot(tok::l_brace) &&
910          Tok.isNot(tok::l_square) &&
911          // Tokens that can only be used as binary operators and a part of
912          // overloaded operator names.
913          Tok.isNot(tok::period) && Tok.isNot(tok::periodstar) &&
914          Tok.isNot(tok::arrow) && Tok.isNot(tok::arrowstar) &&
915          Tok.isNot(tok::less) && Tok.isNot(tok::greater) &&
916          Tok.isNot(tok::slash) && Tok.isNot(tok::percent) &&
917          Tok.isNot(tok::lessless) && Tok.isNot(tok::greatergreater) &&
918          Tok.isNot(tok::equal) && Tok.isNot(tok::plusequal) &&
919          Tok.isNot(tok::minusequal) && Tok.isNot(tok::starequal) &&
920          Tok.isNot(tok::slashequal) && Tok.isNot(tok::percentequal) &&
921          Tok.isNot(tok::ampequal) && Tok.isNot(tok::pipeequal) &&
922          Tok.isNot(tok::caretequal) && Tok.isNot(tok::greatergreaterequal) &&
923          Tok.isNot(tok::lesslessequal) &&
924          // Colon is used in labels, base class lists, initializer lists,
925          // range-based for loops, ternary operator, but should never be the
926          // first token in an unwrapped line.
927          Tok.isNot(tok::colon) &&
928          // 'noexcept' is a trailing annotation.
929          Tok.isNot(tok::kw_noexcept);
930 }
931 
932 static bool mustBeJSIdent(const AdditionalKeywords &Keywords,
933                           const FormatToken *FormatTok) {
934   // FIXME: This returns true for C/C++ keywords like 'struct'.
935   return FormatTok->is(tok::identifier) &&
936          (FormatTok->Tok.getIdentifierInfo() == nullptr ||
937           !FormatTok->isOneOf(
938               Keywords.kw_in, Keywords.kw_of, Keywords.kw_as, Keywords.kw_async,
939               Keywords.kw_await, Keywords.kw_yield, Keywords.kw_finally,
940               Keywords.kw_function, Keywords.kw_import, Keywords.kw_is,
941               Keywords.kw_let, Keywords.kw_var, tok::kw_const,
942               Keywords.kw_abstract, Keywords.kw_extends, Keywords.kw_implements,
943               Keywords.kw_instanceof, Keywords.kw_interface, Keywords.kw_throws,
944               Keywords.kw_from));
945 }
946 
947 static bool mustBeJSIdentOrValue(const AdditionalKeywords &Keywords,
948                                  const FormatToken *FormatTok) {
949   return FormatTok->Tok.isLiteral() ||
950          FormatTok->isOneOf(tok::kw_true, tok::kw_false) ||
951          mustBeJSIdent(Keywords, FormatTok);
952 }
953 
954 // isJSDeclOrStmt returns true if |FormatTok| starts a declaration or statement
955 // when encountered after a value (see mustBeJSIdentOrValue).
956 static bool isJSDeclOrStmt(const AdditionalKeywords &Keywords,
957                            const FormatToken *FormatTok) {
958   return FormatTok->isOneOf(
959       tok::kw_return, Keywords.kw_yield,
960       // conditionals
961       tok::kw_if, tok::kw_else,
962       // loops
963       tok::kw_for, tok::kw_while, tok::kw_do, tok::kw_continue, tok::kw_break,
964       // switch/case
965       tok::kw_switch, tok::kw_case,
966       // exceptions
967       tok::kw_throw, tok::kw_try, tok::kw_catch, Keywords.kw_finally,
968       // declaration
969       tok::kw_const, tok::kw_class, Keywords.kw_var, Keywords.kw_let,
970       Keywords.kw_async, Keywords.kw_function,
971       // import/export
972       Keywords.kw_import, tok::kw_export);
973 }
974 
975 // readTokenWithJavaScriptASI reads the next token and terminates the current
976 // line if JavaScript Automatic Semicolon Insertion must
977 // happen between the current token and the next token.
978 //
979 // This method is conservative - it cannot cover all edge cases of JavaScript,
980 // but only aims to correctly handle certain well known cases. It *must not*
981 // return true in speculative cases.
982 void UnwrappedLineParser::readTokenWithJavaScriptASI() {
983   FormatToken *Previous = FormatTok;
984   readToken();
985   FormatToken *Next = FormatTok;
986 
987   bool IsOnSameLine =
988       CommentsBeforeNextToken.empty()
989           ? Next->NewlinesBefore == 0
990           : CommentsBeforeNextToken.front()->NewlinesBefore == 0;
991   if (IsOnSameLine)
992     return;
993 
994   bool PreviousMustBeValue = mustBeJSIdentOrValue(Keywords, Previous);
995   bool PreviousStartsTemplateExpr =
996       Previous->is(TT_TemplateString) && Previous->TokenText.endswith("${");
997   if (PreviousMustBeValue || Previous->is(tok::r_paren)) {
998     // If the line contains an '@' sign, the previous token might be an
999     // annotation, which can precede another identifier/value.
1000     bool HasAt = std::find_if(Line->Tokens.begin(), Line->Tokens.end(),
1001                               [](UnwrappedLineNode &LineNode) {
1002                                 return LineNode.Tok->is(tok::at);
1003                               }) != Line->Tokens.end();
1004     if (HasAt)
1005       return;
1006   }
1007   if (Next->is(tok::exclaim) && PreviousMustBeValue)
1008     return addUnwrappedLine();
1009   bool NextMustBeValue = mustBeJSIdentOrValue(Keywords, Next);
1010   bool NextEndsTemplateExpr =
1011       Next->is(TT_TemplateString) && Next->TokenText.startswith("}");
1012   if (NextMustBeValue && !NextEndsTemplateExpr && !PreviousStartsTemplateExpr &&
1013       (PreviousMustBeValue ||
1014        Previous->isOneOf(tok::r_square, tok::r_paren, tok::plusplus,
1015                          tok::minusminus)))
1016     return addUnwrappedLine();
1017   if ((PreviousMustBeValue || Previous->is(tok::r_paren)) &&
1018       isJSDeclOrStmt(Keywords, Next))
1019     return addUnwrappedLine();
1020 }
1021 
1022 void UnwrappedLineParser::parseStructuralElement() {
1023   assert(!FormatTok->is(tok::l_brace));
1024   if (Style.Language == FormatStyle::LK_TableGen &&
1025       FormatTok->is(tok::pp_include)) {
1026     nextToken();
1027     if (FormatTok->is(tok::string_literal))
1028       nextToken();
1029     addUnwrappedLine();
1030     return;
1031   }
1032   switch (FormatTok->Tok.getKind()) {
1033   case tok::kw_asm:
1034     nextToken();
1035     if (FormatTok->is(tok::l_brace)) {
1036       FormatTok->setType(TT_InlineASMBrace);
1037       nextToken();
1038       while (FormatTok && FormatTok->isNot(tok::eof)) {
1039         if (FormatTok->is(tok::r_brace)) {
1040           FormatTok->setType(TT_InlineASMBrace);
1041           nextToken();
1042           addUnwrappedLine();
1043           break;
1044         }
1045         FormatTok->Finalized = true;
1046         nextToken();
1047       }
1048     }
1049     break;
1050   case tok::kw_namespace:
1051     parseNamespace();
1052     return;
1053   case tok::kw_public:
1054   case tok::kw_protected:
1055   case tok::kw_private:
1056     if (Style.Language == FormatStyle::LK_Java ||
1057         Style.Language == FormatStyle::LK_JavaScript || Style.isCSharp())
1058       nextToken();
1059     else
1060       parseAccessSpecifier();
1061     return;
1062   case tok::kw_if:
1063     if (Style.Language == FormatStyle::LK_JavaScript && Line->MustBeDeclaration)
1064       // field/method declaration.
1065       break;
1066     parseIfThenElse();
1067     return;
1068   case tok::kw_for:
1069   case tok::kw_while:
1070     if (Style.Language == FormatStyle::LK_JavaScript && Line->MustBeDeclaration)
1071       // field/method declaration.
1072       break;
1073     parseForOrWhileLoop();
1074     return;
1075   case tok::kw_do:
1076     if (Style.Language == FormatStyle::LK_JavaScript && Line->MustBeDeclaration)
1077       // field/method declaration.
1078       break;
1079     parseDoWhile();
1080     return;
1081   case tok::kw_switch:
1082     if (Style.Language == FormatStyle::LK_JavaScript && Line->MustBeDeclaration)
1083       // 'switch: string' field declaration.
1084       break;
1085     parseSwitch();
1086     return;
1087   case tok::kw_default:
1088     if (Style.Language == FormatStyle::LK_JavaScript && Line->MustBeDeclaration)
1089       // 'default: string' field declaration.
1090       break;
1091     nextToken();
1092     if (FormatTok->is(tok::colon)) {
1093       parseLabel();
1094       return;
1095     }
1096     // e.g. "default void f() {}" in a Java interface.
1097     break;
1098   case tok::kw_case:
1099     if (Style.Language == FormatStyle::LK_JavaScript && Line->MustBeDeclaration)
1100       // 'case: string' field declaration.
1101       break;
1102     parseCaseLabel();
1103     return;
1104   case tok::kw_try:
1105   case tok::kw___try:
1106     if (Style.Language == FormatStyle::LK_JavaScript && Line->MustBeDeclaration)
1107       // field/method declaration.
1108       break;
1109     parseTryCatch();
1110     return;
1111   case tok::kw_extern:
1112     nextToken();
1113     if (FormatTok->Tok.is(tok::string_literal)) {
1114       nextToken();
1115       if (FormatTok->Tok.is(tok::l_brace)) {
1116         if (Style.BraceWrapping.AfterExternBlock) {
1117           addUnwrappedLine();
1118           parseBlock(/*MustBeDeclaration=*/true);
1119         } else {
1120           parseBlock(/*MustBeDeclaration=*/true, /*AddLevel=*/false);
1121         }
1122         addUnwrappedLine();
1123         return;
1124       }
1125     }
1126     break;
1127   case tok::kw_export:
1128     if (Style.Language == FormatStyle::LK_JavaScript) {
1129       parseJavaScriptEs6ImportExport();
1130       return;
1131     }
1132     if (!Style.isCpp())
1133       break;
1134     // Handle C++ "(inline|export) namespace".
1135     LLVM_FALLTHROUGH;
1136   case tok::kw_inline:
1137     nextToken();
1138     if (FormatTok->Tok.is(tok::kw_namespace)) {
1139       parseNamespace();
1140       return;
1141     }
1142     break;
1143   case tok::identifier:
1144     if (FormatTok->is(TT_ForEachMacro)) {
1145       parseForOrWhileLoop();
1146       return;
1147     }
1148     if (FormatTok->is(TT_MacroBlockBegin)) {
1149       parseBlock(/*MustBeDeclaration=*/false, /*AddLevel=*/true,
1150                  /*MunchSemi=*/false);
1151       return;
1152     }
1153     if (FormatTok->is(Keywords.kw_import)) {
1154       if (Style.Language == FormatStyle::LK_JavaScript) {
1155         parseJavaScriptEs6ImportExport();
1156         return;
1157       }
1158       if (Style.Language == FormatStyle::LK_Proto) {
1159         nextToken();
1160         if (FormatTok->is(tok::kw_public))
1161           nextToken();
1162         if (!FormatTok->is(tok::string_literal))
1163           return;
1164         nextToken();
1165         if (FormatTok->is(tok::semi))
1166           nextToken();
1167         addUnwrappedLine();
1168         return;
1169       }
1170     }
1171     if (Style.isCpp() &&
1172         FormatTok->isOneOf(Keywords.kw_signals, Keywords.kw_qsignals,
1173                            Keywords.kw_slots, Keywords.kw_qslots)) {
1174       nextToken();
1175       if (FormatTok->is(tok::colon)) {
1176         nextToken();
1177         addUnwrappedLine();
1178         return;
1179       }
1180     }
1181     if (Style.isCpp() && FormatTok->is(TT_StatementMacro)) {
1182       parseStatementMacro();
1183       return;
1184     }
1185     if (Style.isCpp() && FormatTok->is(TT_NamespaceMacro)) {
1186       parseNamespace();
1187       return;
1188     }
1189     // In all other cases, parse the declaration.
1190     break;
1191   default:
1192     break;
1193   }
1194   do {
1195     const FormatToken *Previous = FormatTok->Previous;
1196     switch (FormatTok->Tok.getKind()) {
1197     case tok::at:
1198       nextToken();
1199       if (FormatTok->Tok.is(tok::l_brace)) {
1200         nextToken();
1201         parseBracedList();
1202         break;
1203       } else if (Style.Language == FormatStyle::LK_Java &&
1204                  FormatTok->is(Keywords.kw_interface)) {
1205         nextToken();
1206         break;
1207       }
1208       switch (FormatTok->Tok.getObjCKeywordID()) {
1209       case tok::objc_public:
1210       case tok::objc_protected:
1211       case tok::objc_package:
1212       case tok::objc_private:
1213         return parseAccessSpecifier();
1214       case tok::objc_interface:
1215       case tok::objc_implementation:
1216         return parseObjCInterfaceOrImplementation();
1217       case tok::objc_protocol:
1218         if (parseObjCProtocol())
1219           return;
1220         break;
1221       case tok::objc_end:
1222         return; // Handled by the caller.
1223       case tok::objc_optional:
1224       case tok::objc_required:
1225         nextToken();
1226         addUnwrappedLine();
1227         return;
1228       case tok::objc_autoreleasepool:
1229         nextToken();
1230         if (FormatTok->Tok.is(tok::l_brace)) {
1231           if (Style.BraceWrapping.AfterControlStatement ==
1232               FormatStyle::BWACS_Always)
1233             addUnwrappedLine();
1234           parseBlock(/*MustBeDeclaration=*/false);
1235         }
1236         addUnwrappedLine();
1237         return;
1238       case tok::objc_synchronized:
1239         nextToken();
1240         if (FormatTok->Tok.is(tok::l_paren))
1241           // Skip synchronization object
1242           parseParens();
1243         if (FormatTok->Tok.is(tok::l_brace)) {
1244           if (Style.BraceWrapping.AfterControlStatement ==
1245               FormatStyle::BWACS_Always)
1246             addUnwrappedLine();
1247           parseBlock(/*MustBeDeclaration=*/false);
1248         }
1249         addUnwrappedLine();
1250         return;
1251       case tok::objc_try:
1252         // This branch isn't strictly necessary (the kw_try case below would
1253         // do this too after the tok::at is parsed above).  But be explicit.
1254         parseTryCatch();
1255         return;
1256       default:
1257         break;
1258       }
1259       break;
1260     case tok::kw_enum:
1261       // Ignore if this is part of "template <enum ...".
1262       if (Previous && Previous->is(tok::less)) {
1263         nextToken();
1264         break;
1265       }
1266 
1267       // parseEnum falls through and does not yet add an unwrapped line as an
1268       // enum definition can start a structural element.
1269       if (!parseEnum())
1270         break;
1271       // This only applies for C++.
1272       if (!Style.isCpp()) {
1273         addUnwrappedLine();
1274         return;
1275       }
1276       break;
1277     case tok::kw_typedef:
1278       nextToken();
1279       if (FormatTok->isOneOf(Keywords.kw_NS_ENUM, Keywords.kw_NS_OPTIONS,
1280                              Keywords.kw_CF_ENUM, Keywords.kw_CF_OPTIONS,
1281                              Keywords.kw_CF_CLOSED_ENUM,
1282                              Keywords.kw_NS_CLOSED_ENUM))
1283         parseEnum();
1284       break;
1285     case tok::kw_struct:
1286     case tok::kw_union:
1287     case tok::kw_class:
1288       // parseRecord falls through and does not yet add an unwrapped line as a
1289       // record declaration or definition can start a structural element.
1290       parseRecord();
1291       // This does not apply for Java, JavaScript and C#.
1292       if (Style.Language == FormatStyle::LK_Java ||
1293           Style.Language == FormatStyle::LK_JavaScript || Style.isCSharp()) {
1294         if (FormatTok->is(tok::semi))
1295           nextToken();
1296         addUnwrappedLine();
1297         return;
1298       }
1299       break;
1300     case tok::period:
1301       nextToken();
1302       // In Java, classes have an implicit static member "class".
1303       if (Style.Language == FormatStyle::LK_Java && FormatTok &&
1304           FormatTok->is(tok::kw_class))
1305         nextToken();
1306       if (Style.Language == FormatStyle::LK_JavaScript && FormatTok &&
1307           FormatTok->Tok.getIdentifierInfo())
1308         // JavaScript only has pseudo keywords, all keywords are allowed to
1309         // appear in "IdentifierName" positions. See http://es5.github.io/#x7.6
1310         nextToken();
1311       break;
1312     case tok::semi:
1313       nextToken();
1314       addUnwrappedLine();
1315       return;
1316     case tok::r_brace:
1317       addUnwrappedLine();
1318       return;
1319     case tok::l_paren:
1320       parseParens();
1321       break;
1322     case tok::kw_operator:
1323       nextToken();
1324       if (FormatTok->isBinaryOperator())
1325         nextToken();
1326       break;
1327     case tok::caret:
1328       nextToken();
1329       if (FormatTok->Tok.isAnyIdentifier() ||
1330           FormatTok->isSimpleTypeSpecifier())
1331         nextToken();
1332       if (FormatTok->is(tok::l_paren))
1333         parseParens();
1334       if (FormatTok->is(tok::l_brace))
1335         parseChildBlock();
1336       break;
1337     case tok::l_brace:
1338       if (!tryToParsePropertyAccessor() && !tryToParseBracedList()) {
1339         // A block outside of parentheses must be the last part of a
1340         // structural element.
1341         // FIXME: Figure out cases where this is not true, and add projections
1342         // for them (the one we know is missing are lambdas).
1343         if (Style.BraceWrapping.AfterFunction)
1344           addUnwrappedLine();
1345         FormatTok->setType(TT_FunctionLBrace);
1346         parseBlock(/*MustBeDeclaration=*/false);
1347         addUnwrappedLine();
1348         return;
1349       }
1350       // Otherwise this was a braced init list, and the structural
1351       // element continues.
1352       break;
1353     case tok::kw_try:
1354       if (Style.Language == FormatStyle::LK_JavaScript &&
1355           Line->MustBeDeclaration) {
1356         // field/method declaration.
1357         nextToken();
1358         break;
1359       }
1360       // We arrive here when parsing function-try blocks.
1361       if (Style.BraceWrapping.AfterFunction)
1362         addUnwrappedLine();
1363       parseTryCatch();
1364       return;
1365     case tok::identifier: {
1366       if (Style.isCSharp() && FormatTok->is(Keywords.kw_where) &&
1367           Line->MustBeDeclaration) {
1368         addUnwrappedLine();
1369         parseCSharpGenericTypeConstraint();
1370         break;
1371       }
1372       if (FormatTok->is(TT_MacroBlockEnd)) {
1373         addUnwrappedLine();
1374         return;
1375       }
1376 
1377       // Function declarations (as opposed to function expressions) are parsed
1378       // on their own unwrapped line by continuing this loop. Function
1379       // expressions (functions that are not on their own line) must not create
1380       // a new unwrapped line, so they are special cased below.
1381       size_t TokenCount = Line->Tokens.size();
1382       if (Style.Language == FormatStyle::LK_JavaScript &&
1383           FormatTok->is(Keywords.kw_function) &&
1384           (TokenCount > 1 || (TokenCount == 1 && !Line->Tokens.front().Tok->is(
1385                                                      Keywords.kw_async)))) {
1386         tryToParseJSFunction();
1387         break;
1388       }
1389       if ((Style.Language == FormatStyle::LK_JavaScript ||
1390            Style.Language == FormatStyle::LK_Java) &&
1391           FormatTok->is(Keywords.kw_interface)) {
1392         if (Style.Language == FormatStyle::LK_JavaScript) {
1393           // In JavaScript/TypeScript, "interface" can be used as a standalone
1394           // identifier, e.g. in `var interface = 1;`. If "interface" is
1395           // followed by another identifier, it is very like to be an actual
1396           // interface declaration.
1397           unsigned StoredPosition = Tokens->getPosition();
1398           FormatToken *Next = Tokens->getNextToken();
1399           FormatTok = Tokens->setPosition(StoredPosition);
1400           if (Next && !mustBeJSIdent(Keywords, Next)) {
1401             nextToken();
1402             break;
1403           }
1404         }
1405         parseRecord();
1406         addUnwrappedLine();
1407         return;
1408       }
1409 
1410       if (Style.isCpp() && FormatTok->is(TT_StatementMacro)) {
1411         parseStatementMacro();
1412         return;
1413       }
1414 
1415       // See if the following token should start a new unwrapped line.
1416       StringRef Text = FormatTok->TokenText;
1417       nextToken();
1418 
1419       // JS doesn't have macros, and within classes colons indicate fields, not
1420       // labels.
1421       if (Style.Language == FormatStyle::LK_JavaScript)
1422         break;
1423 
1424       TokenCount = Line->Tokens.size();
1425       if (TokenCount == 1 ||
1426           (TokenCount == 2 && Line->Tokens.front().Tok->is(tok::comment))) {
1427         if (FormatTok->Tok.is(tok::colon) && !Line->MustBeDeclaration) {
1428           Line->Tokens.begin()->Tok->MustBreakBefore = true;
1429           parseLabel(!Style.IndentGotoLabels);
1430           return;
1431         }
1432         // Recognize function-like macro usages without trailing semicolon as
1433         // well as free-standing macros like Q_OBJECT.
1434         bool FunctionLike = FormatTok->is(tok::l_paren);
1435         if (FunctionLike)
1436           parseParens();
1437 
1438         bool FollowedByNewline =
1439             CommentsBeforeNextToken.empty()
1440                 ? FormatTok->NewlinesBefore > 0
1441                 : CommentsBeforeNextToken.front()->NewlinesBefore > 0;
1442 
1443         if (FollowedByNewline && (Text.size() >= 5 || FunctionLike) &&
1444             tokenCanStartNewLine(FormatTok->Tok) && Text == Text.upper()) {
1445           addUnwrappedLine();
1446           return;
1447         }
1448       }
1449       break;
1450     }
1451     case tok::equal:
1452       // Fat arrows (=>) have tok::TokenKind tok::equal but TokenType
1453       // TT_JsFatArrow. The always start an expression or a child block if
1454       // followed by a curly.
1455       if (FormatTok->is(TT_JsFatArrow)) {
1456         nextToken();
1457         if (FormatTok->is(tok::l_brace))
1458           parseChildBlock();
1459         break;
1460       }
1461 
1462       nextToken();
1463       if (FormatTok->Tok.is(tok::l_brace)) {
1464         // Block kind should probably be set to BK_BracedInit for any language.
1465         // C# needs this change to ensure that array initialisers and object
1466         // initialisers are indented the same way.
1467         if (Style.isCSharp())
1468           FormatTok->BlockKind = BK_BracedInit;
1469         nextToken();
1470         parseBracedList();
1471       } else if (Style.Language == FormatStyle::LK_Proto &&
1472                  FormatTok->Tok.is(tok::less)) {
1473         nextToken();
1474         parseBracedList(/*ContinueOnSemicolons=*/false, /*IsEnum=*/false,
1475                         /*ClosingBraceKind=*/tok::greater);
1476       }
1477       break;
1478     case tok::l_square:
1479       parseSquare();
1480       break;
1481     case tok::kw_new:
1482       parseNew();
1483       break;
1484     default:
1485       nextToken();
1486       break;
1487     }
1488   } while (!eof());
1489 }
1490 
1491 bool UnwrappedLineParser::tryToParsePropertyAccessor() {
1492   assert(FormatTok->is(tok::l_brace));
1493   if (!Style.isCSharp())
1494     return false;
1495   // See if it's a property accessor.
1496   if (FormatTok->Previous->isNot(tok::identifier))
1497     return false;
1498 
1499   // See if we are inside a property accessor.
1500   //
1501   // Record the current tokenPosition so that we can advance and
1502   // reset the current token. `Next` is not set yet so we need
1503   // another way to advance along the token stream.
1504   unsigned int StoredPosition = Tokens->getPosition();
1505   FormatToken *Tok = Tokens->getNextToken();
1506 
1507   // A trivial property accessor is of the form:
1508   // { [ACCESS_SPECIFIER] [get]; [ACCESS_SPECIFIER] [set] }
1509   // Track these as they do not require line breaks to be introduced.
1510   bool HasGetOrSet = false;
1511   bool IsTrivialPropertyAccessor = true;
1512   while (!eof()) {
1513     if (Tok->isOneOf(tok::semi, tok::kw_public, tok::kw_private,
1514                      tok::kw_protected, Keywords.kw_internal, Keywords.kw_get,
1515                      Keywords.kw_set)) {
1516       if (Tok->isOneOf(Keywords.kw_get, Keywords.kw_set))
1517         HasGetOrSet = true;
1518       Tok = Tokens->getNextToken();
1519       continue;
1520     }
1521     if (Tok->isNot(tok::r_brace))
1522       IsTrivialPropertyAccessor = false;
1523     break;
1524   }
1525 
1526   if (!HasGetOrSet) {
1527     Tokens->setPosition(StoredPosition);
1528     return false;
1529   }
1530 
1531   // Try to parse the property accessor:
1532   // https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/properties
1533   Tokens->setPosition(StoredPosition);
1534   nextToken();
1535   do {
1536     switch (FormatTok->Tok.getKind()) {
1537     case tok::r_brace:
1538       nextToken();
1539       if (FormatTok->is(tok::equal)) {
1540         while (!eof() && FormatTok->isNot(tok::semi))
1541           nextToken();
1542         nextToken();
1543       }
1544       addUnwrappedLine();
1545       return true;
1546     case tok::l_brace:
1547       ++Line->Level;
1548       parseBlock(/*MustBeDeclaration=*/true);
1549       addUnwrappedLine();
1550       --Line->Level;
1551       break;
1552     case tok::equal:
1553       if (FormatTok->is(TT_JsFatArrow)) {
1554         ++Line->Level;
1555         do {
1556           nextToken();
1557         } while (!eof() && FormatTok->isNot(tok::semi));
1558         nextToken();
1559         addUnwrappedLine();
1560         --Line->Level;
1561         break;
1562       }
1563       nextToken();
1564       break;
1565     default:
1566       if (FormatTok->isOneOf(Keywords.kw_get, Keywords.kw_set) &&
1567           !IsTrivialPropertyAccessor) {
1568         // Non-trivial get/set needs to be on its own line.
1569         addUnwrappedLine();
1570       }
1571       nextToken();
1572     }
1573   } while (!eof());
1574 
1575   // Unreachable for well-formed code (paired '{' and '}').
1576   return true;
1577 }
1578 
1579 bool UnwrappedLineParser::tryToParseLambda() {
1580   if (!Style.isCpp()) {
1581     nextToken();
1582     return false;
1583   }
1584   assert(FormatTok->is(tok::l_square));
1585   FormatToken &LSquare = *FormatTok;
1586   if (!tryToParseLambdaIntroducer())
1587     return false;
1588 
1589   bool SeenArrow = false;
1590 
1591   while (FormatTok->isNot(tok::l_brace)) {
1592     if (FormatTok->isSimpleTypeSpecifier()) {
1593       nextToken();
1594       continue;
1595     }
1596     switch (FormatTok->Tok.getKind()) {
1597     case tok::l_brace:
1598       break;
1599     case tok::l_paren:
1600       parseParens();
1601       break;
1602     case tok::amp:
1603     case tok::star:
1604     case tok::kw_const:
1605     case tok::comma:
1606     case tok::less:
1607     case tok::greater:
1608     case tok::identifier:
1609     case tok::numeric_constant:
1610     case tok::coloncolon:
1611     case tok::kw_class:
1612     case tok::kw_mutable:
1613     case tok::kw_noexcept:
1614     case tok::kw_template:
1615     case tok::kw_typename:
1616       nextToken();
1617       break;
1618     // Specialization of a template with an integer parameter can contain
1619     // arithmetic, logical, comparison and ternary operators.
1620     //
1621     // FIXME: This also accepts sequences of operators that are not in the scope
1622     // of a template argument list.
1623     //
1624     // In a C++ lambda a template type can only occur after an arrow. We use
1625     // this as an heuristic to distinguish between Objective-C expressions
1626     // followed by an `a->b` expression, such as:
1627     // ([obj func:arg] + a->b)
1628     // Otherwise the code below would parse as a lambda.
1629     //
1630     // FIXME: This heuristic is incorrect for C++20 generic lambdas with
1631     // explicit template lists: []<bool b = true && false>(U &&u){}
1632     case tok::plus:
1633     case tok::minus:
1634     case tok::exclaim:
1635     case tok::tilde:
1636     case tok::slash:
1637     case tok::percent:
1638     case tok::lessless:
1639     case tok::pipe:
1640     case tok::pipepipe:
1641     case tok::ampamp:
1642     case tok::caret:
1643     case tok::equalequal:
1644     case tok::exclaimequal:
1645     case tok::greaterequal:
1646     case tok::lessequal:
1647     case tok::question:
1648     case tok::colon:
1649     case tok::ellipsis:
1650     case tok::kw_true:
1651     case tok::kw_false:
1652       if (SeenArrow) {
1653         nextToken();
1654         break;
1655       }
1656       return true;
1657     case tok::arrow:
1658       // This might or might not actually be a lambda arrow (this could be an
1659       // ObjC method invocation followed by a dereferencing arrow). We might
1660       // reset this back to TT_Unknown in TokenAnnotator.
1661       FormatTok->setType(TT_LambdaArrow);
1662       SeenArrow = true;
1663       nextToken();
1664       break;
1665     default:
1666       return true;
1667     }
1668   }
1669   FormatTok->setType(TT_LambdaLBrace);
1670   LSquare.setType(TT_LambdaLSquare);
1671   parseChildBlock();
1672   return true;
1673 }
1674 
1675 bool UnwrappedLineParser::tryToParseLambdaIntroducer() {
1676   const FormatToken *Previous = FormatTok->Previous;
1677   if (Previous &&
1678       (Previous->isOneOf(tok::identifier, tok::kw_operator, tok::kw_new,
1679                          tok::kw_delete, tok::l_square) ||
1680        FormatTok->isCppStructuredBinding(Style) || Previous->closesScope() ||
1681        Previous->isSimpleTypeSpecifier())) {
1682     nextToken();
1683     return false;
1684   }
1685   nextToken();
1686   if (FormatTok->is(tok::l_square)) {
1687     return false;
1688   }
1689   parseSquare(/*LambdaIntroducer=*/true);
1690   return true;
1691 }
1692 
1693 void UnwrappedLineParser::tryToParseJSFunction() {
1694   assert(FormatTok->is(Keywords.kw_function) ||
1695          FormatTok->startsSequence(Keywords.kw_async, Keywords.kw_function));
1696   if (FormatTok->is(Keywords.kw_async))
1697     nextToken();
1698   // Consume "function".
1699   nextToken();
1700 
1701   // Consume * (generator function). Treat it like C++'s overloaded operators.
1702   if (FormatTok->is(tok::star)) {
1703     FormatTok->setType(TT_OverloadedOperator);
1704     nextToken();
1705   }
1706 
1707   // Consume function name.
1708   if (FormatTok->is(tok::identifier))
1709     nextToken();
1710 
1711   if (FormatTok->isNot(tok::l_paren))
1712     return;
1713 
1714   // Parse formal parameter list.
1715   parseParens();
1716 
1717   if (FormatTok->is(tok::colon)) {
1718     // Parse a type definition.
1719     nextToken();
1720 
1721     // Eat the type declaration. For braced inline object types, balance braces,
1722     // otherwise just parse until finding an l_brace for the function body.
1723     if (FormatTok->is(tok::l_brace))
1724       tryToParseBracedList();
1725     else
1726       while (!FormatTok->isOneOf(tok::l_brace, tok::semi) && !eof())
1727         nextToken();
1728   }
1729 
1730   if (FormatTok->is(tok::semi))
1731     return;
1732 
1733   parseChildBlock();
1734 }
1735 
1736 bool UnwrappedLineParser::tryToParseBracedList() {
1737   if (FormatTok->BlockKind == BK_Unknown)
1738     calculateBraceTypes();
1739   assert(FormatTok->BlockKind != BK_Unknown);
1740   if (FormatTok->BlockKind == BK_Block)
1741     return false;
1742   nextToken();
1743   parseBracedList();
1744   return true;
1745 }
1746 
1747 bool UnwrappedLineParser::parseBracedList(bool ContinueOnSemicolons,
1748                                           bool IsEnum,
1749                                           tok::TokenKind ClosingBraceKind) {
1750   bool HasError = false;
1751 
1752   // FIXME: Once we have an expression parser in the UnwrappedLineParser,
1753   // replace this by using parseAssigmentExpression() inside.
1754   do {
1755     if (Style.isCSharp()) {
1756       if (FormatTok->is(TT_JsFatArrow)) {
1757         nextToken();
1758         // Fat arrows can be followed by simple expressions or by child blocks
1759         // in curly braces.
1760         if (FormatTok->is(tok::l_brace)) {
1761           parseChildBlock();
1762           continue;
1763         }
1764       }
1765     }
1766     if (Style.Language == FormatStyle::LK_JavaScript) {
1767       if (FormatTok->is(Keywords.kw_function) ||
1768           FormatTok->startsSequence(Keywords.kw_async, Keywords.kw_function)) {
1769         tryToParseJSFunction();
1770         continue;
1771       }
1772       if (FormatTok->is(TT_JsFatArrow)) {
1773         nextToken();
1774         // Fat arrows can be followed by simple expressions or by child blocks
1775         // in curly braces.
1776         if (FormatTok->is(tok::l_brace)) {
1777           parseChildBlock();
1778           continue;
1779         }
1780       }
1781       if (FormatTok->is(tok::l_brace)) {
1782         // Could be a method inside of a braced list `{a() { return 1; }}`.
1783         if (tryToParseBracedList())
1784           continue;
1785         parseChildBlock();
1786       }
1787     }
1788     if (FormatTok->Tok.getKind() == ClosingBraceKind) {
1789       if (IsEnum && !Style.AllowShortEnumsOnASingleLine)
1790         addUnwrappedLine();
1791       nextToken();
1792       return !HasError;
1793     }
1794     switch (FormatTok->Tok.getKind()) {
1795     case tok::caret:
1796       nextToken();
1797       if (FormatTok->is(tok::l_brace)) {
1798         parseChildBlock();
1799       }
1800       break;
1801     case tok::l_square:
1802       if (Style.isCSharp())
1803         parseSquare();
1804       else
1805         tryToParseLambda();
1806       break;
1807     case tok::l_paren:
1808       parseParens();
1809       // JavaScript can just have free standing methods and getters/setters in
1810       // object literals. Detect them by a "{" following ")".
1811       if (Style.Language == FormatStyle::LK_JavaScript) {
1812         if (FormatTok->is(tok::l_brace))
1813           parseChildBlock();
1814         break;
1815       }
1816       break;
1817     case tok::l_brace:
1818       // Assume there are no blocks inside a braced init list apart
1819       // from the ones we explicitly parse out (like lambdas).
1820       FormatTok->BlockKind = BK_BracedInit;
1821       nextToken();
1822       parseBracedList();
1823       break;
1824     case tok::less:
1825       if (Style.Language == FormatStyle::LK_Proto) {
1826         nextToken();
1827         parseBracedList(/*ContinueOnSemicolons=*/false, /*IsEnum=*/false,
1828                         /*ClosingBraceKind=*/tok::greater);
1829       } else {
1830         nextToken();
1831       }
1832       break;
1833     case tok::semi:
1834       // JavaScript (or more precisely TypeScript) can have semicolons in braced
1835       // lists (in so-called TypeMemberLists). Thus, the semicolon cannot be
1836       // used for error recovery if we have otherwise determined that this is
1837       // a braced list.
1838       if (Style.Language == FormatStyle::LK_JavaScript) {
1839         nextToken();
1840         break;
1841       }
1842       HasError = true;
1843       if (!ContinueOnSemicolons)
1844         return !HasError;
1845       nextToken();
1846       break;
1847     case tok::comma:
1848       nextToken();
1849       if (IsEnum && !Style.AllowShortEnumsOnASingleLine)
1850         addUnwrappedLine();
1851       break;
1852     default:
1853       nextToken();
1854       break;
1855     }
1856   } while (!eof());
1857   return false;
1858 }
1859 
1860 void UnwrappedLineParser::parseParens() {
1861   assert(FormatTok->Tok.is(tok::l_paren) && "'(' expected.");
1862   nextToken();
1863   do {
1864     switch (FormatTok->Tok.getKind()) {
1865     case tok::l_paren:
1866       parseParens();
1867       if (Style.Language == FormatStyle::LK_Java && FormatTok->is(tok::l_brace))
1868         parseChildBlock();
1869       break;
1870     case tok::r_paren:
1871       nextToken();
1872       return;
1873     case tok::r_brace:
1874       // A "}" inside parenthesis is an error if there wasn't a matching "{".
1875       return;
1876     case tok::l_square:
1877       tryToParseLambda();
1878       break;
1879     case tok::l_brace:
1880       if (!tryToParseBracedList())
1881         parseChildBlock();
1882       break;
1883     case tok::at:
1884       nextToken();
1885       if (FormatTok->Tok.is(tok::l_brace)) {
1886         nextToken();
1887         parseBracedList();
1888       }
1889       break;
1890     case tok::kw_class:
1891       if (Style.Language == FormatStyle::LK_JavaScript)
1892         parseRecord(/*ParseAsExpr=*/true);
1893       else
1894         nextToken();
1895       break;
1896     case tok::identifier:
1897       if (Style.Language == FormatStyle::LK_JavaScript &&
1898           (FormatTok->is(Keywords.kw_function) ||
1899            FormatTok->startsSequence(Keywords.kw_async, Keywords.kw_function)))
1900         tryToParseJSFunction();
1901       else
1902         nextToken();
1903       break;
1904     default:
1905       nextToken();
1906       break;
1907     }
1908   } while (!eof());
1909 }
1910 
1911 void UnwrappedLineParser::parseSquare(bool LambdaIntroducer) {
1912   if (!LambdaIntroducer) {
1913     assert(FormatTok->Tok.is(tok::l_square) && "'[' expected.");
1914     if (tryToParseLambda())
1915       return;
1916   }
1917   do {
1918     switch (FormatTok->Tok.getKind()) {
1919     case tok::l_paren:
1920       parseParens();
1921       break;
1922     case tok::r_square:
1923       nextToken();
1924       return;
1925     case tok::r_brace:
1926       // A "}" inside parenthesis is an error if there wasn't a matching "{".
1927       return;
1928     case tok::l_square:
1929       parseSquare();
1930       break;
1931     case tok::l_brace: {
1932       if (!tryToParseBracedList())
1933         parseChildBlock();
1934       break;
1935     }
1936     case tok::at:
1937       nextToken();
1938       if (FormatTok->Tok.is(tok::l_brace)) {
1939         nextToken();
1940         parseBracedList();
1941       }
1942       break;
1943     default:
1944       nextToken();
1945       break;
1946     }
1947   } while (!eof());
1948 }
1949 
1950 void UnwrappedLineParser::parseIfThenElse() {
1951   assert(FormatTok->Tok.is(tok::kw_if) && "'if' expected");
1952   nextToken();
1953   if (FormatTok->Tok.isOneOf(tok::kw_constexpr, tok::identifier))
1954     nextToken();
1955   if (FormatTok->Tok.is(tok::l_paren))
1956     parseParens();
1957   bool NeedsUnwrappedLine = false;
1958   if (FormatTok->Tok.is(tok::l_brace)) {
1959     CompoundStatementIndenter Indenter(this, Style, Line->Level);
1960     parseBlock(/*MustBeDeclaration=*/false);
1961     if (Style.BraceWrapping.BeforeElse)
1962       addUnwrappedLine();
1963     else
1964       NeedsUnwrappedLine = true;
1965   } else {
1966     addUnwrappedLine();
1967     ++Line->Level;
1968     parseStructuralElement();
1969     --Line->Level;
1970   }
1971   if (FormatTok->Tok.is(tok::kw_else)) {
1972     nextToken();
1973     if (FormatTok->Tok.is(tok::l_brace)) {
1974       CompoundStatementIndenter Indenter(this, Style, Line->Level);
1975       parseBlock(/*MustBeDeclaration=*/false);
1976       addUnwrappedLine();
1977     } else if (FormatTok->Tok.is(tok::kw_if)) {
1978       parseIfThenElse();
1979     } else {
1980       addUnwrappedLine();
1981       ++Line->Level;
1982       parseStructuralElement();
1983       if (FormatTok->is(tok::eof))
1984         addUnwrappedLine();
1985       --Line->Level;
1986     }
1987   } else if (NeedsUnwrappedLine) {
1988     addUnwrappedLine();
1989   }
1990 }
1991 
1992 void UnwrappedLineParser::parseTryCatch() {
1993   assert(FormatTok->isOneOf(tok::kw_try, tok::kw___try) && "'try' expected");
1994   nextToken();
1995   bool NeedsUnwrappedLine = false;
1996   if (FormatTok->is(tok::colon)) {
1997     // We are in a function try block, what comes is an initializer list.
1998     nextToken();
1999 
2000     // In case identifiers were removed by clang-tidy, what might follow is
2001     // multiple commas in sequence - before the first identifier.
2002     while (FormatTok->is(tok::comma))
2003       nextToken();
2004 
2005     while (FormatTok->is(tok::identifier)) {
2006       nextToken();
2007       if (FormatTok->is(tok::l_paren))
2008         parseParens();
2009 
2010       // In case identifiers were removed by clang-tidy, what might follow is
2011       // multiple commas in sequence - after the first identifier.
2012       while (FormatTok->is(tok::comma))
2013         nextToken();
2014     }
2015   }
2016   // Parse try with resource.
2017   if (Style.Language == FormatStyle::LK_Java && FormatTok->is(tok::l_paren)) {
2018     parseParens();
2019   }
2020   if (FormatTok->is(tok::l_brace)) {
2021     CompoundStatementIndenter Indenter(this, Style, Line->Level);
2022     parseBlock(/*MustBeDeclaration=*/false);
2023     if (Style.BraceWrapping.BeforeCatch) {
2024       addUnwrappedLine();
2025     } else {
2026       NeedsUnwrappedLine = true;
2027     }
2028   } else if (!FormatTok->is(tok::kw_catch)) {
2029     // The C++ standard requires a compound-statement after a try.
2030     // If there's none, we try to assume there's a structuralElement
2031     // and try to continue.
2032     addUnwrappedLine();
2033     ++Line->Level;
2034     parseStructuralElement();
2035     --Line->Level;
2036   }
2037   while (1) {
2038     if (FormatTok->is(tok::at))
2039       nextToken();
2040     if (!(FormatTok->isOneOf(tok::kw_catch, Keywords.kw___except,
2041                              tok::kw___finally) ||
2042           ((Style.Language == FormatStyle::LK_Java ||
2043             Style.Language == FormatStyle::LK_JavaScript) &&
2044            FormatTok->is(Keywords.kw_finally)) ||
2045           (FormatTok->Tok.isObjCAtKeyword(tok::objc_catch) ||
2046            FormatTok->Tok.isObjCAtKeyword(tok::objc_finally))))
2047       break;
2048     nextToken();
2049     while (FormatTok->isNot(tok::l_brace)) {
2050       if (FormatTok->is(tok::l_paren)) {
2051         parseParens();
2052         continue;
2053       }
2054       if (FormatTok->isOneOf(tok::semi, tok::r_brace, tok::eof))
2055         return;
2056       nextToken();
2057     }
2058     NeedsUnwrappedLine = false;
2059     CompoundStatementIndenter Indenter(this, Style, Line->Level);
2060     parseBlock(/*MustBeDeclaration=*/false);
2061     if (Style.BraceWrapping.BeforeCatch)
2062       addUnwrappedLine();
2063     else
2064       NeedsUnwrappedLine = true;
2065   }
2066   if (NeedsUnwrappedLine)
2067     addUnwrappedLine();
2068 }
2069 
2070 void UnwrappedLineParser::parseNamespace() {
2071   assert(FormatTok->isOneOf(tok::kw_namespace, TT_NamespaceMacro) &&
2072          "'namespace' expected");
2073 
2074   const FormatToken &InitialToken = *FormatTok;
2075   nextToken();
2076   if (InitialToken.is(TT_NamespaceMacro)) {
2077     parseParens();
2078   } else {
2079     while (FormatTok->isOneOf(tok::identifier, tok::coloncolon, tok::kw_inline,
2080                               tok::l_square)) {
2081       if (FormatTok->is(tok::l_square))
2082         parseSquare();
2083       else
2084         nextToken();
2085     }
2086   }
2087   if (FormatTok->Tok.is(tok::l_brace)) {
2088     if (ShouldBreakBeforeBrace(Style, InitialToken))
2089       addUnwrappedLine();
2090 
2091     bool AddLevel = Style.NamespaceIndentation == FormatStyle::NI_All ||
2092                     (Style.NamespaceIndentation == FormatStyle::NI_Inner &&
2093                      DeclarationScopeStack.size() > 1);
2094     parseBlock(/*MustBeDeclaration=*/true, AddLevel);
2095     // Munch the semicolon after a namespace. This is more common than one would
2096     // think. Putting the semicolon into its own line is very ugly.
2097     if (FormatTok->Tok.is(tok::semi))
2098       nextToken();
2099     addUnwrappedLine();
2100   }
2101   // FIXME: Add error handling.
2102 }
2103 
2104 void UnwrappedLineParser::parseNew() {
2105   assert(FormatTok->is(tok::kw_new) && "'new' expected");
2106   nextToken();
2107 
2108   if (Style.isCSharp()) {
2109     do {
2110       if (FormatTok->is(tok::l_brace))
2111         parseBracedList();
2112 
2113       if (FormatTok->isOneOf(tok::semi, tok::comma))
2114         return;
2115 
2116       nextToken();
2117     } while (!eof());
2118   }
2119 
2120   if (Style.Language != FormatStyle::LK_Java)
2121     return;
2122 
2123   // In Java, we can parse everything up to the parens, which aren't optional.
2124   do {
2125     // There should not be a ;, { or } before the new's open paren.
2126     if (FormatTok->isOneOf(tok::semi, tok::l_brace, tok::r_brace))
2127       return;
2128 
2129     // Consume the parens.
2130     if (FormatTok->is(tok::l_paren)) {
2131       parseParens();
2132 
2133       // If there is a class body of an anonymous class, consume that as child.
2134       if (FormatTok->is(tok::l_brace))
2135         parseChildBlock();
2136       return;
2137     }
2138     nextToken();
2139   } while (!eof());
2140 }
2141 
2142 void UnwrappedLineParser::parseForOrWhileLoop() {
2143   assert(FormatTok->isOneOf(tok::kw_for, tok::kw_while, TT_ForEachMacro) &&
2144          "'for', 'while' or foreach macro expected");
2145   nextToken();
2146   // JS' for await ( ...
2147   if (Style.Language == FormatStyle::LK_JavaScript &&
2148       FormatTok->is(Keywords.kw_await))
2149     nextToken();
2150   if (FormatTok->Tok.is(tok::l_paren))
2151     parseParens();
2152   if (FormatTok->Tok.is(tok::l_brace)) {
2153     CompoundStatementIndenter Indenter(this, Style, Line->Level);
2154     parseBlock(/*MustBeDeclaration=*/false);
2155     addUnwrappedLine();
2156   } else {
2157     addUnwrappedLine();
2158     ++Line->Level;
2159     parseStructuralElement();
2160     --Line->Level;
2161   }
2162 }
2163 
2164 void UnwrappedLineParser::parseDoWhile() {
2165   assert(FormatTok->Tok.is(tok::kw_do) && "'do' expected");
2166   nextToken();
2167   if (FormatTok->Tok.is(tok::l_brace)) {
2168     CompoundStatementIndenter Indenter(this, Style, Line->Level);
2169     parseBlock(/*MustBeDeclaration=*/false);
2170     if (Style.BraceWrapping.IndentBraces)
2171       addUnwrappedLine();
2172   } else {
2173     addUnwrappedLine();
2174     ++Line->Level;
2175     parseStructuralElement();
2176     --Line->Level;
2177   }
2178 
2179   // FIXME: Add error handling.
2180   if (!FormatTok->Tok.is(tok::kw_while)) {
2181     addUnwrappedLine();
2182     return;
2183   }
2184 
2185   nextToken();
2186   parseStructuralElement();
2187 }
2188 
2189 void UnwrappedLineParser::parseLabel(bool LeftAlignLabel) {
2190   nextToken();
2191   unsigned OldLineLevel = Line->Level;
2192   if (Line->Level > 1 || (!Line->InPPDirective && Line->Level > 0))
2193     --Line->Level;
2194   if (LeftAlignLabel)
2195     Line->Level = 0;
2196   if (!Style.IndentCaseBlocks && CommentsBeforeNextToken.empty() &&
2197       FormatTok->Tok.is(tok::l_brace)) {
2198     CompoundStatementIndenter Indenter(this, Line->Level,
2199                                        Style.BraceWrapping.AfterCaseLabel,
2200                                        Style.BraceWrapping.IndentBraces);
2201     parseBlock(/*MustBeDeclaration=*/false);
2202     if (FormatTok->Tok.is(tok::kw_break)) {
2203       if (Style.BraceWrapping.AfterControlStatement ==
2204           FormatStyle::BWACS_Always)
2205         addUnwrappedLine();
2206       parseStructuralElement();
2207     }
2208     addUnwrappedLine();
2209   } else {
2210     if (FormatTok->is(tok::semi))
2211       nextToken();
2212     addUnwrappedLine();
2213   }
2214   Line->Level = OldLineLevel;
2215   if (FormatTok->isNot(tok::l_brace)) {
2216     parseStructuralElement();
2217     addUnwrappedLine();
2218   }
2219 }
2220 
2221 void UnwrappedLineParser::parseCaseLabel() {
2222   assert(FormatTok->Tok.is(tok::kw_case) && "'case' expected");
2223   // FIXME: fix handling of complex expressions here.
2224   do {
2225     nextToken();
2226   } while (!eof() && !FormatTok->Tok.is(tok::colon));
2227   parseLabel();
2228 }
2229 
2230 void UnwrappedLineParser::parseSwitch() {
2231   assert(FormatTok->Tok.is(tok::kw_switch) && "'switch' expected");
2232   nextToken();
2233   if (FormatTok->Tok.is(tok::l_paren))
2234     parseParens();
2235   if (FormatTok->Tok.is(tok::l_brace)) {
2236     CompoundStatementIndenter Indenter(this, Style, Line->Level);
2237     parseBlock(/*MustBeDeclaration=*/false);
2238     addUnwrappedLine();
2239   } else {
2240     addUnwrappedLine();
2241     ++Line->Level;
2242     parseStructuralElement();
2243     --Line->Level;
2244   }
2245 }
2246 
2247 void UnwrappedLineParser::parseAccessSpecifier() {
2248   nextToken();
2249   // Understand Qt's slots.
2250   if (FormatTok->isOneOf(Keywords.kw_slots, Keywords.kw_qslots))
2251     nextToken();
2252   // Otherwise, we don't know what it is, and we'd better keep the next token.
2253   if (FormatTok->Tok.is(tok::colon))
2254     nextToken();
2255   addUnwrappedLine();
2256 }
2257 
2258 bool UnwrappedLineParser::parseEnum() {
2259   // Won't be 'enum' for NS_ENUMs.
2260   if (FormatTok->Tok.is(tok::kw_enum))
2261     nextToken();
2262 
2263   // In TypeScript, "enum" can also be used as property name, e.g. in interface
2264   // declarations. An "enum" keyword followed by a colon would be a syntax
2265   // error and thus assume it is just an identifier.
2266   if (Style.Language == FormatStyle::LK_JavaScript &&
2267       FormatTok->isOneOf(tok::colon, tok::question))
2268     return false;
2269 
2270   // In protobuf, "enum" can be used as a field name.
2271   if (Style.Language == FormatStyle::LK_Proto && FormatTok->is(tok::equal))
2272     return false;
2273 
2274   // Eat up enum class ...
2275   if (FormatTok->Tok.is(tok::kw_class) || FormatTok->Tok.is(tok::kw_struct))
2276     nextToken();
2277 
2278   while (FormatTok->Tok.getIdentifierInfo() ||
2279          FormatTok->isOneOf(tok::colon, tok::coloncolon, tok::less,
2280                             tok::greater, tok::comma, tok::question)) {
2281     nextToken();
2282     // We can have macros or attributes in between 'enum' and the enum name.
2283     if (FormatTok->is(tok::l_paren))
2284       parseParens();
2285     if (FormatTok->is(tok::identifier)) {
2286       nextToken();
2287       // If there are two identifiers in a row, this is likely an elaborate
2288       // return type. In Java, this can be "implements", etc.
2289       if (Style.isCpp() && FormatTok->is(tok::identifier))
2290         return false;
2291     }
2292   }
2293 
2294   // Just a declaration or something is wrong.
2295   if (FormatTok->isNot(tok::l_brace))
2296     return true;
2297   FormatTok->BlockKind = BK_Block;
2298 
2299   if (Style.Language == FormatStyle::LK_Java) {
2300     // Java enums are different.
2301     parseJavaEnumBody();
2302     return true;
2303   }
2304   if (Style.Language == FormatStyle::LK_Proto) {
2305     parseBlock(/*MustBeDeclaration=*/true);
2306     return true;
2307   }
2308 
2309   if (!Style.AllowShortEnumsOnASingleLine)
2310     addUnwrappedLine();
2311   // Parse enum body.
2312   nextToken();
2313   if (!Style.AllowShortEnumsOnASingleLine) {
2314     addUnwrappedLine();
2315     Line->Level += 1;
2316   }
2317   bool HasError = !parseBracedList(/*ContinueOnSemicolons=*/true,
2318                                    /*IsEnum=*/true);
2319   if (!Style.AllowShortEnumsOnASingleLine)
2320     Line->Level -= 1;
2321   if (HasError) {
2322     if (FormatTok->is(tok::semi))
2323       nextToken();
2324     addUnwrappedLine();
2325   }
2326   return true;
2327 
2328   // There is no addUnwrappedLine() here so that we fall through to parsing a
2329   // structural element afterwards. Thus, in "enum A {} n, m;",
2330   // "} n, m;" will end up in one unwrapped line.
2331 }
2332 
2333 void UnwrappedLineParser::parseJavaEnumBody() {
2334   // Determine whether the enum is simple, i.e. does not have a semicolon or
2335   // constants with class bodies. Simple enums can be formatted like braced
2336   // lists, contracted to a single line, etc.
2337   unsigned StoredPosition = Tokens->getPosition();
2338   bool IsSimple = true;
2339   FormatToken *Tok = Tokens->getNextToken();
2340   while (Tok) {
2341     if (Tok->is(tok::r_brace))
2342       break;
2343     if (Tok->isOneOf(tok::l_brace, tok::semi)) {
2344       IsSimple = false;
2345       break;
2346     }
2347     // FIXME: This will also mark enums with braces in the arguments to enum
2348     // constants as "not simple". This is probably fine in practice, though.
2349     Tok = Tokens->getNextToken();
2350   }
2351   FormatTok = Tokens->setPosition(StoredPosition);
2352 
2353   if (IsSimple) {
2354     nextToken();
2355     parseBracedList();
2356     addUnwrappedLine();
2357     return;
2358   }
2359 
2360   // Parse the body of a more complex enum.
2361   // First add a line for everything up to the "{".
2362   nextToken();
2363   addUnwrappedLine();
2364   ++Line->Level;
2365 
2366   // Parse the enum constants.
2367   while (FormatTok) {
2368     if (FormatTok->is(tok::l_brace)) {
2369       // Parse the constant's class body.
2370       parseBlock(/*MustBeDeclaration=*/true, /*AddLevel=*/true,
2371                  /*MunchSemi=*/false);
2372     } else if (FormatTok->is(tok::l_paren)) {
2373       parseParens();
2374     } else if (FormatTok->is(tok::comma)) {
2375       nextToken();
2376       addUnwrappedLine();
2377     } else if (FormatTok->is(tok::semi)) {
2378       nextToken();
2379       addUnwrappedLine();
2380       break;
2381     } else if (FormatTok->is(tok::r_brace)) {
2382       addUnwrappedLine();
2383       break;
2384     } else {
2385       nextToken();
2386     }
2387   }
2388 
2389   // Parse the class body after the enum's ";" if any.
2390   parseLevel(/*HasOpeningBrace=*/true);
2391   nextToken();
2392   --Line->Level;
2393   addUnwrappedLine();
2394 }
2395 
2396 void UnwrappedLineParser::parseRecord(bool ParseAsExpr) {
2397   const FormatToken &InitialToken = *FormatTok;
2398   nextToken();
2399 
2400   // The actual identifier can be a nested name specifier, and in macros
2401   // it is often token-pasted.
2402   // An [[attribute]] can be before the identifier.
2403   while (FormatTok->isOneOf(tok::identifier, tok::coloncolon, tok::hashhash,
2404                             tok::kw___attribute, tok::kw___declspec,
2405                             tok::kw_alignas, TT_AttributeSquare) ||
2406          ((Style.Language == FormatStyle::LK_Java ||
2407            Style.Language == FormatStyle::LK_JavaScript) &&
2408           FormatTok->isOneOf(tok::period, tok::comma))) {
2409     if (Style.Language == FormatStyle::LK_JavaScript &&
2410         FormatTok->isOneOf(Keywords.kw_extends, Keywords.kw_implements)) {
2411       // JavaScript/TypeScript supports inline object types in
2412       // extends/implements positions:
2413       //     class Foo implements {bar: number} { }
2414       nextToken();
2415       if (FormatTok->is(tok::l_brace)) {
2416         tryToParseBracedList();
2417         continue;
2418       }
2419     }
2420     bool IsNonMacroIdentifier =
2421         FormatTok->is(tok::identifier) &&
2422         FormatTok->TokenText != FormatTok->TokenText.upper();
2423     nextToken();
2424     // We can have macros or attributes in between 'class' and the class name.
2425     if (!IsNonMacroIdentifier) {
2426       if (FormatTok->Tok.is(tok::l_paren)) {
2427         parseParens();
2428       } else if (FormatTok->is(TT_AttributeSquare)) {
2429         parseSquare();
2430         // Consume the closing TT_AttributeSquare.
2431         if (FormatTok->Next && FormatTok->is(TT_AttributeSquare))
2432           nextToken();
2433       }
2434     }
2435   }
2436 
2437   // Note that parsing away template declarations here leads to incorrectly
2438   // accepting function declarations as record declarations.
2439   // In general, we cannot solve this problem. Consider:
2440   // class A<int> B() {}
2441   // which can be a function definition or a class definition when B() is a
2442   // macro. If we find enough real-world cases where this is a problem, we
2443   // can parse for the 'template' keyword in the beginning of the statement,
2444   // and thus rule out the record production in case there is no template
2445   // (this would still leave us with an ambiguity between template function
2446   // and class declarations).
2447   if (FormatTok->isOneOf(tok::colon, tok::less)) {
2448     while (!eof()) {
2449       if (FormatTok->is(tok::l_brace)) {
2450         calculateBraceTypes(/*ExpectClassBody=*/true);
2451         if (!tryToParseBracedList())
2452           break;
2453       }
2454       if (FormatTok->Tok.is(tok::semi))
2455         return;
2456       if (Style.isCSharp() && FormatTok->is(Keywords.kw_where)) {
2457         addUnwrappedLine();
2458         nextToken();
2459         parseCSharpGenericTypeConstraint();
2460         break;
2461       }
2462       nextToken();
2463     }
2464   }
2465   if (FormatTok->Tok.is(tok::l_brace)) {
2466     if (ParseAsExpr) {
2467       parseChildBlock();
2468     } else {
2469       if (ShouldBreakBeforeBrace(Style, InitialToken))
2470         addUnwrappedLine();
2471 
2472       parseBlock(/*MustBeDeclaration=*/true, /*AddLevel=*/true,
2473                  /*MunchSemi=*/false);
2474     }
2475   }
2476   // There is no addUnwrappedLine() here so that we fall through to parsing a
2477   // structural element afterwards. Thus, in "class A {} n, m;",
2478   // "} n, m;" will end up in one unwrapped line.
2479 }
2480 
2481 void UnwrappedLineParser::parseObjCMethod() {
2482   assert(FormatTok->Tok.isOneOf(tok::l_paren, tok::identifier) &&
2483          "'(' or identifier expected.");
2484   do {
2485     if (FormatTok->Tok.is(tok::semi)) {
2486       nextToken();
2487       addUnwrappedLine();
2488       return;
2489     } else if (FormatTok->Tok.is(tok::l_brace)) {
2490       if (Style.BraceWrapping.AfterFunction)
2491         addUnwrappedLine();
2492       parseBlock(/*MustBeDeclaration=*/false);
2493       addUnwrappedLine();
2494       return;
2495     } else {
2496       nextToken();
2497     }
2498   } while (!eof());
2499 }
2500 
2501 void UnwrappedLineParser::parseObjCProtocolList() {
2502   assert(FormatTok->Tok.is(tok::less) && "'<' expected.");
2503   do {
2504     nextToken();
2505     // Early exit in case someone forgot a close angle.
2506     if (FormatTok->isOneOf(tok::semi, tok::l_brace) ||
2507         FormatTok->Tok.isObjCAtKeyword(tok::objc_end))
2508       return;
2509   } while (!eof() && FormatTok->Tok.isNot(tok::greater));
2510   nextToken(); // Skip '>'.
2511 }
2512 
2513 void UnwrappedLineParser::parseObjCUntilAtEnd() {
2514   do {
2515     if (FormatTok->Tok.isObjCAtKeyword(tok::objc_end)) {
2516       nextToken();
2517       addUnwrappedLine();
2518       break;
2519     }
2520     if (FormatTok->is(tok::l_brace)) {
2521       parseBlock(/*MustBeDeclaration=*/false);
2522       // In ObjC interfaces, nothing should be following the "}".
2523       addUnwrappedLine();
2524     } else if (FormatTok->is(tok::r_brace)) {
2525       // Ignore stray "}". parseStructuralElement doesn't consume them.
2526       nextToken();
2527       addUnwrappedLine();
2528     } else if (FormatTok->isOneOf(tok::minus, tok::plus)) {
2529       nextToken();
2530       parseObjCMethod();
2531     } else {
2532       parseStructuralElement();
2533     }
2534   } while (!eof());
2535 }
2536 
2537 void UnwrappedLineParser::parseObjCInterfaceOrImplementation() {
2538   assert(FormatTok->Tok.getObjCKeywordID() == tok::objc_interface ||
2539          FormatTok->Tok.getObjCKeywordID() == tok::objc_implementation);
2540   nextToken();
2541   nextToken(); // interface name
2542 
2543   // @interface can be followed by a lightweight generic
2544   // specialization list, then either a base class or a category.
2545   if (FormatTok->Tok.is(tok::less)) {
2546     // Unlike protocol lists, generic parameterizations support
2547     // nested angles:
2548     //
2549     // @interface Foo<ValueType : id <NSCopying, NSSecureCoding>> :
2550     //     NSObject <NSCopying, NSSecureCoding>
2551     //
2552     // so we need to count how many open angles we have left.
2553     unsigned NumOpenAngles = 1;
2554     do {
2555       nextToken();
2556       // Early exit in case someone forgot a close angle.
2557       if (FormatTok->isOneOf(tok::semi, tok::l_brace) ||
2558           FormatTok->Tok.isObjCAtKeyword(tok::objc_end))
2559         break;
2560       if (FormatTok->Tok.is(tok::less))
2561         ++NumOpenAngles;
2562       else if (FormatTok->Tok.is(tok::greater)) {
2563         assert(NumOpenAngles > 0 && "'>' makes NumOpenAngles negative");
2564         --NumOpenAngles;
2565       }
2566     } while (!eof() && NumOpenAngles != 0);
2567     nextToken(); // Skip '>'.
2568   }
2569   if (FormatTok->Tok.is(tok::colon)) {
2570     nextToken();
2571     nextToken(); // base class name
2572   } else if (FormatTok->Tok.is(tok::l_paren))
2573     // Skip category, if present.
2574     parseParens();
2575 
2576   if (FormatTok->Tok.is(tok::less))
2577     parseObjCProtocolList();
2578 
2579   if (FormatTok->Tok.is(tok::l_brace)) {
2580     if (Style.BraceWrapping.AfterObjCDeclaration)
2581       addUnwrappedLine();
2582     parseBlock(/*MustBeDeclaration=*/true);
2583   }
2584 
2585   // With instance variables, this puts '}' on its own line.  Without instance
2586   // variables, this ends the @interface line.
2587   addUnwrappedLine();
2588 
2589   parseObjCUntilAtEnd();
2590 }
2591 
2592 // Returns true for the declaration/definition form of @protocol,
2593 // false for the expression form.
2594 bool UnwrappedLineParser::parseObjCProtocol() {
2595   assert(FormatTok->Tok.getObjCKeywordID() == tok::objc_protocol);
2596   nextToken();
2597 
2598   if (FormatTok->is(tok::l_paren))
2599     // The expression form of @protocol, e.g. "Protocol* p = @protocol(foo);".
2600     return false;
2601 
2602   // The definition/declaration form,
2603   // @protocol Foo
2604   // - (int)someMethod;
2605   // @end
2606 
2607   nextToken(); // protocol name
2608 
2609   if (FormatTok->Tok.is(tok::less))
2610     parseObjCProtocolList();
2611 
2612   // Check for protocol declaration.
2613   if (FormatTok->Tok.is(tok::semi)) {
2614     nextToken();
2615     addUnwrappedLine();
2616     return true;
2617   }
2618 
2619   addUnwrappedLine();
2620   parseObjCUntilAtEnd();
2621   return true;
2622 }
2623 
2624 void UnwrappedLineParser::parseJavaScriptEs6ImportExport() {
2625   bool IsImport = FormatTok->is(Keywords.kw_import);
2626   assert(IsImport || FormatTok->is(tok::kw_export));
2627   nextToken();
2628 
2629   // Consume the "default" in "export default class/function".
2630   if (FormatTok->is(tok::kw_default))
2631     nextToken();
2632 
2633   // Consume "async function", "function" and "default function", so that these
2634   // get parsed as free-standing JS functions, i.e. do not require a trailing
2635   // semicolon.
2636   if (FormatTok->is(Keywords.kw_async))
2637     nextToken();
2638   if (FormatTok->is(Keywords.kw_function)) {
2639     nextToken();
2640     return;
2641   }
2642 
2643   // For imports, `export *`, `export {...}`, consume the rest of the line up
2644   // to the terminating `;`. For everything else, just return and continue
2645   // parsing the structural element, i.e. the declaration or expression for
2646   // `export default`.
2647   if (!IsImport && !FormatTok->isOneOf(tok::l_brace, tok::star) &&
2648       !FormatTok->isStringLiteral())
2649     return;
2650 
2651   while (!eof()) {
2652     if (FormatTok->is(tok::semi))
2653       return;
2654     if (Line->Tokens.empty()) {
2655       // Common issue: Automatic Semicolon Insertion wrapped the line, so the
2656       // import statement should terminate.
2657       return;
2658     }
2659     if (FormatTok->is(tok::l_brace)) {
2660       FormatTok->BlockKind = BK_Block;
2661       nextToken();
2662       parseBracedList();
2663     } else {
2664       nextToken();
2665     }
2666   }
2667 }
2668 
2669 void UnwrappedLineParser::parseStatementMacro() {
2670   nextToken();
2671   if (FormatTok->is(tok::l_paren))
2672     parseParens();
2673   if (FormatTok->is(tok::semi))
2674     nextToken();
2675   addUnwrappedLine();
2676 }
2677 
2678 LLVM_ATTRIBUTE_UNUSED static void printDebugInfo(const UnwrappedLine &Line,
2679                                                  StringRef Prefix = "") {
2680   llvm::dbgs() << Prefix << "Line(" << Line.Level
2681                << ", FSC=" << Line.FirstStartColumn << ")"
2682                << (Line.InPPDirective ? " MACRO" : "") << ": ";
2683   for (std::list<UnwrappedLineNode>::const_iterator I = Line.Tokens.begin(),
2684                                                     E = Line.Tokens.end();
2685        I != E; ++I) {
2686     llvm::dbgs() << I->Tok->Tok.getName() << "["
2687                  << "T=" << I->Tok->getType()
2688                  << ", OC=" << I->Tok->OriginalColumn << "] ";
2689   }
2690   for (std::list<UnwrappedLineNode>::const_iterator I = Line.Tokens.begin(),
2691                                                     E = Line.Tokens.end();
2692        I != E; ++I) {
2693     const UnwrappedLineNode &Node = *I;
2694     for (SmallVectorImpl<UnwrappedLine>::const_iterator
2695              I = Node.Children.begin(),
2696              E = Node.Children.end();
2697          I != E; ++I) {
2698       printDebugInfo(*I, "\nChild: ");
2699     }
2700   }
2701   llvm::dbgs() << "\n";
2702 }
2703 
2704 void UnwrappedLineParser::addUnwrappedLine() {
2705   if (Line->Tokens.empty())
2706     return;
2707   LLVM_DEBUG({
2708     if (CurrentLines == &Lines)
2709       printDebugInfo(*Line);
2710   });
2711   CurrentLines->push_back(std::move(*Line));
2712   Line->Tokens.clear();
2713   Line->MatchingOpeningBlockLineIndex = UnwrappedLine::kInvalidIndex;
2714   Line->FirstStartColumn = 0;
2715   if (CurrentLines == &Lines && !PreprocessorDirectives.empty()) {
2716     CurrentLines->append(
2717         std::make_move_iterator(PreprocessorDirectives.begin()),
2718         std::make_move_iterator(PreprocessorDirectives.end()));
2719     PreprocessorDirectives.clear();
2720   }
2721   // Disconnect the current token from the last token on the previous line.
2722   FormatTok->Previous = nullptr;
2723 }
2724 
2725 bool UnwrappedLineParser::eof() const { return FormatTok->Tok.is(tok::eof); }
2726 
2727 bool UnwrappedLineParser::isOnNewLine(const FormatToken &FormatTok) {
2728   return (Line->InPPDirective || FormatTok.HasUnescapedNewline) &&
2729          FormatTok.NewlinesBefore > 0;
2730 }
2731 
2732 // Checks if \p FormatTok is a line comment that continues the line comment
2733 // section on \p Line.
2734 static bool
2735 continuesLineCommentSection(const FormatToken &FormatTok,
2736                             const UnwrappedLine &Line,
2737                             const llvm::Regex &CommentPragmasRegex) {
2738   if (Line.Tokens.empty())
2739     return false;
2740 
2741   StringRef IndentContent = FormatTok.TokenText;
2742   if (FormatTok.TokenText.startswith("//") ||
2743       FormatTok.TokenText.startswith("/*"))
2744     IndentContent = FormatTok.TokenText.substr(2);
2745   if (CommentPragmasRegex.match(IndentContent))
2746     return false;
2747 
2748   // If Line starts with a line comment, then FormatTok continues the comment
2749   // section if its original column is greater or equal to the original start
2750   // column of the line.
2751   //
2752   // Define the min column token of a line as follows: if a line ends in '{' or
2753   // contains a '{' followed by a line comment, then the min column token is
2754   // that '{'. Otherwise, the min column token of the line is the first token of
2755   // the line.
2756   //
2757   // If Line starts with a token other than a line comment, then FormatTok
2758   // continues the comment section if its original column is greater than the
2759   // original start column of the min column token of the line.
2760   //
2761   // For example, the second line comment continues the first in these cases:
2762   //
2763   // // first line
2764   // // second line
2765   //
2766   // and:
2767   //
2768   // // first line
2769   //  // second line
2770   //
2771   // and:
2772   //
2773   // int i; // first line
2774   //  // second line
2775   //
2776   // and:
2777   //
2778   // do { // first line
2779   //      // second line
2780   //   int i;
2781   // } while (true);
2782   //
2783   // and:
2784   //
2785   // enum {
2786   //   a, // first line
2787   //    // second line
2788   //   b
2789   // };
2790   //
2791   // The second line comment doesn't continue the first in these cases:
2792   //
2793   //   // first line
2794   //  // second line
2795   //
2796   // and:
2797   //
2798   // int i; // first line
2799   // // second line
2800   //
2801   // and:
2802   //
2803   // do { // first line
2804   //   // second line
2805   //   int i;
2806   // } while (true);
2807   //
2808   // and:
2809   //
2810   // enum {
2811   //   a, // first line
2812   //   // second line
2813   // };
2814   const FormatToken *MinColumnToken = Line.Tokens.front().Tok;
2815 
2816   // Scan for '{//'. If found, use the column of '{' as a min column for line
2817   // comment section continuation.
2818   const FormatToken *PreviousToken = nullptr;
2819   for (const UnwrappedLineNode &Node : Line.Tokens) {
2820     if (PreviousToken && PreviousToken->is(tok::l_brace) &&
2821         isLineComment(*Node.Tok)) {
2822       MinColumnToken = PreviousToken;
2823       break;
2824     }
2825     PreviousToken = Node.Tok;
2826 
2827     // Grab the last newline preceding a token in this unwrapped line.
2828     if (Node.Tok->NewlinesBefore > 0) {
2829       MinColumnToken = Node.Tok;
2830     }
2831   }
2832   if (PreviousToken && PreviousToken->is(tok::l_brace)) {
2833     MinColumnToken = PreviousToken;
2834   }
2835 
2836   return continuesLineComment(FormatTok, /*Previous=*/Line.Tokens.back().Tok,
2837                               MinColumnToken);
2838 }
2839 
2840 void UnwrappedLineParser::flushComments(bool NewlineBeforeNext) {
2841   bool JustComments = Line->Tokens.empty();
2842   for (SmallVectorImpl<FormatToken *>::const_iterator
2843            I = CommentsBeforeNextToken.begin(),
2844            E = CommentsBeforeNextToken.end();
2845        I != E; ++I) {
2846     // Line comments that belong to the same line comment section are put on the
2847     // same line since later we might want to reflow content between them.
2848     // Additional fine-grained breaking of line comment sections is controlled
2849     // by the class BreakableLineCommentSection in case it is desirable to keep
2850     // several line comment sections in the same unwrapped line.
2851     //
2852     // FIXME: Consider putting separate line comment sections as children to the
2853     // unwrapped line instead.
2854     (*I)->ContinuesLineCommentSection =
2855         continuesLineCommentSection(**I, *Line, CommentPragmasRegex);
2856     if (isOnNewLine(**I) && JustComments && !(*I)->ContinuesLineCommentSection)
2857       addUnwrappedLine();
2858     pushToken(*I);
2859   }
2860   if (NewlineBeforeNext && JustComments)
2861     addUnwrappedLine();
2862   CommentsBeforeNextToken.clear();
2863 }
2864 
2865 void UnwrappedLineParser::nextToken(int LevelDifference) {
2866   if (eof())
2867     return;
2868   flushComments(isOnNewLine(*FormatTok));
2869   pushToken(FormatTok);
2870   FormatToken *Previous = FormatTok;
2871   if (Style.Language != FormatStyle::LK_JavaScript)
2872     readToken(LevelDifference);
2873   else
2874     readTokenWithJavaScriptASI();
2875   FormatTok->Previous = Previous;
2876 }
2877 
2878 void UnwrappedLineParser::distributeComments(
2879     const SmallVectorImpl<FormatToken *> &Comments,
2880     const FormatToken *NextTok) {
2881   // Whether or not a line comment token continues a line is controlled by
2882   // the method continuesLineCommentSection, with the following caveat:
2883   //
2884   // Define a trail of Comments to be a nonempty proper postfix of Comments such
2885   // that each comment line from the trail is aligned with the next token, if
2886   // the next token exists. If a trail exists, the beginning of the maximal
2887   // trail is marked as a start of a new comment section.
2888   //
2889   // For example in this code:
2890   //
2891   // int a; // line about a
2892   //   // line 1 about b
2893   //   // line 2 about b
2894   //   int b;
2895   //
2896   // the two lines about b form a maximal trail, so there are two sections, the
2897   // first one consisting of the single comment "// line about a" and the
2898   // second one consisting of the next two comments.
2899   if (Comments.empty())
2900     return;
2901   bool ShouldPushCommentsInCurrentLine = true;
2902   bool HasTrailAlignedWithNextToken = false;
2903   unsigned StartOfTrailAlignedWithNextToken = 0;
2904   if (NextTok) {
2905     // We are skipping the first element intentionally.
2906     for (unsigned i = Comments.size() - 1; i > 0; --i) {
2907       if (Comments[i]->OriginalColumn == NextTok->OriginalColumn) {
2908         HasTrailAlignedWithNextToken = true;
2909         StartOfTrailAlignedWithNextToken = i;
2910       }
2911     }
2912   }
2913   for (unsigned i = 0, e = Comments.size(); i < e; ++i) {
2914     FormatToken *FormatTok = Comments[i];
2915     if (HasTrailAlignedWithNextToken && i == StartOfTrailAlignedWithNextToken) {
2916       FormatTok->ContinuesLineCommentSection = false;
2917     } else {
2918       FormatTok->ContinuesLineCommentSection =
2919           continuesLineCommentSection(*FormatTok, *Line, CommentPragmasRegex);
2920     }
2921     if (!FormatTok->ContinuesLineCommentSection &&
2922         (isOnNewLine(*FormatTok) || FormatTok->IsFirst)) {
2923       ShouldPushCommentsInCurrentLine = false;
2924     }
2925     if (ShouldPushCommentsInCurrentLine) {
2926       pushToken(FormatTok);
2927     } else {
2928       CommentsBeforeNextToken.push_back(FormatTok);
2929     }
2930   }
2931 }
2932 
2933 void UnwrappedLineParser::readToken(int LevelDifference) {
2934   SmallVector<FormatToken *, 1> Comments;
2935   do {
2936     FormatTok = Tokens->getNextToken();
2937     assert(FormatTok);
2938     while (!Line->InPPDirective && FormatTok->Tok.is(tok::hash) &&
2939            (FormatTok->HasUnescapedNewline || FormatTok->IsFirst)) {
2940       distributeComments(Comments, FormatTok);
2941       Comments.clear();
2942       // If there is an unfinished unwrapped line, we flush the preprocessor
2943       // directives only after that unwrapped line was finished later.
2944       bool SwitchToPreprocessorLines = !Line->Tokens.empty();
2945       ScopedLineState BlockState(*this, SwitchToPreprocessorLines);
2946       assert((LevelDifference >= 0 ||
2947               static_cast<unsigned>(-LevelDifference) <= Line->Level) &&
2948              "LevelDifference makes Line->Level negative");
2949       Line->Level += LevelDifference;
2950       // Comments stored before the preprocessor directive need to be output
2951       // before the preprocessor directive, at the same level as the
2952       // preprocessor directive, as we consider them to apply to the directive.
2953       if (Style.IndentPPDirectives == FormatStyle::PPDIS_BeforeHash &&
2954           PPBranchLevel > 0)
2955         Line->Level += PPBranchLevel;
2956       flushComments(isOnNewLine(*FormatTok));
2957       parsePPDirective();
2958     }
2959     while (FormatTok->getType() == TT_ConflictStart ||
2960            FormatTok->getType() == TT_ConflictEnd ||
2961            FormatTok->getType() == TT_ConflictAlternative) {
2962       if (FormatTok->getType() == TT_ConflictStart) {
2963         conditionalCompilationStart(/*Unreachable=*/false);
2964       } else if (FormatTok->getType() == TT_ConflictAlternative) {
2965         conditionalCompilationAlternative();
2966       } else if (FormatTok->getType() == TT_ConflictEnd) {
2967         conditionalCompilationEnd();
2968       }
2969       FormatTok = Tokens->getNextToken();
2970       FormatTok->MustBreakBefore = true;
2971       FormatTok->MustBreakAlignBefore = true;
2972     }
2973 
2974     if (!PPStack.empty() && (PPStack.back().Kind == PP_Unreachable) &&
2975         !Line->InPPDirective) {
2976       continue;
2977     }
2978 
2979     if (!FormatTok->Tok.is(tok::comment)) {
2980       distributeComments(Comments, FormatTok);
2981       Comments.clear();
2982       return;
2983     }
2984 
2985     Comments.push_back(FormatTok);
2986   } while (!eof());
2987 
2988   distributeComments(Comments, nullptr);
2989   Comments.clear();
2990 }
2991 
2992 void UnwrappedLineParser::pushToken(FormatToken *Tok) {
2993   Line->Tokens.push_back(UnwrappedLineNode(Tok));
2994   if (MustBreakBeforeNextToken) {
2995     Line->Tokens.back().Tok->MustBreakBefore = true;
2996     Line->Tokens.back().Tok->MustBreakAlignBefore = true;
2997     MustBreakBeforeNextToken = false;
2998   }
2999 }
3000 
3001 } // end namespace format
3002 } // end namespace clang
3003