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