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       FormatTok->Finalized = true;
666       while (FormatTok) {
667         FormatTok->Finalized = true;
668         if (FormatTok->is(tok::r_brace)) {
669           nextToken();
670           break;
671         }
672         nextToken();
673       }
674     }
675     break;
676   case tok::kw_namespace:
677     parseNamespace();
678     return;
679   case tok::kw_inline:
680     nextToken();
681     if (FormatTok->Tok.is(tok::kw_namespace)) {
682       parseNamespace();
683       return;
684     }
685     break;
686   case tok::kw_public:
687   case tok::kw_protected:
688   case tok::kw_private:
689     parseAccessSpecifier();
690     return;
691   case tok::kw_if:
692     parseIfThenElse();
693     return;
694   case tok::kw_for:
695   case tok::kw_while:
696     parseForOrWhileLoop();
697     return;
698   case tok::kw_do:
699     parseDoWhile();
700     return;
701   case tok::kw_switch:
702     parseSwitch();
703     return;
704   case tok::kw_default:
705     nextToken();
706     parseLabel();
707     return;
708   case tok::kw_case:
709     parseCaseLabel();
710     return;
711   case tok::kw_try:
712     parseTryCatch();
713     return;
714   case tok::kw_extern:
715     nextToken();
716     if (FormatTok->Tok.is(tok::string_literal)) {
717       nextToken();
718       if (FormatTok->Tok.is(tok::l_brace)) {
719         parseBlock(/*MustBeDeclaration=*/true, /*AddLevel=*/false);
720         addUnwrappedLine();
721         return;
722       }
723     }
724     break;
725   case tok::identifier:
726     if (FormatTok->IsForEachMacro) {
727       parseForOrWhileLoop();
728       return;
729     }
730     // In all other cases, parse the declaration.
731     break;
732   default:
733     break;
734   }
735   do {
736     switch (FormatTok->Tok.getKind()) {
737     case tok::at:
738       nextToken();
739       if (FormatTok->Tok.is(tok::l_brace))
740         parseBracedList();
741       break;
742     case tok::kw_enum:
743       parseEnum();
744       break;
745     case tok::kw_typedef:
746       nextToken();
747       // FIXME: Use the IdentifierTable instead.
748       if (FormatTok->TokenText == "NS_ENUM")
749         parseEnum();
750       break;
751     case tok::kw_struct:
752     case tok::kw_union:
753     case tok::kw_class:
754       parseRecord();
755       // A record declaration or definition is always the start of a structural
756       // element.
757       break;
758     case tok::semi:
759       nextToken();
760       addUnwrappedLine();
761       return;
762     case tok::r_brace:
763       addUnwrappedLine();
764       return;
765     case tok::l_paren:
766       parseParens();
767       break;
768     case tok::caret:
769       nextToken();
770       if (FormatTok->Tok.isAnyIdentifier() ||
771           FormatTok->isSimpleTypeSpecifier())
772         nextToken();
773       if (FormatTok->is(tok::l_paren))
774         parseParens();
775       if (FormatTok->is(tok::l_brace))
776         parseChildBlock();
777       break;
778     case tok::l_brace:
779       if (!tryToParseBracedList()) {
780         // A block outside of parentheses must be the last part of a
781         // structural element.
782         // FIXME: Figure out cases where this is not true, and add projections
783         // for them (the one we know is missing are lambdas).
784         if (Style.BreakBeforeBraces != FormatStyle::BS_Attach)
785           addUnwrappedLine();
786         FormatTok->Type = TT_FunctionLBrace;
787         parseBlock(/*MustBeDeclaration=*/false);
788         addUnwrappedLine();
789         return;
790       }
791       // Otherwise this was a braced init list, and the structural
792       // element continues.
793       break;
794     case tok::kw_try:
795       // We arrive here when parsing function-try blocks.
796       parseTryCatch();
797       return;
798     case tok::identifier: {
799       StringRef Text = FormatTok->TokenText;
800       // Parse function literal unless 'function' is the first token in a line
801       // in which case this should be treated as a free-standing function.
802       if (Style.Language == FormatStyle::LK_JavaScript && Text == "function" &&
803           Line->Tokens.size() > 0) {
804         tryToParseJSFunction();
805         break;
806       }
807       nextToken();
808       if (Line->Tokens.size() == 1) {
809         if (FormatTok->Tok.is(tok::colon)) {
810           parseLabel();
811           return;
812         }
813         // Recognize function-like macro usages without trailing semicolon.
814         if (FormatTok->Tok.is(tok::l_paren)) {
815           parseParens();
816           if (FormatTok->NewlinesBefore > 0 &&
817               tokenCanStartNewLine(FormatTok->Tok) && Text == Text.upper()) {
818             addUnwrappedLine();
819             return;
820           }
821         } else if (FormatTok->HasUnescapedNewline && Text.size() >= 5 &&
822                    Text == Text.upper()) {
823           // Recognize free-standing macros like Q_OBJECT.
824           addUnwrappedLine();
825           return;
826         }
827       }
828       break;
829     }
830     case tok::equal:
831       nextToken();
832       if (FormatTok->Tok.is(tok::l_brace)) {
833         parseBracedList();
834       }
835       break;
836     case tok::l_square:
837       parseSquare();
838       break;
839     default:
840       nextToken();
841       break;
842     }
843   } while (!eof());
844 }
845 
846 bool UnwrappedLineParser::tryToParseLambda() {
847   // FIXME: This is a dirty way to access the previous token. Find a better
848   // solution.
849   if (!Line->Tokens.empty() &&
850       (Line->Tokens.back().Tok->isOneOf(tok::identifier, tok::kw_operator) ||
851        Line->Tokens.back().Tok->closesScope() ||
852        Line->Tokens.back().Tok->isSimpleTypeSpecifier())) {
853     nextToken();
854     return false;
855   }
856   assert(FormatTok->is(tok::l_square));
857   FormatToken &LSquare = *FormatTok;
858   if (!tryToParseLambdaIntroducer())
859     return false;
860 
861   while (FormatTok->isNot(tok::l_brace)) {
862     if (FormatTok->isSimpleTypeSpecifier()) {
863       nextToken();
864       continue;
865     }
866     switch (FormatTok->Tok.getKind()) {
867     case tok::l_brace:
868       break;
869     case tok::l_paren:
870       parseParens();
871       break;
872     case tok::less:
873     case tok::greater:
874     case tok::identifier:
875     case tok::coloncolon:
876     case tok::kw_mutable:
877       nextToken();
878       break;
879     case tok::arrow:
880       FormatTok->Type = TT_TrailingReturnArrow;
881       nextToken();
882       break;
883     default:
884       return true;
885     }
886   }
887   LSquare.Type = TT_LambdaLSquare;
888   parseChildBlock();
889   return true;
890 }
891 
892 bool UnwrappedLineParser::tryToParseLambdaIntroducer() {
893   nextToken();
894   if (FormatTok->is(tok::equal)) {
895     nextToken();
896     if (FormatTok->is(tok::r_square)) {
897       nextToken();
898       return true;
899     }
900     if (FormatTok->isNot(tok::comma))
901       return false;
902     nextToken();
903   } else if (FormatTok->is(tok::amp)) {
904     nextToken();
905     if (FormatTok->is(tok::r_square)) {
906       nextToken();
907       return true;
908     }
909     if (!FormatTok->isOneOf(tok::comma, tok::identifier)) {
910       return false;
911     }
912     if (FormatTok->is(tok::comma))
913       nextToken();
914   } else if (FormatTok->is(tok::r_square)) {
915     nextToken();
916     return true;
917   }
918   do {
919     if (FormatTok->is(tok::amp))
920       nextToken();
921     if (!FormatTok->isOneOf(tok::identifier, tok::kw_this))
922       return false;
923     nextToken();
924     if (FormatTok->is(tok::ellipsis))
925       nextToken();
926     if (FormatTok->is(tok::comma)) {
927       nextToken();
928     } else if (FormatTok->is(tok::r_square)) {
929       nextToken();
930       return true;
931     } else {
932       return false;
933     }
934   } while (!eof());
935   return false;
936 }
937 
938 void UnwrappedLineParser::tryToParseJSFunction() {
939   nextToken();
940 
941   // Consume function name.
942   if (FormatTok->is(tok::identifier))
943       nextToken();
944 
945   if (FormatTok->isNot(tok::l_paren))
946     return;
947   nextToken();
948   while (FormatTok->isNot(tok::l_brace)) {
949     // Err on the side of caution in order to avoid consuming the full file in
950     // case of incomplete code.
951     if (!FormatTok->isOneOf(tok::identifier, tok::comma, tok::r_paren,
952                             tok::comment))
953       return;
954     nextToken();
955   }
956   parseChildBlock();
957 }
958 
959 bool UnwrappedLineParser::tryToParseBracedList() {
960   if (FormatTok->BlockKind == BK_Unknown)
961     calculateBraceTypes();
962   assert(FormatTok->BlockKind != BK_Unknown);
963   if (FormatTok->BlockKind == BK_Block)
964     return false;
965   parseBracedList();
966   return true;
967 }
968 
969 bool UnwrappedLineParser::parseBracedList(bool ContinueOnSemicolons) {
970   bool HasError = false;
971   nextToken();
972 
973   // FIXME: Once we have an expression parser in the UnwrappedLineParser,
974   // replace this by using parseAssigmentExpression() inside.
975   do {
976     if (Style.Language == FormatStyle::LK_JavaScript &&
977         FormatTok->TokenText == "function") {
978       tryToParseJSFunction();
979       continue;
980     }
981     switch (FormatTok->Tok.getKind()) {
982     case tok::caret:
983       nextToken();
984       if (FormatTok->is(tok::l_brace)) {
985         parseChildBlock();
986       }
987       break;
988     case tok::l_square:
989       tryToParseLambda();
990       break;
991     case tok::l_brace:
992       // Assume there are no blocks inside a braced init list apart
993       // from the ones we explicitly parse out (like lambdas).
994       FormatTok->BlockKind = BK_BracedInit;
995       parseBracedList();
996       break;
997     case tok::r_brace:
998       nextToken();
999       return !HasError;
1000     case tok::semi:
1001       HasError = true;
1002       if (!ContinueOnSemicolons)
1003         return !HasError;
1004       nextToken();
1005       break;
1006     case tok::comma:
1007       nextToken();
1008       break;
1009     default:
1010       nextToken();
1011       break;
1012     }
1013   } while (!eof());
1014   return false;
1015 }
1016 
1017 void UnwrappedLineParser::parseParens() {
1018   assert(FormatTok->Tok.is(tok::l_paren) && "'(' expected.");
1019   nextToken();
1020   do {
1021     switch (FormatTok->Tok.getKind()) {
1022     case tok::l_paren:
1023       parseParens();
1024       break;
1025     case tok::r_paren:
1026       nextToken();
1027       return;
1028     case tok::r_brace:
1029       // A "}" inside parenthesis is an error if there wasn't a matching "{".
1030       return;
1031     case tok::l_square:
1032       tryToParseLambda();
1033       break;
1034     case tok::l_brace: {
1035       if (!tryToParseBracedList()) {
1036         parseChildBlock();
1037       }
1038       break;
1039     }
1040     case tok::at:
1041       nextToken();
1042       if (FormatTok->Tok.is(tok::l_brace))
1043         parseBracedList();
1044       break;
1045     default:
1046       nextToken();
1047       break;
1048     }
1049   } while (!eof());
1050 }
1051 
1052 void UnwrappedLineParser::parseSquare() {
1053   assert(FormatTok->Tok.is(tok::l_square) && "'[' expected.");
1054   if (tryToParseLambda())
1055     return;
1056   do {
1057     switch (FormatTok->Tok.getKind()) {
1058     case tok::l_paren:
1059       parseParens();
1060       break;
1061     case tok::r_square:
1062       nextToken();
1063       return;
1064     case tok::r_brace:
1065       // A "}" inside parenthesis is an error if there wasn't a matching "{".
1066       return;
1067     case tok::l_square:
1068       parseSquare();
1069       break;
1070     case tok::l_brace: {
1071       if (!tryToParseBracedList()) {
1072         parseChildBlock();
1073       }
1074       break;
1075     }
1076     case tok::at:
1077       nextToken();
1078       if (FormatTok->Tok.is(tok::l_brace))
1079         parseBracedList();
1080       break;
1081     default:
1082       nextToken();
1083       break;
1084     }
1085   } while (!eof());
1086 }
1087 
1088 void UnwrappedLineParser::parseIfThenElse() {
1089   assert(FormatTok->Tok.is(tok::kw_if) && "'if' expected");
1090   nextToken();
1091   if (FormatTok->Tok.is(tok::l_paren))
1092     parseParens();
1093   bool NeedsUnwrappedLine = false;
1094   if (FormatTok->Tok.is(tok::l_brace)) {
1095     CompoundStatementIndenter Indenter(this, Style, Line->Level);
1096     parseBlock(/*MustBeDeclaration=*/false);
1097     if (Style.BreakBeforeBraces == FormatStyle::BS_Allman ||
1098         Style.BreakBeforeBraces == FormatStyle::BS_GNU) {
1099       addUnwrappedLine();
1100     } else {
1101       NeedsUnwrappedLine = true;
1102     }
1103   } else {
1104     addUnwrappedLine();
1105     ++Line->Level;
1106     parseStructuralElement();
1107     --Line->Level;
1108   }
1109   if (FormatTok->Tok.is(tok::kw_else)) {
1110     if (Style.BreakBeforeBraces == FormatStyle::BS_Stroustrup)
1111       addUnwrappedLine();
1112     nextToken();
1113     if (FormatTok->Tok.is(tok::l_brace)) {
1114       CompoundStatementIndenter Indenter(this, Style, Line->Level);
1115       parseBlock(/*MustBeDeclaration=*/false);
1116       addUnwrappedLine();
1117     } else if (FormatTok->Tok.is(tok::kw_if)) {
1118       parseIfThenElse();
1119     } else {
1120       addUnwrappedLine();
1121       ++Line->Level;
1122       parseStructuralElement();
1123       --Line->Level;
1124     }
1125   } else if (NeedsUnwrappedLine) {
1126     addUnwrappedLine();
1127   }
1128 }
1129 
1130 void UnwrappedLineParser::parseTryCatch() {
1131   assert(FormatTok->is(tok::kw_try) && "'try' expected");
1132   nextToken();
1133   bool NeedsUnwrappedLine = false;
1134   if (FormatTok->is(tok::colon)) {
1135     // We are in a function try block, what comes is an initializer list.
1136     nextToken();
1137     while (FormatTok->is(tok::identifier)) {
1138       nextToken();
1139       if (FormatTok->is(tok::l_paren))
1140         parseParens();
1141       else
1142         StructuralError = true;
1143       if (FormatTok->is(tok::comma))
1144         nextToken();
1145     }
1146   }
1147   if (FormatTok->is(tok::l_brace)) {
1148     CompoundStatementIndenter Indenter(this, Style, Line->Level);
1149     parseBlock(/*MustBeDeclaration=*/false);
1150     if (Style.BreakBeforeBraces == FormatStyle::BS_Allman ||
1151         Style.BreakBeforeBraces == FormatStyle::BS_GNU ||
1152         Style.BreakBeforeBraces == FormatStyle::BS_Stroustrup) {
1153       addUnwrappedLine();
1154     } else {
1155       NeedsUnwrappedLine = true;
1156     }
1157   } else if (!FormatTok->is(tok::kw_catch)) {
1158     // The C++ standard requires a compound-statement after a try.
1159     // If there's none, we try to assume there's a structuralElement
1160     // and try to continue.
1161     StructuralError = true;
1162     addUnwrappedLine();
1163     ++Line->Level;
1164     parseStructuralElement();
1165     --Line->Level;
1166   }
1167   while (FormatTok->is(tok::kw_catch) ||
1168          (Style.Language == FormatStyle::LK_JavaScript &&
1169           FormatTok->TokenText == "finally")) {
1170     nextToken();
1171     while (FormatTok->isNot(tok::l_brace)) {
1172       if (FormatTok->is(tok::l_paren)) {
1173         parseParens();
1174         continue;
1175       }
1176       if (FormatTok->isOneOf(tok::semi, tok::r_brace))
1177         return;
1178       nextToken();
1179     }
1180     NeedsUnwrappedLine = false;
1181     CompoundStatementIndenter Indenter(this, Style, Line->Level);
1182     parseBlock(/*MustBeDeclaration=*/false);
1183     if (Style.BreakBeforeBraces == FormatStyle::BS_Allman ||
1184         Style.BreakBeforeBraces == FormatStyle::BS_GNU ||
1185         Style.BreakBeforeBraces == FormatStyle::BS_Stroustrup) {
1186       addUnwrappedLine();
1187     } else {
1188       NeedsUnwrappedLine = true;
1189     }
1190   }
1191   if (NeedsUnwrappedLine) {
1192     addUnwrappedLine();
1193   }
1194 }
1195 
1196 void UnwrappedLineParser::parseNamespace() {
1197   assert(FormatTok->Tok.is(tok::kw_namespace) && "'namespace' expected");
1198 
1199   const FormatToken &InitialToken = *FormatTok;
1200   nextToken();
1201   if (FormatTok->Tok.is(tok::identifier))
1202     nextToken();
1203   if (FormatTok->Tok.is(tok::l_brace)) {
1204     if (ShouldBreakBeforeBrace(Style, InitialToken))
1205       addUnwrappedLine();
1206 
1207     bool AddLevel = Style.NamespaceIndentation == FormatStyle::NI_All ||
1208                     (Style.NamespaceIndentation == FormatStyle::NI_Inner &&
1209                      DeclarationScopeStack.size() > 1);
1210     parseBlock(/*MustBeDeclaration=*/true, AddLevel);
1211     // Munch the semicolon after a namespace. This is more common than one would
1212     // think. Puttin the semicolon into its own line is very ugly.
1213     if (FormatTok->Tok.is(tok::semi))
1214       nextToken();
1215     addUnwrappedLine();
1216   }
1217   // FIXME: Add error handling.
1218 }
1219 
1220 void UnwrappedLineParser::parseForOrWhileLoop() {
1221   assert((FormatTok->Tok.is(tok::kw_for) || FormatTok->Tok.is(tok::kw_while) ||
1222           FormatTok->IsForEachMacro) &&
1223          "'for', 'while' or foreach macro expected");
1224   nextToken();
1225   if (FormatTok->Tok.is(tok::l_paren))
1226     parseParens();
1227   if (FormatTok->Tok.is(tok::l_brace)) {
1228     CompoundStatementIndenter Indenter(this, Style, Line->Level);
1229     parseBlock(/*MustBeDeclaration=*/false);
1230     addUnwrappedLine();
1231   } else {
1232     addUnwrappedLine();
1233     ++Line->Level;
1234     parseStructuralElement();
1235     --Line->Level;
1236   }
1237 }
1238 
1239 void UnwrappedLineParser::parseDoWhile() {
1240   assert(FormatTok->Tok.is(tok::kw_do) && "'do' expected");
1241   nextToken();
1242   if (FormatTok->Tok.is(tok::l_brace)) {
1243     CompoundStatementIndenter Indenter(this, Style, Line->Level);
1244     parseBlock(/*MustBeDeclaration=*/false);
1245     if (Style.BreakBeforeBraces == FormatStyle::BS_GNU)
1246       addUnwrappedLine();
1247   } else {
1248     addUnwrappedLine();
1249     ++Line->Level;
1250     parseStructuralElement();
1251     --Line->Level;
1252   }
1253 
1254   // FIXME: Add error handling.
1255   if (!FormatTok->Tok.is(tok::kw_while)) {
1256     addUnwrappedLine();
1257     return;
1258   }
1259 
1260   nextToken();
1261   parseStructuralElement();
1262 }
1263 
1264 void UnwrappedLineParser::parseLabel() {
1265   nextToken();
1266   unsigned OldLineLevel = Line->Level;
1267   if (Line->Level > 1 || (!Line->InPPDirective && Line->Level > 0))
1268     --Line->Level;
1269   if (CommentsBeforeNextToken.empty() && FormatTok->Tok.is(tok::l_brace)) {
1270     CompoundStatementIndenter Indenter(this, Style, Line->Level);
1271     parseBlock(/*MustBeDeclaration=*/false);
1272     if (FormatTok->Tok.is(tok::kw_break)) {
1273       // "break;" after "}" on its own line only for BS_Allman and BS_GNU
1274       if (Style.BreakBeforeBraces == FormatStyle::BS_Allman ||
1275           Style.BreakBeforeBraces == FormatStyle::BS_GNU) {
1276         addUnwrappedLine();
1277       }
1278       parseStructuralElement();
1279     }
1280     addUnwrappedLine();
1281   } else {
1282     addUnwrappedLine();
1283   }
1284   Line->Level = OldLineLevel;
1285 }
1286 
1287 void UnwrappedLineParser::parseCaseLabel() {
1288   assert(FormatTok->Tok.is(tok::kw_case) && "'case' expected");
1289   // FIXME: fix handling of complex expressions here.
1290   do {
1291     nextToken();
1292   } while (!eof() && !FormatTok->Tok.is(tok::colon));
1293   parseLabel();
1294 }
1295 
1296 void UnwrappedLineParser::parseSwitch() {
1297   assert(FormatTok->Tok.is(tok::kw_switch) && "'switch' expected");
1298   nextToken();
1299   if (FormatTok->Tok.is(tok::l_paren))
1300     parseParens();
1301   if (FormatTok->Tok.is(tok::l_brace)) {
1302     CompoundStatementIndenter Indenter(this, Style, Line->Level);
1303     parseBlock(/*MustBeDeclaration=*/false);
1304     addUnwrappedLine();
1305   } else {
1306     addUnwrappedLine();
1307     ++Line->Level;
1308     parseStructuralElement();
1309     --Line->Level;
1310   }
1311 }
1312 
1313 void UnwrappedLineParser::parseAccessSpecifier() {
1314   nextToken();
1315   // Understand Qt's slots.
1316   if (FormatTok->is(tok::identifier) &&
1317       (FormatTok->TokenText == "slots" || FormatTok->TokenText == "Q_SLOTS"))
1318     nextToken();
1319   // Otherwise, we don't know what it is, and we'd better keep the next token.
1320   if (FormatTok->Tok.is(tok::colon))
1321     nextToken();
1322   addUnwrappedLine();
1323 }
1324 
1325 void UnwrappedLineParser::parseEnum() {
1326   if (FormatTok->Tok.is(tok::kw_enum)) {
1327     // Won't be 'enum' for NS_ENUMs.
1328     nextToken();
1329   }
1330   // Eat up enum class ...
1331   if (FormatTok->Tok.is(tok::kw_class) || FormatTok->Tok.is(tok::kw_struct))
1332     nextToken();
1333   while (FormatTok->Tok.getIdentifierInfo() ||
1334          FormatTok->isOneOf(tok::colon, tok::coloncolon)) {
1335     nextToken();
1336     // We can have macros or attributes in between 'enum' and the enum name.
1337     if (FormatTok->Tok.is(tok::l_paren)) {
1338       parseParens();
1339     }
1340     if (FormatTok->Tok.is(tok::identifier))
1341       nextToken();
1342   }
1343   if (FormatTok->Tok.is(tok::l_brace)) {
1344     FormatTok->BlockKind = BK_Block;
1345     bool HasError = !parseBracedList(/*ContinueOnSemicolons=*/true);
1346     if (HasError) {
1347       if (FormatTok->is(tok::semi))
1348         nextToken();
1349       addUnwrappedLine();
1350     }
1351   }
1352   // We fall through to parsing a structural element afterwards, so that in
1353   // enum A {} n, m;
1354   // "} n, m;" will end up in one unwrapped line.
1355 }
1356 
1357 void UnwrappedLineParser::parseRecord() {
1358   const FormatToken &InitialToken = *FormatTok;
1359   nextToken();
1360   if (FormatTok->isOneOf(tok::identifier, tok::coloncolon, tok::kw___attribute,
1361                          tok::kw___declspec, tok::kw_alignas)) {
1362     nextToken();
1363     // We can have macros or attributes in between 'class' and the class name.
1364     if (FormatTok->Tok.is(tok::l_paren)) {
1365       parseParens();
1366     }
1367     // The actual identifier can be a nested name specifier, and in macros
1368     // it is often token-pasted.
1369     while (FormatTok->Tok.is(tok::identifier) ||
1370            FormatTok->Tok.is(tok::coloncolon) ||
1371            FormatTok->Tok.is(tok::hashhash))
1372       nextToken();
1373 
1374     // Note that parsing away template declarations here leads to incorrectly
1375     // accepting function declarations as record declarations.
1376     // In general, we cannot solve this problem. Consider:
1377     // class A<int> B() {}
1378     // which can be a function definition or a class definition when B() is a
1379     // macro. If we find enough real-world cases where this is a problem, we
1380     // can parse for the 'template' keyword in the beginning of the statement,
1381     // and thus rule out the record production in case there is no template
1382     // (this would still leave us with an ambiguity between template function
1383     // and class declarations).
1384     if (FormatTok->Tok.is(tok::colon) || FormatTok->Tok.is(tok::less)) {
1385       while (!eof() && FormatTok->Tok.isNot(tok::l_brace)) {
1386         if (FormatTok->Tok.is(tok::semi))
1387           return;
1388         nextToken();
1389       }
1390     }
1391   }
1392   if (FormatTok->Tok.is(tok::l_brace)) {
1393     if (ShouldBreakBeforeBrace(Style, InitialToken))
1394       addUnwrappedLine();
1395 
1396     parseBlock(/*MustBeDeclaration=*/true, /*AddLevel=*/true,
1397                /*MunchSemi=*/false);
1398   }
1399   // We fall through to parsing a structural element afterwards, so
1400   // class A {} n, m;
1401   // will end up in one unwrapped line.
1402 }
1403 
1404 void UnwrappedLineParser::parseObjCProtocolList() {
1405   assert(FormatTok->Tok.is(tok::less) && "'<' expected.");
1406   do
1407     nextToken();
1408   while (!eof() && FormatTok->Tok.isNot(tok::greater));
1409   nextToken(); // Skip '>'.
1410 }
1411 
1412 void UnwrappedLineParser::parseObjCUntilAtEnd() {
1413   do {
1414     if (FormatTok->Tok.isObjCAtKeyword(tok::objc_end)) {
1415       nextToken();
1416       addUnwrappedLine();
1417       break;
1418     }
1419     if (FormatTok->is(tok::l_brace)) {
1420       parseBlock(/*MustBeDeclaration=*/false);
1421       // In ObjC interfaces, nothing should be following the "}".
1422       addUnwrappedLine();
1423     } else if (FormatTok->is(tok::r_brace)) {
1424       // Ignore stray "}". parseStructuralElement doesn't consume them.
1425       nextToken();
1426       addUnwrappedLine();
1427     } else {
1428       parseStructuralElement();
1429     }
1430   } while (!eof());
1431 }
1432 
1433 void UnwrappedLineParser::parseObjCInterfaceOrImplementation() {
1434   nextToken();
1435   nextToken(); // interface name
1436 
1437   // @interface can be followed by either a base class, or a category.
1438   if (FormatTok->Tok.is(tok::colon)) {
1439     nextToken();
1440     nextToken(); // base class name
1441   } else if (FormatTok->Tok.is(tok::l_paren))
1442     // Skip category, if present.
1443     parseParens();
1444 
1445   if (FormatTok->Tok.is(tok::less))
1446     parseObjCProtocolList();
1447 
1448   if (FormatTok->Tok.is(tok::l_brace)) {
1449     if (Style.BreakBeforeBraces == FormatStyle::BS_Allman ||
1450         Style.BreakBeforeBraces == FormatStyle::BS_GNU)
1451       addUnwrappedLine();
1452     parseBlock(/*MustBeDeclaration=*/true);
1453   }
1454 
1455   // With instance variables, this puts '}' on its own line.  Without instance
1456   // variables, this ends the @interface line.
1457   addUnwrappedLine();
1458 
1459   parseObjCUntilAtEnd();
1460 }
1461 
1462 void UnwrappedLineParser::parseObjCProtocol() {
1463   nextToken();
1464   nextToken(); // protocol name
1465 
1466   if (FormatTok->Tok.is(tok::less))
1467     parseObjCProtocolList();
1468 
1469   // Check for protocol declaration.
1470   if (FormatTok->Tok.is(tok::semi)) {
1471     nextToken();
1472     return addUnwrappedLine();
1473   }
1474 
1475   addUnwrappedLine();
1476   parseObjCUntilAtEnd();
1477 }
1478 
1479 LLVM_ATTRIBUTE_UNUSED static void printDebugInfo(const UnwrappedLine &Line,
1480                                                  StringRef Prefix = "") {
1481   llvm::dbgs() << Prefix << "Line(" << Line.Level << ")"
1482                << (Line.InPPDirective ? " MACRO" : "") << ": ";
1483   for (std::list<UnwrappedLineNode>::const_iterator I = Line.Tokens.begin(),
1484                                                     E = Line.Tokens.end();
1485        I != E; ++I) {
1486     llvm::dbgs() << I->Tok->Tok.getName() << "[" << I->Tok->Type << "] ";
1487   }
1488   for (std::list<UnwrappedLineNode>::const_iterator I = Line.Tokens.begin(),
1489                                                     E = Line.Tokens.end();
1490        I != E; ++I) {
1491     const UnwrappedLineNode &Node = *I;
1492     for (SmallVectorImpl<UnwrappedLine>::const_iterator
1493              I = Node.Children.begin(),
1494              E = Node.Children.end();
1495          I != E; ++I) {
1496       printDebugInfo(*I, "\nChild: ");
1497     }
1498   }
1499   llvm::dbgs() << "\n";
1500 }
1501 
1502 void UnwrappedLineParser::addUnwrappedLine() {
1503   if (Line->Tokens.empty())
1504     return;
1505   DEBUG({
1506     if (CurrentLines == &Lines)
1507       printDebugInfo(*Line);
1508   });
1509   CurrentLines->push_back(*Line);
1510   Line->Tokens.clear();
1511   if (CurrentLines == &Lines && !PreprocessorDirectives.empty()) {
1512     for (SmallVectorImpl<UnwrappedLine>::iterator
1513              I = PreprocessorDirectives.begin(),
1514              E = PreprocessorDirectives.end();
1515          I != E; ++I) {
1516       CurrentLines->push_back(*I);
1517     }
1518     PreprocessorDirectives.clear();
1519   }
1520 }
1521 
1522 bool UnwrappedLineParser::eof() const { return FormatTok->Tok.is(tok::eof); }
1523 
1524 bool UnwrappedLineParser::isOnNewLine(const FormatToken &FormatTok) {
1525   return (Line->InPPDirective || FormatTok.HasUnescapedNewline) &&
1526          FormatTok.NewlinesBefore > 0;
1527 }
1528 
1529 void UnwrappedLineParser::flushComments(bool NewlineBeforeNext) {
1530   bool JustComments = Line->Tokens.empty();
1531   for (SmallVectorImpl<FormatToken *>::const_iterator
1532            I = CommentsBeforeNextToken.begin(),
1533            E = CommentsBeforeNextToken.end();
1534        I != E; ++I) {
1535     if (isOnNewLine(**I) && JustComments) {
1536       addUnwrappedLine();
1537     }
1538     pushToken(*I);
1539   }
1540   if (NewlineBeforeNext && JustComments) {
1541     addUnwrappedLine();
1542   }
1543   CommentsBeforeNextToken.clear();
1544 }
1545 
1546 void UnwrappedLineParser::nextToken() {
1547   if (eof())
1548     return;
1549   flushComments(isOnNewLine(*FormatTok));
1550   pushToken(FormatTok);
1551   readToken();
1552 }
1553 
1554 void UnwrappedLineParser::readToken() {
1555   bool CommentsInCurrentLine = true;
1556   do {
1557     FormatTok = Tokens->getNextToken();
1558     assert(FormatTok);
1559     while (!Line->InPPDirective && FormatTok->Tok.is(tok::hash) &&
1560            (FormatTok->HasUnescapedNewline || FormatTok->IsFirst)) {
1561       // If there is an unfinished unwrapped line, we flush the preprocessor
1562       // directives only after that unwrapped line was finished later.
1563       bool SwitchToPreprocessorLines =
1564           !Line->Tokens.empty() && CurrentLines == &Lines;
1565       ScopedLineState BlockState(*this, SwitchToPreprocessorLines);
1566       // Comments stored before the preprocessor directive need to be output
1567       // before the preprocessor directive, at the same level as the
1568       // preprocessor directive, as we consider them to apply to the directive.
1569       flushComments(isOnNewLine(*FormatTok));
1570       parsePPDirective();
1571     }
1572     while (FormatTok->Type == TT_ConflictStart ||
1573            FormatTok->Type == TT_ConflictEnd ||
1574            FormatTok->Type == TT_ConflictAlternative) {
1575       if (FormatTok->Type == TT_ConflictStart) {
1576         conditionalCompilationStart(/*Unreachable=*/false);
1577       } else if (FormatTok->Type == TT_ConflictAlternative) {
1578         conditionalCompilationAlternative();
1579       } else if (FormatTok->Type == TT_ConflictEnd) {
1580         conditionalCompilationEnd();
1581       }
1582       FormatTok = Tokens->getNextToken();
1583       FormatTok->MustBreakBefore = true;
1584     }
1585 
1586     if (!PPStack.empty() && (PPStack.back() == PP_Unreachable) &&
1587         !Line->InPPDirective) {
1588       continue;
1589     }
1590 
1591     if (!FormatTok->Tok.is(tok::comment))
1592       return;
1593     if (isOnNewLine(*FormatTok) || FormatTok->IsFirst) {
1594       CommentsInCurrentLine = false;
1595     }
1596     if (CommentsInCurrentLine) {
1597       pushToken(FormatTok);
1598     } else {
1599       CommentsBeforeNextToken.push_back(FormatTok);
1600     }
1601   } while (!eof());
1602 }
1603 
1604 void UnwrappedLineParser::pushToken(FormatToken *Tok) {
1605   Line->Tokens.push_back(UnwrappedLineNode(Tok));
1606   if (MustBreakBeforeNextToken) {
1607     Line->Tokens.back().Tok->MustBreakBefore = true;
1608     MustBreakBeforeNextToken = false;
1609   }
1610 }
1611 
1612 } // end namespace format
1613 } // end namespace clang
1614