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