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