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