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