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