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