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