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 (Style.isCpp() && FormatTok->is(tok::kw_co_await))
2403     nextToken();
2404   if (FormatTok->Tok.is(tok::l_paren))
2405     parseParens();
2406   if (FormatTok->Tok.is(tok::l_brace)) {
2407     CompoundStatementIndenter Indenter(this, Style, Line->Level);
2408     parseBlock();
2409     addUnwrappedLine();
2410   } else {
2411     addUnwrappedLine();
2412     ++Line->Level;
2413     parseStructuralElement();
2414     --Line->Level;
2415   }
2416 }
2417 
2418 void UnwrappedLineParser::parseDoWhile() {
2419   assert(FormatTok->Tok.is(tok::kw_do) && "'do' expected");
2420   nextToken();
2421   if (FormatTok->Tok.is(tok::l_brace)) {
2422     CompoundStatementIndenter Indenter(this, Style, Line->Level);
2423     parseBlock();
2424     if (Style.BraceWrapping.BeforeWhile)
2425       addUnwrappedLine();
2426   } else {
2427     addUnwrappedLine();
2428     ++Line->Level;
2429     parseStructuralElement();
2430     --Line->Level;
2431   }
2432 
2433   // FIXME: Add error handling.
2434   if (!FormatTok->Tok.is(tok::kw_while)) {
2435     addUnwrappedLine();
2436     return;
2437   }
2438 
2439   // If in Whitesmiths mode, the line with the while() needs to be indented
2440   // to the same level as the block.
2441   if (Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths)
2442     ++Line->Level;
2443 
2444   nextToken();
2445   parseStructuralElement();
2446 }
2447 
2448 void UnwrappedLineParser::parseLabel(bool LeftAlignLabel) {
2449   nextToken();
2450   unsigned OldLineLevel = Line->Level;
2451   if (Line->Level > 1 || (!Line->InPPDirective && Line->Level > 0))
2452     --Line->Level;
2453   if (LeftAlignLabel)
2454     Line->Level = 0;
2455 
2456   if (!Style.IndentCaseBlocks && CommentsBeforeNextToken.empty() &&
2457       FormatTok->Tok.is(tok::l_brace)) {
2458 
2459     CompoundStatementIndenter Indenter(this, Line->Level,
2460                                        Style.BraceWrapping.AfterCaseLabel,
2461                                        Style.BraceWrapping.IndentBraces);
2462     parseBlock();
2463     if (FormatTok->Tok.is(tok::kw_break)) {
2464       if (Style.BraceWrapping.AfterControlStatement ==
2465           FormatStyle::BWACS_Always) {
2466         addUnwrappedLine();
2467         if (!Style.IndentCaseBlocks &&
2468             Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths) {
2469           Line->Level++;
2470         }
2471       }
2472       parseStructuralElement();
2473     }
2474     addUnwrappedLine();
2475   } else {
2476     if (FormatTok->is(tok::semi))
2477       nextToken();
2478     addUnwrappedLine();
2479   }
2480   Line->Level = OldLineLevel;
2481   if (FormatTok->isNot(tok::l_brace)) {
2482     parseStructuralElement();
2483     addUnwrappedLine();
2484   }
2485 }
2486 
2487 void UnwrappedLineParser::parseCaseLabel() {
2488   assert(FormatTok->Tok.is(tok::kw_case) && "'case' expected");
2489 
2490   // FIXME: fix handling of complex expressions here.
2491   do {
2492     nextToken();
2493   } while (!eof() && !FormatTok->Tok.is(tok::colon));
2494   parseLabel();
2495 }
2496 
2497 void UnwrappedLineParser::parseSwitch() {
2498   assert(FormatTok->Tok.is(tok::kw_switch) && "'switch' expected");
2499   nextToken();
2500   if (FormatTok->Tok.is(tok::l_paren))
2501     parseParens();
2502   if (FormatTok->Tok.is(tok::l_brace)) {
2503     CompoundStatementIndenter Indenter(this, Style, Line->Level);
2504     parseBlock();
2505     addUnwrappedLine();
2506   } else {
2507     addUnwrappedLine();
2508     ++Line->Level;
2509     parseStructuralElement();
2510     --Line->Level;
2511   }
2512 }
2513 
2514 void UnwrappedLineParser::parseAccessSpecifier() {
2515   nextToken();
2516   // Understand Qt's slots.
2517   if (FormatTok->isOneOf(Keywords.kw_slots, Keywords.kw_qslots))
2518     nextToken();
2519   // Otherwise, we don't know what it is, and we'd better keep the next token.
2520   if (FormatTok->Tok.is(tok::colon))
2521     nextToken();
2522   addUnwrappedLine();
2523 }
2524 
2525 void UnwrappedLineParser::parseConcept() {
2526   assert(FormatTok->Tok.is(tok::kw_concept) && "'concept' expected");
2527   nextToken();
2528   if (!FormatTok->Tok.is(tok::identifier))
2529     return;
2530   nextToken();
2531   if (!FormatTok->Tok.is(tok::equal))
2532     return;
2533   nextToken();
2534   if (FormatTok->Tok.is(tok::kw_requires)) {
2535     nextToken();
2536     parseRequiresExpression(Line->Level);
2537   } else {
2538     parseConstraintExpression(Line->Level);
2539   }
2540 }
2541 
2542 void UnwrappedLineParser::parseRequiresExpression(unsigned int OriginalLevel) {
2543   // requires (R range)
2544   if (FormatTok->Tok.is(tok::l_paren)) {
2545     parseParens();
2546     if (Style.IndentRequires && OriginalLevel != Line->Level) {
2547       addUnwrappedLine();
2548       --Line->Level;
2549     }
2550   }
2551 
2552   if (FormatTok->Tok.is(tok::l_brace)) {
2553     if (Style.BraceWrapping.AfterFunction)
2554       addUnwrappedLine();
2555     FormatTok->setType(TT_FunctionLBrace);
2556     parseBlock();
2557     addUnwrappedLine();
2558   } else {
2559     parseConstraintExpression(OriginalLevel);
2560   }
2561 }
2562 
2563 void UnwrappedLineParser::parseConstraintExpression(
2564     unsigned int OriginalLevel) {
2565   // requires Id<T> && Id<T> || Id<T>
2566   while (
2567       FormatTok->isOneOf(tok::identifier, tok::kw_requires, tok::coloncolon)) {
2568     nextToken();
2569     while (FormatTok->isOneOf(tok::identifier, tok::coloncolon, tok::less,
2570                               tok::greater, tok::comma, tok::ellipsis)) {
2571       if (FormatTok->Tok.is(tok::less)) {
2572         parseBracedList(/*ContinueOnSemicolons=*/false, /*IsEnum=*/false,
2573                         /*ClosingBraceKind=*/tok::greater);
2574         continue;
2575       }
2576       nextToken();
2577     }
2578     if (FormatTok->Tok.is(tok::kw_requires)) {
2579       parseRequiresExpression(OriginalLevel);
2580     }
2581     if (FormatTok->Tok.is(tok::less)) {
2582       parseBracedList(/*ContinueOnSemicolons=*/false, /*IsEnum=*/false,
2583                       /*ClosingBraceKind=*/tok::greater);
2584     }
2585 
2586     if (FormatTok->Tok.is(tok::l_paren)) {
2587       parseParens();
2588     }
2589     if (FormatTok->Tok.is(tok::l_brace)) {
2590       if (Style.BraceWrapping.AfterFunction)
2591         addUnwrappedLine();
2592       FormatTok->setType(TT_FunctionLBrace);
2593       parseBlock();
2594     }
2595     if (FormatTok->Tok.is(tok::semi)) {
2596       // Eat any trailing semi.
2597       nextToken();
2598       addUnwrappedLine();
2599     }
2600     if (FormatTok->Tok.is(tok::colon)) {
2601       return;
2602     }
2603     if (!FormatTok->Tok.isOneOf(tok::ampamp, tok::pipepipe)) {
2604       if (FormatTok->Previous &&
2605           !FormatTok->Previous->isOneOf(tok::identifier, tok::kw_requires,
2606                                         tok::coloncolon)) {
2607         addUnwrappedLine();
2608       }
2609       if (Style.IndentRequires && OriginalLevel != Line->Level) {
2610         --Line->Level;
2611       }
2612       break;
2613     } else {
2614       FormatTok->setType(TT_ConstraintJunctions);
2615     }
2616 
2617     nextToken();
2618   }
2619 }
2620 
2621 void UnwrappedLineParser::parseRequires() {
2622   assert(FormatTok->Tok.is(tok::kw_requires) && "'requires' expected");
2623 
2624   unsigned OriginalLevel = Line->Level;
2625   if (FormatTok->Previous && FormatTok->Previous->is(tok::greater)) {
2626     addUnwrappedLine();
2627     if (Style.IndentRequires) {
2628       Line->Level++;
2629     }
2630   }
2631   nextToken();
2632 
2633   parseRequiresExpression(OriginalLevel);
2634 }
2635 
2636 bool UnwrappedLineParser::parseEnum() {
2637   // Won't be 'enum' for NS_ENUMs.
2638   if (FormatTok->Tok.is(tok::kw_enum))
2639     nextToken();
2640 
2641   const FormatToken &InitialToken = *FormatTok;
2642 
2643   // In TypeScript, "enum" can also be used as property name, e.g. in interface
2644   // declarations. An "enum" keyword followed by a colon would be a syntax
2645   // error and thus assume it is just an identifier.
2646   if (Style.Language == FormatStyle::LK_JavaScript &&
2647       FormatTok->isOneOf(tok::colon, tok::question))
2648     return false;
2649 
2650   // In protobuf, "enum" can be used as a field name.
2651   if (Style.Language == FormatStyle::LK_Proto && FormatTok->is(tok::equal))
2652     return false;
2653 
2654   // Eat up enum class ...
2655   if (FormatTok->Tok.is(tok::kw_class) || FormatTok->Tok.is(tok::kw_struct))
2656     nextToken();
2657 
2658   while (FormatTok->Tok.getIdentifierInfo() ||
2659          FormatTok->isOneOf(tok::colon, tok::coloncolon, tok::less,
2660                             tok::greater, tok::comma, tok::question)) {
2661     nextToken();
2662     // We can have macros or attributes in between 'enum' and the enum name.
2663     if (FormatTok->is(tok::l_paren))
2664       parseParens();
2665     if (FormatTok->is(tok::identifier)) {
2666       nextToken();
2667       // If there are two identifiers in a row, this is likely an elaborate
2668       // return type. In Java, this can be "implements", etc.
2669       if (Style.isCpp() && FormatTok->is(tok::identifier))
2670         return false;
2671     }
2672   }
2673 
2674   // Just a declaration or something is wrong.
2675   if (FormatTok->isNot(tok::l_brace))
2676     return true;
2677   FormatTok->setBlockKind(BK_Block);
2678 
2679   if (Style.Language == FormatStyle::LK_Java) {
2680     // Java enums are different.
2681     parseJavaEnumBody();
2682     return true;
2683   }
2684   if (Style.Language == FormatStyle::LK_Proto) {
2685     parseBlock(/*MustBeDeclaration=*/true);
2686     return true;
2687   }
2688 
2689   if (!Style.AllowShortEnumsOnASingleLine &&
2690       ShouldBreakBeforeBrace(Style, InitialToken))
2691     addUnwrappedLine();
2692   // Parse enum body.
2693   nextToken();
2694   if (!Style.AllowShortEnumsOnASingleLine) {
2695     addUnwrappedLine();
2696     Line->Level += 1;
2697   }
2698   bool HasError = !parseBracedList(/*ContinueOnSemicolons=*/true,
2699                                    /*IsEnum=*/true);
2700   if (!Style.AllowShortEnumsOnASingleLine)
2701     Line->Level -= 1;
2702   if (HasError) {
2703     if (FormatTok->is(tok::semi))
2704       nextToken();
2705     addUnwrappedLine();
2706   }
2707   return true;
2708 
2709   // There is no addUnwrappedLine() here so that we fall through to parsing a
2710   // structural element afterwards. Thus, in "enum A {} n, m;",
2711   // "} n, m;" will end up in one unwrapped line.
2712 }
2713 
2714 bool UnwrappedLineParser::parseStructLike() {
2715   // parseRecord falls through and does not yet add an unwrapped line as a
2716   // record declaration or definition can start a structural element.
2717   parseRecord();
2718   // This does not apply to Java, JavaScript and C#.
2719   if (Style.Language == FormatStyle::LK_Java ||
2720       Style.Language == FormatStyle::LK_JavaScript || Style.isCSharp()) {
2721     if (FormatTok->is(tok::semi))
2722       nextToken();
2723     addUnwrappedLine();
2724     return true;
2725   }
2726   return false;
2727 }
2728 
2729 namespace {
2730 // A class used to set and restore the Token position when peeking
2731 // ahead in the token source.
2732 class ScopedTokenPosition {
2733   unsigned StoredPosition;
2734   FormatTokenSource *Tokens;
2735 
2736 public:
2737   ScopedTokenPosition(FormatTokenSource *Tokens) : Tokens(Tokens) {
2738     assert(Tokens && "Tokens expected to not be null");
2739     StoredPosition = Tokens->getPosition();
2740   }
2741 
2742   ~ScopedTokenPosition() { Tokens->setPosition(StoredPosition); }
2743 };
2744 } // namespace
2745 
2746 // Look to see if we have [[ by looking ahead, if
2747 // its not then rewind to the original position.
2748 bool UnwrappedLineParser::tryToParseSimpleAttribute() {
2749   ScopedTokenPosition AutoPosition(Tokens);
2750   FormatToken *Tok = Tokens->getNextToken();
2751   // We already read the first [ check for the second.
2752   if (!Tok->is(tok::l_square)) {
2753     return false;
2754   }
2755   // Double check that the attribute is just something
2756   // fairly simple.
2757   while (Tok->isNot(tok::eof)) {
2758     if (Tok->is(tok::r_square)) {
2759       break;
2760     }
2761     Tok = Tokens->getNextToken();
2762   }
2763   if (Tok->is(tok::eof))
2764     return false;
2765   Tok = Tokens->getNextToken();
2766   if (!Tok->is(tok::r_square)) {
2767     return false;
2768   }
2769   Tok = Tokens->getNextToken();
2770   if (Tok->is(tok::semi)) {
2771     return false;
2772   }
2773   return true;
2774 }
2775 
2776 void UnwrappedLineParser::parseJavaEnumBody() {
2777   // Determine whether the enum is simple, i.e. does not have a semicolon or
2778   // constants with class bodies. Simple enums can be formatted like braced
2779   // lists, contracted to a single line, etc.
2780   unsigned StoredPosition = Tokens->getPosition();
2781   bool IsSimple = true;
2782   FormatToken *Tok = Tokens->getNextToken();
2783   while (!Tok->is(tok::eof)) {
2784     if (Tok->is(tok::r_brace))
2785       break;
2786     if (Tok->isOneOf(tok::l_brace, tok::semi)) {
2787       IsSimple = false;
2788       break;
2789     }
2790     // FIXME: This will also mark enums with braces in the arguments to enum
2791     // constants as "not simple". This is probably fine in practice, though.
2792     Tok = Tokens->getNextToken();
2793   }
2794   FormatTok = Tokens->setPosition(StoredPosition);
2795 
2796   if (IsSimple) {
2797     nextToken();
2798     parseBracedList();
2799     addUnwrappedLine();
2800     return;
2801   }
2802 
2803   // Parse the body of a more complex enum.
2804   // First add a line for everything up to the "{".
2805   nextToken();
2806   addUnwrappedLine();
2807   ++Line->Level;
2808 
2809   // Parse the enum constants.
2810   while (FormatTok) {
2811     if (FormatTok->is(tok::l_brace)) {
2812       // Parse the constant's class body.
2813       parseBlock(/*MustBeDeclaration=*/true, /*AddLevels=*/1u,
2814                  /*MunchSemi=*/false);
2815     } else if (FormatTok->is(tok::l_paren)) {
2816       parseParens();
2817     } else if (FormatTok->is(tok::comma)) {
2818       nextToken();
2819       addUnwrappedLine();
2820     } else if (FormatTok->is(tok::semi)) {
2821       nextToken();
2822       addUnwrappedLine();
2823       break;
2824     } else if (FormatTok->is(tok::r_brace)) {
2825       addUnwrappedLine();
2826       break;
2827     } else {
2828       nextToken();
2829     }
2830   }
2831 
2832   // Parse the class body after the enum's ";" if any.
2833   parseLevel(/*HasOpeningBrace=*/true);
2834   nextToken();
2835   --Line->Level;
2836   addUnwrappedLine();
2837 }
2838 
2839 void UnwrappedLineParser::parseRecord(bool ParseAsExpr) {
2840   const FormatToken &InitialToken = *FormatTok;
2841   nextToken();
2842 
2843   // The actual identifier can be a nested name specifier, and in macros
2844   // it is often token-pasted.
2845   // An [[attribute]] can be before the identifier.
2846   while (FormatTok->isOneOf(tok::identifier, tok::coloncolon, tok::hashhash,
2847                             tok::kw___attribute, tok::kw___declspec,
2848                             tok::kw_alignas, tok::l_square, tok::r_square) ||
2849          ((Style.Language == FormatStyle::LK_Java ||
2850            Style.Language == FormatStyle::LK_JavaScript) &&
2851           FormatTok->isOneOf(tok::period, tok::comma))) {
2852     if (Style.Language == FormatStyle::LK_JavaScript &&
2853         FormatTok->isOneOf(Keywords.kw_extends, Keywords.kw_implements)) {
2854       // JavaScript/TypeScript supports inline object types in
2855       // extends/implements positions:
2856       //     class Foo implements {bar: number} { }
2857       nextToken();
2858       if (FormatTok->is(tok::l_brace)) {
2859         tryToParseBracedList();
2860         continue;
2861       }
2862     }
2863     bool IsNonMacroIdentifier =
2864         FormatTok->is(tok::identifier) &&
2865         FormatTok->TokenText != FormatTok->TokenText.upper();
2866     nextToken();
2867     // We can have macros or attributes in between 'class' and the class name.
2868     if (!IsNonMacroIdentifier) {
2869       if (FormatTok->Tok.is(tok::l_paren)) {
2870         parseParens();
2871       } else if (FormatTok->is(TT_AttributeSquare)) {
2872         parseSquare();
2873         // Consume the closing TT_AttributeSquare.
2874         if (FormatTok->Next && FormatTok->is(TT_AttributeSquare))
2875           nextToken();
2876       }
2877     }
2878   }
2879 
2880   // Note that parsing away template declarations here leads to incorrectly
2881   // accepting function declarations as record declarations.
2882   // In general, we cannot solve this problem. Consider:
2883   // class A<int> B() {}
2884   // which can be a function definition or a class definition when B() is a
2885   // macro. If we find enough real-world cases where this is a problem, we
2886   // can parse for the 'template' keyword in the beginning of the statement,
2887   // and thus rule out the record production in case there is no template
2888   // (this would still leave us with an ambiguity between template function
2889   // and class declarations).
2890   if (FormatTok->isOneOf(tok::colon, tok::less)) {
2891     while (!eof()) {
2892       if (FormatTok->is(tok::l_brace)) {
2893         calculateBraceTypes(/*ExpectClassBody=*/true);
2894         if (!tryToParseBracedList())
2895           break;
2896       }
2897       if (FormatTok->Tok.is(tok::semi))
2898         return;
2899       if (Style.isCSharp() && FormatTok->is(Keywords.kw_where)) {
2900         addUnwrappedLine();
2901         nextToken();
2902         parseCSharpGenericTypeConstraint();
2903         break;
2904       }
2905       nextToken();
2906     }
2907   }
2908   if (FormatTok->Tok.is(tok::l_brace)) {
2909     if (ParseAsExpr) {
2910       parseChildBlock();
2911     } else {
2912       if (ShouldBreakBeforeBrace(Style, InitialToken))
2913         addUnwrappedLine();
2914 
2915       unsigned AddLevels = Style.IndentAccessModifiers ? 2u : 1u;
2916       parseBlock(/*MustBeDeclaration=*/true, AddLevels, /*MunchSemi=*/false);
2917     }
2918   }
2919   // There is no addUnwrappedLine() here so that we fall through to parsing a
2920   // structural element afterwards. Thus, in "class A {} n, m;",
2921   // "} n, m;" will end up in one unwrapped line.
2922 }
2923 
2924 void UnwrappedLineParser::parseObjCMethod() {
2925   assert(FormatTok->Tok.isOneOf(tok::l_paren, tok::identifier) &&
2926          "'(' or identifier expected.");
2927   do {
2928     if (FormatTok->Tok.is(tok::semi)) {
2929       nextToken();
2930       addUnwrappedLine();
2931       return;
2932     } else if (FormatTok->Tok.is(tok::l_brace)) {
2933       if (Style.BraceWrapping.AfterFunction)
2934         addUnwrappedLine();
2935       parseBlock();
2936       addUnwrappedLine();
2937       return;
2938     } else {
2939       nextToken();
2940     }
2941   } while (!eof());
2942 }
2943 
2944 void UnwrappedLineParser::parseObjCProtocolList() {
2945   assert(FormatTok->Tok.is(tok::less) && "'<' expected.");
2946   do {
2947     nextToken();
2948     // Early exit in case someone forgot a close angle.
2949     if (FormatTok->isOneOf(tok::semi, tok::l_brace) ||
2950         FormatTok->Tok.isObjCAtKeyword(tok::objc_end))
2951       return;
2952   } while (!eof() && FormatTok->Tok.isNot(tok::greater));
2953   nextToken(); // Skip '>'.
2954 }
2955 
2956 void UnwrappedLineParser::parseObjCUntilAtEnd() {
2957   do {
2958     if (FormatTok->Tok.isObjCAtKeyword(tok::objc_end)) {
2959       nextToken();
2960       addUnwrappedLine();
2961       break;
2962     }
2963     if (FormatTok->is(tok::l_brace)) {
2964       parseBlock();
2965       // In ObjC interfaces, nothing should be following the "}".
2966       addUnwrappedLine();
2967     } else if (FormatTok->is(tok::r_brace)) {
2968       // Ignore stray "}". parseStructuralElement doesn't consume them.
2969       nextToken();
2970       addUnwrappedLine();
2971     } else if (FormatTok->isOneOf(tok::minus, tok::plus)) {
2972       nextToken();
2973       parseObjCMethod();
2974     } else {
2975       parseStructuralElement();
2976     }
2977   } while (!eof());
2978 }
2979 
2980 void UnwrappedLineParser::parseObjCInterfaceOrImplementation() {
2981   assert(FormatTok->Tok.getObjCKeywordID() == tok::objc_interface ||
2982          FormatTok->Tok.getObjCKeywordID() == tok::objc_implementation);
2983   nextToken();
2984   nextToken(); // interface name
2985 
2986   // @interface can be followed by a lightweight generic
2987   // specialization list, then either a base class or a category.
2988   if (FormatTok->Tok.is(tok::less)) {
2989     parseObjCLightweightGenerics();
2990   }
2991   if (FormatTok->Tok.is(tok::colon)) {
2992     nextToken();
2993     nextToken(); // base class name
2994     // The base class can also have lightweight generics applied to it.
2995     if (FormatTok->Tok.is(tok::less)) {
2996       parseObjCLightweightGenerics();
2997     }
2998   } else if (FormatTok->Tok.is(tok::l_paren))
2999     // Skip category, if present.
3000     parseParens();
3001 
3002   if (FormatTok->Tok.is(tok::less))
3003     parseObjCProtocolList();
3004 
3005   if (FormatTok->Tok.is(tok::l_brace)) {
3006     if (Style.BraceWrapping.AfterObjCDeclaration)
3007       addUnwrappedLine();
3008     parseBlock(/*MustBeDeclaration=*/true);
3009   }
3010 
3011   // With instance variables, this puts '}' on its own line.  Without instance
3012   // variables, this ends the @interface line.
3013   addUnwrappedLine();
3014 
3015   parseObjCUntilAtEnd();
3016 }
3017 
3018 void UnwrappedLineParser::parseObjCLightweightGenerics() {
3019   assert(FormatTok->Tok.is(tok::less));
3020   // Unlike protocol lists, generic parameterizations support
3021   // nested angles:
3022   //
3023   // @interface Foo<ValueType : id <NSCopying, NSSecureCoding>> :
3024   //     NSObject <NSCopying, NSSecureCoding>
3025   //
3026   // so we need to count how many open angles we have left.
3027   unsigned NumOpenAngles = 1;
3028   do {
3029     nextToken();
3030     // Early exit in case someone forgot a close angle.
3031     if (FormatTok->isOneOf(tok::semi, tok::l_brace) ||
3032         FormatTok->Tok.isObjCAtKeyword(tok::objc_end))
3033       break;
3034     if (FormatTok->Tok.is(tok::less))
3035       ++NumOpenAngles;
3036     else if (FormatTok->Tok.is(tok::greater)) {
3037       assert(NumOpenAngles > 0 && "'>' makes NumOpenAngles negative");
3038       --NumOpenAngles;
3039     }
3040   } while (!eof() && NumOpenAngles != 0);
3041   nextToken(); // Skip '>'.
3042 }
3043 
3044 // Returns true for the declaration/definition form of @protocol,
3045 // false for the expression form.
3046 bool UnwrappedLineParser::parseObjCProtocol() {
3047   assert(FormatTok->Tok.getObjCKeywordID() == tok::objc_protocol);
3048   nextToken();
3049 
3050   if (FormatTok->is(tok::l_paren))
3051     // The expression form of @protocol, e.g. "Protocol* p = @protocol(foo);".
3052     return false;
3053 
3054   // The definition/declaration form,
3055   // @protocol Foo
3056   // - (int)someMethod;
3057   // @end
3058 
3059   nextToken(); // protocol name
3060 
3061   if (FormatTok->Tok.is(tok::less))
3062     parseObjCProtocolList();
3063 
3064   // Check for protocol declaration.
3065   if (FormatTok->Tok.is(tok::semi)) {
3066     nextToken();
3067     addUnwrappedLine();
3068     return true;
3069   }
3070 
3071   addUnwrappedLine();
3072   parseObjCUntilAtEnd();
3073   return true;
3074 }
3075 
3076 void UnwrappedLineParser::parseJavaScriptEs6ImportExport() {
3077   bool IsImport = FormatTok->is(Keywords.kw_import);
3078   assert(IsImport || FormatTok->is(tok::kw_export));
3079   nextToken();
3080 
3081   // Consume the "default" in "export default class/function".
3082   if (FormatTok->is(tok::kw_default))
3083     nextToken();
3084 
3085   // Consume "async function", "function" and "default function", so that these
3086   // get parsed as free-standing JS functions, i.e. do not require a trailing
3087   // semicolon.
3088   if (FormatTok->is(Keywords.kw_async))
3089     nextToken();
3090   if (FormatTok->is(Keywords.kw_function)) {
3091     nextToken();
3092     return;
3093   }
3094 
3095   // For imports, `export *`, `export {...}`, consume the rest of the line up
3096   // to the terminating `;`. For everything else, just return and continue
3097   // parsing the structural element, i.e. the declaration or expression for
3098   // `export default`.
3099   if (!IsImport && !FormatTok->isOneOf(tok::l_brace, tok::star) &&
3100       !FormatTok->isStringLiteral())
3101     return;
3102 
3103   while (!eof()) {
3104     if (FormatTok->is(tok::semi))
3105       return;
3106     if (Line->Tokens.empty()) {
3107       // Common issue: Automatic Semicolon Insertion wrapped the line, so the
3108       // import statement should terminate.
3109       return;
3110     }
3111     if (FormatTok->is(tok::l_brace)) {
3112       FormatTok->setBlockKind(BK_Block);
3113       nextToken();
3114       parseBracedList();
3115     } else {
3116       nextToken();
3117     }
3118   }
3119 }
3120 
3121 void UnwrappedLineParser::parseStatementMacro() {
3122   nextToken();
3123   if (FormatTok->is(tok::l_paren))
3124     parseParens();
3125   if (FormatTok->is(tok::semi))
3126     nextToken();
3127   addUnwrappedLine();
3128 }
3129 
3130 LLVM_ATTRIBUTE_UNUSED static void printDebugInfo(const UnwrappedLine &Line,
3131                                                  StringRef Prefix = "") {
3132   llvm::dbgs() << Prefix << "Line(" << Line.Level
3133                << ", FSC=" << Line.FirstStartColumn << ")"
3134                << (Line.InPPDirective ? " MACRO" : "") << ": ";
3135   for (const auto &Node : Line.Tokens) {
3136     llvm::dbgs() << Node.Tok->Tok.getName() << "["
3137                  << "T=" << static_cast<unsigned>(Node.Tok->getType())
3138                  << ", OC=" << Node.Tok->OriginalColumn << "] ";
3139   }
3140   for (const auto &Node : Line.Tokens)
3141     for (const auto &ChildNode : Node.Children)
3142       printDebugInfo(ChildNode, "\nChild: ");
3143 
3144   llvm::dbgs() << "\n";
3145 }
3146 
3147 void UnwrappedLineParser::addUnwrappedLine(LineLevel AdjustLevel) {
3148   if (Line->Tokens.empty())
3149     return;
3150   LLVM_DEBUG({
3151     if (CurrentLines == &Lines)
3152       printDebugInfo(*Line);
3153   });
3154 
3155   // If this line closes a block when in Whitesmiths mode, remember that
3156   // information so that the level can be decreased after the line is added.
3157   // This has to happen after the addition of the line since the line itself
3158   // needs to be indented.
3159   bool ClosesWhitesmithsBlock =
3160       Line->MatchingOpeningBlockLineIndex != UnwrappedLine::kInvalidIndex &&
3161       Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths;
3162 
3163   CurrentLines->push_back(std::move(*Line));
3164   Line->Tokens.clear();
3165   Line->MatchingOpeningBlockLineIndex = UnwrappedLine::kInvalidIndex;
3166   Line->FirstStartColumn = 0;
3167 
3168   if (ClosesWhitesmithsBlock && AdjustLevel == LineLevel::Remove)
3169     --Line->Level;
3170   if (CurrentLines == &Lines && !PreprocessorDirectives.empty()) {
3171     CurrentLines->append(
3172         std::make_move_iterator(PreprocessorDirectives.begin()),
3173         std::make_move_iterator(PreprocessorDirectives.end()));
3174     PreprocessorDirectives.clear();
3175   }
3176   // Disconnect the current token from the last token on the previous line.
3177   FormatTok->Previous = nullptr;
3178 }
3179 
3180 bool UnwrappedLineParser::eof() const { return FormatTok->Tok.is(tok::eof); }
3181 
3182 bool UnwrappedLineParser::isOnNewLine(const FormatToken &FormatTok) {
3183   return (Line->InPPDirective || FormatTok.HasUnescapedNewline) &&
3184          FormatTok.NewlinesBefore > 0;
3185 }
3186 
3187 // Checks if \p FormatTok is a line comment that continues the line comment
3188 // section on \p Line.
3189 static bool
3190 continuesLineCommentSection(const FormatToken &FormatTok,
3191                             const UnwrappedLine &Line,
3192                             const llvm::Regex &CommentPragmasRegex) {
3193   if (Line.Tokens.empty())
3194     return false;
3195 
3196   StringRef IndentContent = FormatTok.TokenText;
3197   if (FormatTok.TokenText.startswith("//") ||
3198       FormatTok.TokenText.startswith("/*"))
3199     IndentContent = FormatTok.TokenText.substr(2);
3200   if (CommentPragmasRegex.match(IndentContent))
3201     return false;
3202 
3203   // If Line starts with a line comment, then FormatTok continues the comment
3204   // section if its original column is greater or equal to the original start
3205   // column of the line.
3206   //
3207   // Define the min column token of a line as follows: if a line ends in '{' or
3208   // contains a '{' followed by a line comment, then the min column token is
3209   // that '{'. Otherwise, the min column token of the line is the first token of
3210   // the line.
3211   //
3212   // If Line starts with a token other than a line comment, then FormatTok
3213   // continues the comment section if its original column is greater than the
3214   // original start column of the min column token of the line.
3215   //
3216   // For example, the second line comment continues the first in these cases:
3217   //
3218   // // first line
3219   // // second line
3220   //
3221   // and:
3222   //
3223   // // first line
3224   //  // second line
3225   //
3226   // and:
3227   //
3228   // int i; // first line
3229   //  // second line
3230   //
3231   // and:
3232   //
3233   // do { // first line
3234   //      // second line
3235   //   int i;
3236   // } while (true);
3237   //
3238   // and:
3239   //
3240   // enum {
3241   //   a, // first line
3242   //    // second line
3243   //   b
3244   // };
3245   //
3246   // The second line comment doesn't continue the first in these cases:
3247   //
3248   //   // first line
3249   //  // second line
3250   //
3251   // and:
3252   //
3253   // int i; // first line
3254   // // second line
3255   //
3256   // and:
3257   //
3258   // do { // first line
3259   //   // second line
3260   //   int i;
3261   // } while (true);
3262   //
3263   // and:
3264   //
3265   // enum {
3266   //   a, // first line
3267   //   // second line
3268   // };
3269   const FormatToken *MinColumnToken = Line.Tokens.front().Tok;
3270 
3271   // Scan for '{//'. If found, use the column of '{' as a min column for line
3272   // comment section continuation.
3273   const FormatToken *PreviousToken = nullptr;
3274   for (const UnwrappedLineNode &Node : Line.Tokens) {
3275     if (PreviousToken && PreviousToken->is(tok::l_brace) &&
3276         isLineComment(*Node.Tok)) {
3277       MinColumnToken = PreviousToken;
3278       break;
3279     }
3280     PreviousToken = Node.Tok;
3281 
3282     // Grab the last newline preceding a token in this unwrapped line.
3283     if (Node.Tok->NewlinesBefore > 0) {
3284       MinColumnToken = Node.Tok;
3285     }
3286   }
3287   if (PreviousToken && PreviousToken->is(tok::l_brace)) {
3288     MinColumnToken = PreviousToken;
3289   }
3290 
3291   return continuesLineComment(FormatTok, /*Previous=*/Line.Tokens.back().Tok,
3292                               MinColumnToken);
3293 }
3294 
3295 void UnwrappedLineParser::flushComments(bool NewlineBeforeNext) {
3296   bool JustComments = Line->Tokens.empty();
3297   for (SmallVectorImpl<FormatToken *>::const_iterator
3298            I = CommentsBeforeNextToken.begin(),
3299            E = CommentsBeforeNextToken.end();
3300        I != E; ++I) {
3301     // Line comments that belong to the same line comment section are put on the
3302     // same line since later we might want to reflow content between them.
3303     // Additional fine-grained breaking of line comment sections is controlled
3304     // by the class BreakableLineCommentSection in case it is desirable to keep
3305     // several line comment sections in the same unwrapped line.
3306     //
3307     // FIXME: Consider putting separate line comment sections as children to the
3308     // unwrapped line instead.
3309     (*I)->ContinuesLineCommentSection =
3310         continuesLineCommentSection(**I, *Line, CommentPragmasRegex);
3311     if (isOnNewLine(**I) && JustComments && !(*I)->ContinuesLineCommentSection)
3312       addUnwrappedLine();
3313     pushToken(*I);
3314   }
3315   if (NewlineBeforeNext && JustComments)
3316     addUnwrappedLine();
3317   CommentsBeforeNextToken.clear();
3318 }
3319 
3320 void UnwrappedLineParser::nextToken(int LevelDifference) {
3321   if (eof())
3322     return;
3323   flushComments(isOnNewLine(*FormatTok));
3324   pushToken(FormatTok);
3325   FormatToken *Previous = FormatTok;
3326   if (Style.Language != FormatStyle::LK_JavaScript)
3327     readToken(LevelDifference);
3328   else
3329     readTokenWithJavaScriptASI();
3330   FormatTok->Previous = Previous;
3331 }
3332 
3333 void UnwrappedLineParser::distributeComments(
3334     const SmallVectorImpl<FormatToken *> &Comments,
3335     const FormatToken *NextTok) {
3336   // Whether or not a line comment token continues a line is controlled by
3337   // the method continuesLineCommentSection, with the following caveat:
3338   //
3339   // Define a trail of Comments to be a nonempty proper postfix of Comments such
3340   // that each comment line from the trail is aligned with the next token, if
3341   // the next token exists. If a trail exists, the beginning of the maximal
3342   // trail is marked as a start of a new comment section.
3343   //
3344   // For example in this code:
3345   //
3346   // int a; // line about a
3347   //   // line 1 about b
3348   //   // line 2 about b
3349   //   int b;
3350   //
3351   // the two lines about b form a maximal trail, so there are two sections, the
3352   // first one consisting of the single comment "// line about a" and the
3353   // second one consisting of the next two comments.
3354   if (Comments.empty())
3355     return;
3356   bool ShouldPushCommentsInCurrentLine = true;
3357   bool HasTrailAlignedWithNextToken = false;
3358   unsigned StartOfTrailAlignedWithNextToken = 0;
3359   if (NextTok) {
3360     // We are skipping the first element intentionally.
3361     for (unsigned i = Comments.size() - 1; i > 0; --i) {
3362       if (Comments[i]->OriginalColumn == NextTok->OriginalColumn) {
3363         HasTrailAlignedWithNextToken = true;
3364         StartOfTrailAlignedWithNextToken = i;
3365       }
3366     }
3367   }
3368   for (unsigned i = 0, e = Comments.size(); i < e; ++i) {
3369     FormatToken *FormatTok = Comments[i];
3370     if (HasTrailAlignedWithNextToken && i == StartOfTrailAlignedWithNextToken) {
3371       FormatTok->ContinuesLineCommentSection = false;
3372     } else {
3373       FormatTok->ContinuesLineCommentSection =
3374           continuesLineCommentSection(*FormatTok, *Line, CommentPragmasRegex);
3375     }
3376     if (!FormatTok->ContinuesLineCommentSection &&
3377         (isOnNewLine(*FormatTok) || FormatTok->IsFirst)) {
3378       ShouldPushCommentsInCurrentLine = false;
3379     }
3380     if (ShouldPushCommentsInCurrentLine) {
3381       pushToken(FormatTok);
3382     } else {
3383       CommentsBeforeNextToken.push_back(FormatTok);
3384     }
3385   }
3386 }
3387 
3388 void UnwrappedLineParser::readToken(int LevelDifference) {
3389   SmallVector<FormatToken *, 1> Comments;
3390   do {
3391     FormatTok = Tokens->getNextToken();
3392     assert(FormatTok);
3393     while (FormatTok->getType() == TT_ConflictStart ||
3394            FormatTok->getType() == TT_ConflictEnd ||
3395            FormatTok->getType() == TT_ConflictAlternative) {
3396       if (FormatTok->getType() == TT_ConflictStart) {
3397         conditionalCompilationStart(/*Unreachable=*/false);
3398       } else if (FormatTok->getType() == TT_ConflictAlternative) {
3399         conditionalCompilationAlternative();
3400       } else if (FormatTok->getType() == TT_ConflictEnd) {
3401         conditionalCompilationEnd();
3402       }
3403       FormatTok = Tokens->getNextToken();
3404       FormatTok->MustBreakBefore = true;
3405     }
3406 
3407     while (!Line->InPPDirective && FormatTok->Tok.is(tok::hash) &&
3408            (FormatTok->HasUnescapedNewline || FormatTok->IsFirst)) {
3409       distributeComments(Comments, FormatTok);
3410       Comments.clear();
3411       // If there is an unfinished unwrapped line, we flush the preprocessor
3412       // directives only after that unwrapped line was finished later.
3413       bool SwitchToPreprocessorLines = !Line->Tokens.empty();
3414       ScopedLineState BlockState(*this, SwitchToPreprocessorLines);
3415       assert((LevelDifference >= 0 ||
3416               static_cast<unsigned>(-LevelDifference) <= Line->Level) &&
3417              "LevelDifference makes Line->Level negative");
3418       Line->Level += LevelDifference;
3419       // Comments stored before the preprocessor directive need to be output
3420       // before the preprocessor directive, at the same level as the
3421       // preprocessor directive, as we consider them to apply to the directive.
3422       if (Style.IndentPPDirectives == FormatStyle::PPDIS_BeforeHash &&
3423           PPBranchLevel > 0)
3424         Line->Level += PPBranchLevel;
3425       flushComments(isOnNewLine(*FormatTok));
3426       parsePPDirective();
3427     }
3428 
3429     if (!PPStack.empty() && (PPStack.back().Kind == PP_Unreachable) &&
3430         !Line->InPPDirective) {
3431       continue;
3432     }
3433 
3434     if (!FormatTok->Tok.is(tok::comment)) {
3435       distributeComments(Comments, FormatTok);
3436       Comments.clear();
3437       return;
3438     }
3439 
3440     Comments.push_back(FormatTok);
3441   } while (!eof());
3442 
3443   distributeComments(Comments, nullptr);
3444   Comments.clear();
3445 }
3446 
3447 void UnwrappedLineParser::pushToken(FormatToken *Tok) {
3448   Line->Tokens.push_back(UnwrappedLineNode(Tok));
3449   if (MustBreakBeforeNextToken) {
3450     Line->Tokens.back().Tok->MustBreakBefore = true;
3451     MustBreakBeforeNextToken = false;
3452   }
3453 }
3454 
3455 } // end namespace format
3456 } // end namespace clang
3457