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