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