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