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