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