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/ADT/STLExtras.h"
18 #include "llvm/Support/Debug.h"
19 #include "llvm/Support/raw_ostream.h"
20 
21 #define DEBUG_TYPE "format-parser"
22 
23 namespace clang {
24 namespace format {
25 
26 class FormatTokenSource {
27 public:
28   virtual ~FormatTokenSource() {}
29   virtual FormatToken *getNextToken() = 0;
30 
31   virtual unsigned getPosition() = 0;
32   virtual FormatToken *setPosition(unsigned Position) = 0;
33 };
34 
35 namespace {
36 
37 class ScopedDeclarationState {
38 public:
39   ScopedDeclarationState(UnwrappedLine &Line, std::vector<bool> &Stack,
40                          bool MustBeDeclaration)
41       : Line(Line), Stack(Stack) {
42     Line.MustBeDeclaration = MustBeDeclaration;
43     Stack.push_back(MustBeDeclaration);
44   }
45   ~ScopedDeclarationState() {
46     Stack.pop_back();
47     if (!Stack.empty())
48       Line.MustBeDeclaration = Stack.back();
49     else
50       Line.MustBeDeclaration = true;
51   }
52 
53 private:
54   UnwrappedLine &Line;
55   std::vector<bool> &Stack;
56 };
57 
58 class ScopedMacroState : public FormatTokenSource {
59 public:
60   ScopedMacroState(UnwrappedLine &Line, FormatTokenSource *&TokenSource,
61                    FormatToken *&ResetToken)
62       : Line(Line), TokenSource(TokenSource), ResetToken(ResetToken),
63         PreviousLineLevel(Line.Level), PreviousTokenSource(TokenSource),
64         Token(nullptr) {
65     TokenSource = this;
66     Line.Level = 0;
67     Line.InPPDirective = true;
68   }
69 
70   ~ScopedMacroState() override {
71     TokenSource = PreviousTokenSource;
72     ResetToken = Token;
73     Line.InPPDirective = false;
74     Line.Level = PreviousLineLevel;
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 
114   FormatToken *Token;
115 };
116 
117 } // end anonymous namespace
118 
119 class ScopedLineState {
120 public:
121   ScopedLineState(UnwrappedLineParser &Parser,
122                   bool SwitchToPreprocessorLines = false)
123       : Parser(Parser), OriginalLines(Parser.CurrentLines) {
124     if (SwitchToPreprocessorLines)
125       Parser.CurrentLines = &Parser.PreprocessorDirectives;
126     else if (!Parser.Line->Tokens.empty())
127       Parser.CurrentLines = &Parser.Line->Tokens.back().Children;
128     PreBlockLine = std::move(Parser.Line);
129     Parser.Line = llvm::make_unique<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 = std::move(PreBlockLine);
140     if (Parser.CurrentLines == &Parser.PreprocessorDirectives)
141       Parser.MustBreakBeforeNextToken = true;
142     Parser.CurrentLines = OriginalLines;
143   }
144 
145 private:
146   UnwrappedLineParser &Parser;
147 
148   std::unique_ptr<UnwrappedLine> PreBlockLine;
149   SmallVectorImpl<UnwrappedLine> *OriginalLines;
150 };
151 
152 class CompoundStatementIndenter {
153 public:
154   CompoundStatementIndenter(UnwrappedLineParser *Parser,
155                             const FormatStyle &Style, unsigned &LineLevel)
156       : LineLevel(LineLevel), OldLineLevel(LineLevel) {
157     if (Style.BreakBeforeBraces == FormatStyle::BS_Allman) {
158       Parser->addUnwrappedLine();
159     } else if (Style.BreakBeforeBraces == FormatStyle::BS_GNU) {
160       Parser->addUnwrappedLine();
161       ++LineLevel;
162     }
163   }
164   ~CompoundStatementIndenter() { LineLevel = OldLineLevel; }
165 
166 private:
167   unsigned &LineLevel;
168   unsigned OldLineLevel;
169 };
170 
171 namespace {
172 
173 class IndexedTokenSource : public FormatTokenSource {
174 public:
175   IndexedTokenSource(ArrayRef<FormatToken *> Tokens)
176       : Tokens(Tokens), Position(-1) {}
177 
178   FormatToken *getNextToken() override {
179     ++Position;
180     return Tokens[Position];
181   }
182 
183   unsigned getPosition() override {
184     assert(Position >= 0);
185     return Position;
186   }
187 
188   FormatToken *setPosition(unsigned P) override {
189     Position = P;
190     return Tokens[Position];
191   }
192 
193   void reset() { Position = -1; }
194 
195 private:
196   ArrayRef<FormatToken *> Tokens;
197   int Position;
198 };
199 
200 } // end anonymous namespace
201 
202 UnwrappedLineParser::UnwrappedLineParser(const FormatStyle &Style,
203                                          const AdditionalKeywords &Keywords,
204                                          ArrayRef<FormatToken *> Tokens,
205                                          UnwrappedLineConsumer &Callback)
206     : Line(new UnwrappedLine), MustBreakBeforeNextToken(false),
207       CurrentLines(&Lines), Style(Style), Keywords(Keywords), Tokens(nullptr),
208       Callback(Callback), AllTokens(Tokens), PPBranchLevel(-1) {}
209 
210 void UnwrappedLineParser::reset() {
211   PPBranchLevel = -1;
212   Line.reset(new UnwrappedLine);
213   CommentsBeforeNextToken.clear();
214   FormatTok = nullptr;
215   MustBreakBeforeNextToken = false;
216   PreprocessorDirectives.clear();
217   CurrentLines = &Lines;
218   DeclarationScopeStack.clear();
219   PPStack.clear();
220 }
221 
222 void UnwrappedLineParser::parse() {
223   IndexedTokenSource TokenSource(AllTokens);
224   do {
225     DEBUG(llvm::dbgs() << "----\n");
226     reset();
227     Tokens = &TokenSource;
228     TokenSource.reset();
229 
230     readToken();
231     parseFile();
232     // Create line with eof token.
233     pushToken(FormatTok);
234     addUnwrappedLine();
235 
236     for (SmallVectorImpl<UnwrappedLine>::iterator I = Lines.begin(),
237                                                   E = Lines.end();
238          I != E; ++I) {
239       Callback.consumeUnwrappedLine(*I);
240     }
241     Callback.finishRun();
242     Lines.clear();
243     while (!PPLevelBranchIndex.empty() &&
244            PPLevelBranchIndex.back() + 1 >= PPLevelBranchCount.back()) {
245       PPLevelBranchIndex.resize(PPLevelBranchIndex.size() - 1);
246       PPLevelBranchCount.resize(PPLevelBranchCount.size() - 1);
247     }
248     if (!PPLevelBranchIndex.empty()) {
249       ++PPLevelBranchIndex.back();
250       assert(PPLevelBranchIndex.size() == PPLevelBranchCount.size());
251       assert(PPLevelBranchIndex.back() <= PPLevelBranchCount.back());
252     }
253   } while (!PPLevelBranchIndex.empty());
254 
255 }
256 
257 void UnwrappedLineParser::parseFile() {
258   // The top-level context in a file always has declarations, except for pre-
259   // processor directives and JavaScript files.
260   bool MustBeDeclaration =
261       !Line->InPPDirective && Style.Language != FormatStyle::LK_JavaScript;
262   ScopedDeclarationState DeclarationState(*Line, DeclarationScopeStack,
263                                           MustBeDeclaration);
264   parseLevel(/*HasOpeningBrace=*/false);
265   // Make sure to format the remaining tokens.
266   flushComments(true);
267   addUnwrappedLine();
268 }
269 
270 void UnwrappedLineParser::parseLevel(bool HasOpeningBrace) {
271   bool SwitchLabelEncountered = false;
272   do {
273     switch (FormatTok->Tok.getKind()) {
274     case tok::comment:
275       nextToken();
276       addUnwrappedLine();
277       break;
278     case tok::l_brace:
279       // FIXME: Add parameter whether this can happen - if this happens, we must
280       // be in a non-declaration context.
281       parseBlock(/*MustBeDeclaration=*/false);
282       addUnwrappedLine();
283       break;
284     case tok::r_brace:
285       if (HasOpeningBrace)
286         return;
287       nextToken();
288       addUnwrappedLine();
289       break;
290     case tok::kw_default:
291     case tok::kw_case:
292       if (!SwitchLabelEncountered &&
293           (Style.IndentCaseLabels || (Line->InPPDirective && Line->Level == 1)))
294         ++Line->Level;
295       SwitchLabelEncountered = true;
296       parseStructuralElement();
297       break;
298     default:
299       parseStructuralElement();
300       break;
301     }
302   } while (!eof());
303 }
304 
305 void UnwrappedLineParser::calculateBraceTypes() {
306   // We'll parse forward through the tokens until we hit
307   // a closing brace or eof - note that getNextToken() will
308   // parse macros, so this will magically work inside macro
309   // definitions, too.
310   unsigned StoredPosition = Tokens->getPosition();
311   FormatToken *Tok = FormatTok;
312   // Keep a stack of positions of lbrace tokens. We will
313   // update information about whether an lbrace starts a
314   // braced init list or a different block during the loop.
315   SmallVector<FormatToken *, 8> LBraceStack;
316   assert(Tok->Tok.is(tok::l_brace));
317   do {
318     // Get next none-comment token.
319     FormatToken *NextTok;
320     unsigned ReadTokens = 0;
321     do {
322       NextTok = Tokens->getNextToken();
323       ++ReadTokens;
324     } while (NextTok->is(tok::comment));
325 
326     switch (Tok->Tok.getKind()) {
327     case tok::l_brace:
328       LBraceStack.push_back(Tok);
329       break;
330     case tok::r_brace:
331       if (!LBraceStack.empty()) {
332         if (LBraceStack.back()->BlockKind == BK_Unknown) {
333           bool ProbablyBracedList = false;
334           if (Style.Language == FormatStyle::LK_Proto) {
335             ProbablyBracedList = NextTok->isOneOf(tok::comma, tok::r_square);
336           } else {
337             // Using OriginalColumn to distinguish between ObjC methods and
338             // binary operators is a bit hacky.
339             bool NextIsObjCMethod = NextTok->isOneOf(tok::plus, tok::minus) &&
340                                     NextTok->OriginalColumn == 0;
341 
342             // If there is a comma, semicolon or right paren after the closing
343             // brace, we assume this is a braced initializer list.  Note that
344             // regardless how we mark inner braces here, we will overwrite the
345             // BlockKind later if we parse a braced list (where all blocks
346             // inside are by default braced lists), or when we explicitly detect
347             // blocks (for example while parsing lambdas).
348             //
349             // We exclude + and - as they can be ObjC visibility modifiers.
350             ProbablyBracedList =
351                 NextTok->isOneOf(tok::comma, tok::semi, tok::period, tok::colon,
352                                  tok::r_paren, tok::r_square, tok::l_brace,
353                                  tok::l_paren, tok::ellipsis) ||
354                 (NextTok->isBinaryOperator() && !NextIsObjCMethod);
355           }
356           if (ProbablyBracedList) {
357             Tok->BlockKind = BK_BracedInit;
358             LBraceStack.back()->BlockKind = BK_BracedInit;
359           } else {
360             Tok->BlockKind = BK_Block;
361             LBraceStack.back()->BlockKind = BK_Block;
362           }
363         }
364         LBraceStack.pop_back();
365       }
366       break;
367     case tok::at:
368     case tok::semi:
369     case tok::kw_if:
370     case tok::kw_while:
371     case tok::kw_for:
372     case tok::kw_switch:
373     case tok::kw_try:
374     case tok::kw___try:
375       if (!LBraceStack.empty())
376         LBraceStack.back()->BlockKind = BK_Block;
377       break;
378     default:
379       break;
380     }
381     Tok = NextTok;
382   } while (Tok->Tok.isNot(tok::eof) && !LBraceStack.empty());
383   // Assume other blocks for all unclosed opening braces.
384   for (unsigned i = 0, e = LBraceStack.size(); i != e; ++i) {
385     if (LBraceStack[i]->BlockKind == BK_Unknown)
386       LBraceStack[i]->BlockKind = BK_Block;
387   }
388 
389   FormatTok = Tokens->setPosition(StoredPosition);
390 }
391 
392 void UnwrappedLineParser::parseBlock(bool MustBeDeclaration, bool AddLevel,
393                                      bool MunchSemi) {
394   assert(FormatTok->Tok.is(tok::l_brace) && "'{' expected");
395   unsigned InitialLevel = Line->Level;
396   nextToken();
397 
398   addUnwrappedLine();
399 
400   ScopedDeclarationState DeclarationState(*Line, DeclarationScopeStack,
401                                           MustBeDeclaration);
402   if (AddLevel)
403     ++Line->Level;
404   parseLevel(/*HasOpeningBrace=*/true);
405 
406   if (!FormatTok->Tok.is(tok::r_brace)) {
407     Line->Level = InitialLevel;
408     return;
409   }
410 
411   nextToken(); // Munch the closing brace.
412   if (MunchSemi && FormatTok->Tok.is(tok::semi))
413     nextToken();
414   Line->Level = InitialLevel;
415 }
416 
417 static bool isGoogScope(const UnwrappedLine &Line) {
418   // FIXME: Closure-library specific stuff should not be hard-coded but be
419   // configurable.
420   if (Line.Tokens.size() < 4)
421     return false;
422   auto I = Line.Tokens.begin();
423   if (I->Tok->TokenText != "goog")
424     return false;
425   ++I;
426   if (I->Tok->isNot(tok::period))
427     return false;
428   ++I;
429   if (I->Tok->TokenText != "scope")
430     return false;
431   ++I;
432   return I->Tok->is(tok::l_paren);
433 }
434 
435 static bool ShouldBreakBeforeBrace(const FormatStyle &Style,
436                                    const FormatToken &InitialToken) {
437   switch (Style.BreakBeforeBraces) {
438   case FormatStyle::BS_Linux:
439     return InitialToken.isOneOf(tok::kw_namespace, tok::kw_class);
440   case FormatStyle::BS_Allman:
441   case FormatStyle::BS_GNU:
442     return true;
443   default:
444     return false;
445   }
446 }
447 
448 void UnwrappedLineParser::parseChildBlock() {
449   FormatTok->BlockKind = BK_Block;
450   nextToken();
451   {
452     bool GoogScope =
453         Style.Language == FormatStyle::LK_JavaScript && isGoogScope(*Line);
454     ScopedLineState LineState(*this);
455     ScopedDeclarationState DeclarationState(*Line, DeclarationScopeStack,
456                                             /*MustBeDeclaration=*/false);
457     Line->Level += GoogScope ? 0 : 1;
458     parseLevel(/*HasOpeningBrace=*/true);
459     flushComments(isOnNewLine(*FormatTok));
460     Line->Level -= GoogScope ? 0 : 1;
461   }
462   nextToken();
463 }
464 
465 void UnwrappedLineParser::parsePPDirective() {
466   assert(FormatTok->Tok.is(tok::hash) && "'#' expected");
467   ScopedMacroState MacroState(*Line, Tokens, FormatTok);
468   nextToken();
469 
470   if (!FormatTok->Tok.getIdentifierInfo()) {
471     parsePPUnknown();
472     return;
473   }
474 
475   switch (FormatTok->Tok.getIdentifierInfo()->getPPKeywordID()) {
476   case tok::pp_define:
477     parsePPDefine();
478     return;
479   case tok::pp_if:
480     parsePPIf(/*IfDef=*/false);
481     break;
482   case tok::pp_ifdef:
483   case tok::pp_ifndef:
484     parsePPIf(/*IfDef=*/true);
485     break;
486   case tok::pp_else:
487     parsePPElse();
488     break;
489   case tok::pp_elif:
490     parsePPElIf();
491     break;
492   case tok::pp_endif:
493     parsePPEndIf();
494     break;
495   default:
496     parsePPUnknown();
497     break;
498   }
499 }
500 
501 void UnwrappedLineParser::conditionalCompilationCondition(bool Unreachable) {
502   if (Unreachable || (!PPStack.empty() && PPStack.back() == PP_Unreachable))
503     PPStack.push_back(PP_Unreachable);
504   else
505     PPStack.push_back(PP_Conditional);
506 }
507 
508 void UnwrappedLineParser::conditionalCompilationStart(bool Unreachable) {
509   ++PPBranchLevel;
510   assert(PPBranchLevel >= 0 && PPBranchLevel <= (int)PPLevelBranchIndex.size());
511   if (PPBranchLevel == (int)PPLevelBranchIndex.size()) {
512     PPLevelBranchIndex.push_back(0);
513     PPLevelBranchCount.push_back(0);
514   }
515   PPChainBranchIndex.push(0);
516   bool Skip = PPLevelBranchIndex[PPBranchLevel] > 0;
517   conditionalCompilationCondition(Unreachable || Skip);
518 }
519 
520 void UnwrappedLineParser::conditionalCompilationAlternative() {
521   if (!PPStack.empty())
522     PPStack.pop_back();
523   assert(PPBranchLevel < (int)PPLevelBranchIndex.size());
524   if (!PPChainBranchIndex.empty())
525     ++PPChainBranchIndex.top();
526   conditionalCompilationCondition(
527       PPBranchLevel >= 0 && !PPChainBranchIndex.empty() &&
528       PPLevelBranchIndex[PPBranchLevel] != PPChainBranchIndex.top());
529 }
530 
531 void UnwrappedLineParser::conditionalCompilationEnd() {
532   assert(PPBranchLevel < (int)PPLevelBranchIndex.size());
533   if (PPBranchLevel >= 0 && !PPChainBranchIndex.empty()) {
534     if (PPChainBranchIndex.top() + 1 > PPLevelBranchCount[PPBranchLevel]) {
535       PPLevelBranchCount[PPBranchLevel] = PPChainBranchIndex.top() + 1;
536     }
537   }
538   // Guard against #endif's without #if.
539   if (PPBranchLevel > 0)
540     --PPBranchLevel;
541   if (!PPChainBranchIndex.empty())
542     PPChainBranchIndex.pop();
543   if (!PPStack.empty())
544     PPStack.pop_back();
545 }
546 
547 void UnwrappedLineParser::parsePPIf(bool IfDef) {
548   nextToken();
549   bool IsLiteralFalse = (FormatTok->Tok.isLiteral() &&
550                          FormatTok->Tok.getLiteralData() != nullptr &&
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 static bool tokenCanStartNewLine(const 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     case tok::objc_try:
658       // This branch isn't strictly necessary (the kw_try case below would
659       // do this too after the tok::at is parsed above).  But be explicit.
660       parseTryCatch();
661       return;
662     default:
663       break;
664     }
665     break;
666   case tok::kw_asm:
667     nextToken();
668     if (FormatTok->is(tok::l_brace)) {
669       nextToken();
670       while (FormatTok && FormatTok->isNot(tok::eof)) {
671         if (FormatTok->is(tok::r_brace)) {
672           nextToken();
673           break;
674         }
675         FormatTok->Finalized = true;
676         nextToken();
677       }
678     }
679     break;
680   case tok::kw_namespace:
681     parseNamespace();
682     return;
683   case tok::kw_inline:
684     nextToken();
685     if (FormatTok->Tok.is(tok::kw_namespace)) {
686       parseNamespace();
687       return;
688     }
689     break;
690   case tok::kw_public:
691   case tok::kw_protected:
692   case tok::kw_private:
693     if (Style.Language == FormatStyle::LK_Java ||
694         Style.Language == FormatStyle::LK_JavaScript)
695       nextToken();
696     else
697       parseAccessSpecifier();
698     return;
699   case tok::kw_if:
700     parseIfThenElse();
701     return;
702   case tok::kw_for:
703   case tok::kw_while:
704     parseForOrWhileLoop();
705     return;
706   case tok::kw_do:
707     parseDoWhile();
708     return;
709   case tok::kw_switch:
710     parseSwitch();
711     return;
712   case tok::kw_default:
713     nextToken();
714     parseLabel();
715     return;
716   case tok::kw_case:
717     parseCaseLabel();
718     return;
719   case tok::kw_try:
720   case tok::kw___try:
721     parseTryCatch();
722     return;
723   case tok::kw_extern:
724     nextToken();
725     if (FormatTok->Tok.is(tok::string_literal)) {
726       nextToken();
727       if (FormatTok->Tok.is(tok::l_brace)) {
728         parseBlock(/*MustBeDeclaration=*/true, /*AddLevel=*/false);
729         addUnwrappedLine();
730         return;
731       }
732     }
733     break;
734   case tok::kw_export:
735     if (Style.Language == FormatStyle::LK_JavaScript) {
736       parseJavaScriptEs6ImportExport();
737       return;
738     }
739     break;
740   case tok::identifier:
741     if (FormatTok->is(TT_ForEachMacro)) {
742       parseForOrWhileLoop();
743       return;
744     }
745     if (Style.Language == FormatStyle::LK_JavaScript &&
746         FormatTok->is(Keywords.kw_import)) {
747       parseJavaScriptEs6ImportExport();
748       return;
749     }
750     if (FormatTok->is(Keywords.kw_signals)) {
751       nextToken();
752       if (FormatTok->is(tok::colon)) {
753         nextToken();
754         addUnwrappedLine();
755       }
756       return;
757     }
758     // In all other cases, parse the declaration.
759     break;
760   default:
761     break;
762   }
763   do {
764     switch (FormatTok->Tok.getKind()) {
765     case tok::at:
766       nextToken();
767       if (FormatTok->Tok.is(tok::l_brace))
768         parseBracedList();
769       break;
770     case tok::kw_enum:
771       parseEnum();
772       break;
773     case tok::kw_typedef:
774       nextToken();
775       if (FormatTok->isOneOf(Keywords.kw_NS_ENUM, Keywords.kw_NS_OPTIONS,
776                              Keywords.kw_CF_ENUM, Keywords.kw_CF_OPTIONS))
777         parseEnum();
778       break;
779     case tok::kw_struct:
780     case tok::kw_union:
781     case tok::kw_class:
782       parseRecord();
783       // A record declaration or definition is always the start of a structural
784       // element.
785       break;
786     case tok::period:
787       nextToken();
788       // In Java, classes have an implicit static member "class".
789       if (Style.Language == FormatStyle::LK_Java && FormatTok &&
790           FormatTok->is(tok::kw_class))
791         nextToken();
792       break;
793     case tok::semi:
794       nextToken();
795       addUnwrappedLine();
796       return;
797     case tok::r_brace:
798       addUnwrappedLine();
799       return;
800     case tok::l_paren:
801       parseParens();
802       break;
803     case tok::caret:
804       nextToken();
805       if (FormatTok->Tok.isAnyIdentifier() ||
806           FormatTok->isSimpleTypeSpecifier())
807         nextToken();
808       if (FormatTok->is(tok::l_paren))
809         parseParens();
810       if (FormatTok->is(tok::l_brace))
811         parseChildBlock();
812       break;
813     case tok::l_brace:
814       if (!tryToParseBracedList()) {
815         // A block outside of parentheses must be the last part of a
816         // structural element.
817         // FIXME: Figure out cases where this is not true, and add projections
818         // for them (the one we know is missing are lambdas).
819         if (Style.BreakBeforeBraces != FormatStyle::BS_Attach)
820           addUnwrappedLine();
821         FormatTok->Type = TT_FunctionLBrace;
822         parseBlock(/*MustBeDeclaration=*/false);
823         addUnwrappedLine();
824         return;
825       }
826       // Otherwise this was a braced init list, and the structural
827       // element continues.
828       break;
829     case tok::kw_try:
830       // We arrive here when parsing function-try blocks.
831       parseTryCatch();
832       return;
833     case tok::identifier: {
834       // Parse function literal unless 'function' is the first token in a line
835       // in which case this should be treated as a free-standing function.
836       if (Style.Language == FormatStyle::LK_JavaScript &&
837           FormatTok->is(Keywords.kw_function) && Line->Tokens.size() > 0) {
838         tryToParseJSFunction();
839         break;
840       }
841       if ((Style.Language == FormatStyle::LK_JavaScript ||
842            Style.Language == FormatStyle::LK_Java) &&
843           FormatTok->is(Keywords.kw_interface)) {
844         parseRecord();
845         break;
846       }
847 
848       StringRef Text = FormatTok->TokenText;
849       nextToken();
850       if (Line->Tokens.size() == 1 &&
851           // JS doesn't have macros, and within classes colons indicate fields,
852           // not labels.
853           Style.Language != FormatStyle::LK_JavaScript) {
854         if (FormatTok->Tok.is(tok::colon) && !Line->MustBeDeclaration) {
855           parseLabel();
856           return;
857         }
858         // Recognize function-like macro usages without trailing semicolon as
859         // well as free-standing macros like Q_OBJECT.
860         bool FunctionLike = FormatTok->is(tok::l_paren);
861         if (FunctionLike)
862           parseParens();
863         if (FormatTok->NewlinesBefore > 0 &&
864             (Text.size() >= 5 || FunctionLike) &&
865             tokenCanStartNewLine(FormatTok->Tok) && Text == Text.upper()) {
866           addUnwrappedLine();
867           return;
868         }
869       }
870       break;
871     }
872     case tok::equal:
873       nextToken();
874       if (FormatTok->Tok.is(tok::l_brace)) {
875         parseBracedList();
876       }
877       break;
878     case tok::l_square:
879       parseSquare();
880       break;
881     case tok::kw_new:
882       parseNew();
883       break;
884     default:
885       nextToken();
886       break;
887     }
888   } while (!eof());
889 }
890 
891 bool UnwrappedLineParser::tryToParseLambda() {
892   // FIXME: This is a dirty way to access the previous token. Find a better
893   // solution.
894   if (!Line->Tokens.empty() &&
895       (Line->Tokens.back().Tok->isOneOf(tok::identifier, tok::kw_operator,
896                                         tok::kw_new, tok::kw_delete) ||
897        Line->Tokens.back().Tok->closesScope() ||
898        Line->Tokens.back().Tok->isSimpleTypeSpecifier())) {
899     nextToken();
900     return false;
901   }
902   assert(FormatTok->is(tok::l_square));
903   FormatToken &LSquare = *FormatTok;
904   if (!tryToParseLambdaIntroducer())
905     return false;
906 
907   while (FormatTok->isNot(tok::l_brace)) {
908     if (FormatTok->isSimpleTypeSpecifier()) {
909       nextToken();
910       continue;
911     }
912     switch (FormatTok->Tok.getKind()) {
913     case tok::l_brace:
914       break;
915     case tok::l_paren:
916       parseParens();
917       break;
918     case tok::amp:
919     case tok::star:
920     case tok::kw_const:
921     case tok::comma:
922     case tok::less:
923     case tok::greater:
924     case tok::identifier:
925     case tok::coloncolon:
926     case tok::kw_mutable:
927       nextToken();
928       break;
929     case tok::arrow:
930       FormatTok->Type = TT_TrailingReturnArrow;
931       nextToken();
932       break;
933     default:
934       return true;
935     }
936   }
937   LSquare.Type = TT_LambdaLSquare;
938   parseChildBlock();
939   return true;
940 }
941 
942 bool UnwrappedLineParser::tryToParseLambdaIntroducer() {
943   nextToken();
944   if (FormatTok->is(tok::equal)) {
945     nextToken();
946     if (FormatTok->is(tok::r_square)) {
947       nextToken();
948       return true;
949     }
950     if (FormatTok->isNot(tok::comma))
951       return false;
952     nextToken();
953   } else if (FormatTok->is(tok::amp)) {
954     nextToken();
955     if (FormatTok->is(tok::r_square)) {
956       nextToken();
957       return true;
958     }
959     if (!FormatTok->isOneOf(tok::comma, tok::identifier)) {
960       return false;
961     }
962     if (FormatTok->is(tok::comma))
963       nextToken();
964   } else if (FormatTok->is(tok::r_square)) {
965     nextToken();
966     return true;
967   }
968   do {
969     if (FormatTok->is(tok::amp))
970       nextToken();
971     if (!FormatTok->isOneOf(tok::identifier, tok::kw_this))
972       return false;
973     nextToken();
974     if (FormatTok->is(tok::ellipsis))
975       nextToken();
976     if (FormatTok->is(tok::comma)) {
977       nextToken();
978     } else if (FormatTok->is(tok::r_square)) {
979       nextToken();
980       return true;
981     } else {
982       return false;
983     }
984   } while (!eof());
985   return false;
986 }
987 
988 void UnwrappedLineParser::tryToParseJSFunction() {
989   nextToken();
990 
991   // Consume function name.
992   if (FormatTok->is(tok::identifier))
993     nextToken();
994 
995   if (FormatTok->isNot(tok::l_paren))
996     return;
997   nextToken();
998   while (FormatTok->isNot(tok::l_brace)) {
999     // Err on the side of caution in order to avoid consuming the full file in
1000     // case of incomplete code.
1001     if (!FormatTok->isOneOf(tok::identifier, tok::comma, tok::r_paren,
1002                             tok::comment))
1003       return;
1004     nextToken();
1005   }
1006   parseChildBlock();
1007 }
1008 
1009 bool UnwrappedLineParser::tryToParseBracedList() {
1010   if (FormatTok->BlockKind == BK_Unknown)
1011     calculateBraceTypes();
1012   assert(FormatTok->BlockKind != BK_Unknown);
1013   if (FormatTok->BlockKind == BK_Block)
1014     return false;
1015   parseBracedList();
1016   return true;
1017 }
1018 
1019 bool UnwrappedLineParser::parseBracedList(bool ContinueOnSemicolons) {
1020   bool HasError = false;
1021   nextToken();
1022 
1023   // FIXME: Once we have an expression parser in the UnwrappedLineParser,
1024   // replace this by using parseAssigmentExpression() inside.
1025   do {
1026     if (Style.Language == FormatStyle::LK_JavaScript &&
1027         FormatTok->is(Keywords.kw_function)) {
1028       tryToParseJSFunction();
1029       continue;
1030     }
1031     switch (FormatTok->Tok.getKind()) {
1032     case tok::caret:
1033       nextToken();
1034       if (FormatTok->is(tok::l_brace)) {
1035         parseChildBlock();
1036       }
1037       break;
1038     case tok::l_square:
1039       tryToParseLambda();
1040       break;
1041     case tok::l_brace:
1042       // Assume there are no blocks inside a braced init list apart
1043       // from the ones we explicitly parse out (like lambdas).
1044       FormatTok->BlockKind = BK_BracedInit;
1045       parseBracedList();
1046       break;
1047     case tok::r_paren:
1048       // JavaScript can just have free standing methods and getters/setters in
1049       // object literals. Detect them by a "{" following ")".
1050       if (Style.Language == FormatStyle::LK_JavaScript) {
1051         nextToken();
1052         if (FormatTok->is(tok::l_brace))
1053           parseChildBlock();
1054         break;
1055       }
1056       nextToken();
1057       break;
1058     case tok::r_brace:
1059       nextToken();
1060       return !HasError;
1061     case tok::semi:
1062       HasError = true;
1063       if (!ContinueOnSemicolons)
1064         return !HasError;
1065       nextToken();
1066       break;
1067     case tok::comma:
1068       nextToken();
1069       break;
1070     default:
1071       nextToken();
1072       break;
1073     }
1074   } while (!eof());
1075   return false;
1076 }
1077 
1078 void UnwrappedLineParser::parseParens() {
1079   assert(FormatTok->Tok.is(tok::l_paren) && "'(' expected.");
1080   nextToken();
1081   do {
1082     switch (FormatTok->Tok.getKind()) {
1083     case tok::l_paren:
1084       parseParens();
1085       if (Style.Language == FormatStyle::LK_Java && FormatTok->is(tok::l_brace))
1086         parseChildBlock();
1087       break;
1088     case tok::r_paren:
1089       nextToken();
1090       return;
1091     case tok::r_brace:
1092       // A "}" inside parenthesis is an error if there wasn't a matching "{".
1093       return;
1094     case tok::l_square:
1095       tryToParseLambda();
1096       break;
1097     case tok::l_brace:
1098       if (!tryToParseBracedList()) {
1099         parseChildBlock();
1100       }
1101       break;
1102     case tok::at:
1103       nextToken();
1104       if (FormatTok->Tok.is(tok::l_brace))
1105         parseBracedList();
1106       break;
1107     case tok::identifier:
1108       if (Style.Language == FormatStyle::LK_JavaScript &&
1109           FormatTok->is(Keywords.kw_function))
1110         tryToParseJSFunction();
1111       else
1112         nextToken();
1113       break;
1114     default:
1115       nextToken();
1116       break;
1117     }
1118   } while (!eof());
1119 }
1120 
1121 void UnwrappedLineParser::parseSquare() {
1122   assert(FormatTok->Tok.is(tok::l_square) && "'[' expected.");
1123   if (tryToParseLambda())
1124     return;
1125   do {
1126     switch (FormatTok->Tok.getKind()) {
1127     case tok::l_paren:
1128       parseParens();
1129       break;
1130     case tok::r_square:
1131       nextToken();
1132       return;
1133     case tok::r_brace:
1134       // A "}" inside parenthesis is an error if there wasn't a matching "{".
1135       return;
1136     case tok::l_square:
1137       parseSquare();
1138       break;
1139     case tok::l_brace: {
1140       if (!tryToParseBracedList()) {
1141         parseChildBlock();
1142       }
1143       break;
1144     }
1145     case tok::at:
1146       nextToken();
1147       if (FormatTok->Tok.is(tok::l_brace))
1148         parseBracedList();
1149       break;
1150     default:
1151       nextToken();
1152       break;
1153     }
1154   } while (!eof());
1155 }
1156 
1157 void UnwrappedLineParser::parseIfThenElse() {
1158   assert(FormatTok->Tok.is(tok::kw_if) && "'if' expected");
1159   nextToken();
1160   if (FormatTok->Tok.is(tok::l_paren))
1161     parseParens();
1162   bool NeedsUnwrappedLine = false;
1163   if (FormatTok->Tok.is(tok::l_brace)) {
1164     CompoundStatementIndenter Indenter(this, Style, Line->Level);
1165     parseBlock(/*MustBeDeclaration=*/false);
1166     if (Style.BreakBeforeBraces == FormatStyle::BS_Allman ||
1167         Style.BreakBeforeBraces == FormatStyle::BS_GNU) {
1168       addUnwrappedLine();
1169     } else {
1170       NeedsUnwrappedLine = true;
1171     }
1172   } else {
1173     addUnwrappedLine();
1174     ++Line->Level;
1175     parseStructuralElement();
1176     --Line->Level;
1177   }
1178   if (FormatTok->Tok.is(tok::kw_else)) {
1179     if (Style.BreakBeforeBraces == FormatStyle::BS_Stroustrup)
1180       addUnwrappedLine();
1181     nextToken();
1182     if (FormatTok->Tok.is(tok::l_brace)) {
1183       CompoundStatementIndenter Indenter(this, Style, Line->Level);
1184       parseBlock(/*MustBeDeclaration=*/false);
1185       addUnwrappedLine();
1186     } else if (FormatTok->Tok.is(tok::kw_if)) {
1187       parseIfThenElse();
1188     } else {
1189       addUnwrappedLine();
1190       ++Line->Level;
1191       parseStructuralElement();
1192       --Line->Level;
1193     }
1194   } else if (NeedsUnwrappedLine) {
1195     addUnwrappedLine();
1196   }
1197 }
1198 
1199 void UnwrappedLineParser::parseTryCatch() {
1200   assert(FormatTok->isOneOf(tok::kw_try, tok::kw___try) && "'try' expected");
1201   nextToken();
1202   bool NeedsUnwrappedLine = false;
1203   if (FormatTok->is(tok::colon)) {
1204     // We are in a function try block, what comes is an initializer list.
1205     nextToken();
1206     while (FormatTok->is(tok::identifier)) {
1207       nextToken();
1208       if (FormatTok->is(tok::l_paren))
1209         parseParens();
1210       if (FormatTok->is(tok::comma))
1211         nextToken();
1212     }
1213   }
1214   // Parse try with resource.
1215   if (Style.Language == FormatStyle::LK_Java && FormatTok->is(tok::l_paren)) {
1216     parseParens();
1217   }
1218   if (FormatTok->is(tok::l_brace)) {
1219     CompoundStatementIndenter Indenter(this, Style, Line->Level);
1220     parseBlock(/*MustBeDeclaration=*/false);
1221     if (Style.BreakBeforeBraces == FormatStyle::BS_Allman ||
1222         Style.BreakBeforeBraces == FormatStyle::BS_GNU ||
1223         Style.BreakBeforeBraces == FormatStyle::BS_Stroustrup) {
1224       addUnwrappedLine();
1225     } else {
1226       NeedsUnwrappedLine = true;
1227     }
1228   } else if (!FormatTok->is(tok::kw_catch)) {
1229     // The C++ standard requires a compound-statement after a try.
1230     // If there's none, we try to assume there's a structuralElement
1231     // and try to continue.
1232     addUnwrappedLine();
1233     ++Line->Level;
1234     parseStructuralElement();
1235     --Line->Level;
1236   }
1237   while (1) {
1238     if (FormatTok->is(tok::at))
1239       nextToken();
1240     if (!(FormatTok->isOneOf(tok::kw_catch, Keywords.kw___except,
1241                              tok::kw___finally) ||
1242           ((Style.Language == FormatStyle::LK_Java ||
1243             Style.Language == FormatStyle::LK_JavaScript) &&
1244            FormatTok->is(Keywords.kw_finally)) ||
1245           (FormatTok->Tok.isObjCAtKeyword(tok::objc_catch) ||
1246            FormatTok->Tok.isObjCAtKeyword(tok::objc_finally))))
1247       break;
1248     nextToken();
1249     while (FormatTok->isNot(tok::l_brace)) {
1250       if (FormatTok->is(tok::l_paren)) {
1251         parseParens();
1252         continue;
1253       }
1254       if (FormatTok->isOneOf(tok::semi, tok::r_brace, tok::eof))
1255         return;
1256       nextToken();
1257     }
1258     NeedsUnwrappedLine = false;
1259     CompoundStatementIndenter Indenter(this, Style, Line->Level);
1260     parseBlock(/*MustBeDeclaration=*/false);
1261     if (Style.BreakBeforeBraces == FormatStyle::BS_Allman ||
1262         Style.BreakBeforeBraces == FormatStyle::BS_GNU ||
1263         Style.BreakBeforeBraces == FormatStyle::BS_Stroustrup) {
1264       addUnwrappedLine();
1265     } else {
1266       NeedsUnwrappedLine = true;
1267     }
1268   }
1269   if (NeedsUnwrappedLine) {
1270     addUnwrappedLine();
1271   }
1272 }
1273 
1274 void UnwrappedLineParser::parseNamespace() {
1275   assert(FormatTok->Tok.is(tok::kw_namespace) && "'namespace' expected");
1276 
1277   const FormatToken &InitialToken = *FormatTok;
1278   nextToken();
1279   if (FormatTok->Tok.is(tok::identifier))
1280     nextToken();
1281   if (FormatTok->Tok.is(tok::l_brace)) {
1282     if (ShouldBreakBeforeBrace(Style, InitialToken))
1283       addUnwrappedLine();
1284 
1285     bool AddLevel = Style.NamespaceIndentation == FormatStyle::NI_All ||
1286                     (Style.NamespaceIndentation == FormatStyle::NI_Inner &&
1287                      DeclarationScopeStack.size() > 1);
1288     parseBlock(/*MustBeDeclaration=*/true, AddLevel);
1289     // Munch the semicolon after a namespace. This is more common than one would
1290     // think. Puttin the semicolon into its own line is very ugly.
1291     if (FormatTok->Tok.is(tok::semi))
1292       nextToken();
1293     addUnwrappedLine();
1294   }
1295   // FIXME: Add error handling.
1296 }
1297 
1298 void UnwrappedLineParser::parseNew() {
1299   assert(FormatTok->is(tok::kw_new) && "'new' expected");
1300   nextToken();
1301   if (Style.Language != FormatStyle::LK_Java)
1302     return;
1303 
1304   // In Java, we can parse everything up to the parens, which aren't optional.
1305   do {
1306     // There should not be a ;, { or } before the new's open paren.
1307     if (FormatTok->isOneOf(tok::semi, tok::l_brace, tok::r_brace))
1308       return;
1309 
1310     // Consume the parens.
1311     if (FormatTok->is(tok::l_paren)) {
1312       parseParens();
1313 
1314       // If there is a class body of an anonymous class, consume that as child.
1315       if (FormatTok->is(tok::l_brace))
1316         parseChildBlock();
1317       return;
1318     }
1319     nextToken();
1320   } while (!eof());
1321 }
1322 
1323 void UnwrappedLineParser::parseForOrWhileLoop() {
1324   assert(FormatTok->isOneOf(tok::kw_for, tok::kw_while, TT_ForEachMacro) &&
1325          "'for', 'while' or foreach macro expected");
1326   nextToken();
1327   if (FormatTok->Tok.is(tok::l_paren))
1328     parseParens();
1329   if (FormatTok->Tok.is(tok::l_brace)) {
1330     CompoundStatementIndenter Indenter(this, Style, Line->Level);
1331     parseBlock(/*MustBeDeclaration=*/false);
1332     addUnwrappedLine();
1333   } else {
1334     addUnwrappedLine();
1335     ++Line->Level;
1336     parseStructuralElement();
1337     --Line->Level;
1338   }
1339 }
1340 
1341 void UnwrappedLineParser::parseDoWhile() {
1342   assert(FormatTok->Tok.is(tok::kw_do) && "'do' expected");
1343   nextToken();
1344   if (FormatTok->Tok.is(tok::l_brace)) {
1345     CompoundStatementIndenter Indenter(this, Style, Line->Level);
1346     parseBlock(/*MustBeDeclaration=*/false);
1347     if (Style.BreakBeforeBraces == FormatStyle::BS_GNU)
1348       addUnwrappedLine();
1349   } else {
1350     addUnwrappedLine();
1351     ++Line->Level;
1352     parseStructuralElement();
1353     --Line->Level;
1354   }
1355 
1356   // FIXME: Add error handling.
1357   if (!FormatTok->Tok.is(tok::kw_while)) {
1358     addUnwrappedLine();
1359     return;
1360   }
1361 
1362   nextToken();
1363   parseStructuralElement();
1364 }
1365 
1366 void UnwrappedLineParser::parseLabel() {
1367   nextToken();
1368   unsigned OldLineLevel = Line->Level;
1369   if (Line->Level > 1 || (!Line->InPPDirective && Line->Level > 0))
1370     --Line->Level;
1371   if (CommentsBeforeNextToken.empty() && FormatTok->Tok.is(tok::l_brace)) {
1372     CompoundStatementIndenter Indenter(this, Style, Line->Level);
1373     parseBlock(/*MustBeDeclaration=*/false);
1374     if (FormatTok->Tok.is(tok::kw_break)) {
1375       // "break;" after "}" on its own line only for BS_Allman and BS_GNU
1376       if (Style.BreakBeforeBraces == FormatStyle::BS_Allman ||
1377           Style.BreakBeforeBraces == FormatStyle::BS_GNU) {
1378         addUnwrappedLine();
1379       }
1380       parseStructuralElement();
1381     }
1382     addUnwrappedLine();
1383   } else {
1384     if (FormatTok->is(tok::semi))
1385       nextToken();
1386     addUnwrappedLine();
1387   }
1388   Line->Level = OldLineLevel;
1389 }
1390 
1391 void UnwrappedLineParser::parseCaseLabel() {
1392   assert(FormatTok->Tok.is(tok::kw_case) && "'case' expected");
1393   // FIXME: fix handling of complex expressions here.
1394   do {
1395     nextToken();
1396   } while (!eof() && !FormatTok->Tok.is(tok::colon));
1397   parseLabel();
1398 }
1399 
1400 void UnwrappedLineParser::parseSwitch() {
1401   assert(FormatTok->Tok.is(tok::kw_switch) && "'switch' expected");
1402   nextToken();
1403   if (FormatTok->Tok.is(tok::l_paren))
1404     parseParens();
1405   if (FormatTok->Tok.is(tok::l_brace)) {
1406     CompoundStatementIndenter Indenter(this, Style, Line->Level);
1407     parseBlock(/*MustBeDeclaration=*/false);
1408     addUnwrappedLine();
1409   } else {
1410     addUnwrappedLine();
1411     ++Line->Level;
1412     parseStructuralElement();
1413     --Line->Level;
1414   }
1415 }
1416 
1417 void UnwrappedLineParser::parseAccessSpecifier() {
1418   nextToken();
1419   // Understand Qt's slots.
1420   if (FormatTok->isOneOf(Keywords.kw_slots, Keywords.kw_qslots))
1421     nextToken();
1422   // Otherwise, we don't know what it is, and we'd better keep the next token.
1423   if (FormatTok->Tok.is(tok::colon))
1424     nextToken();
1425   addUnwrappedLine();
1426 }
1427 
1428 void UnwrappedLineParser::parseEnum() {
1429   // Won't be 'enum' for NS_ENUMs.
1430   if (FormatTok->Tok.is(tok::kw_enum))
1431     nextToken();
1432 
1433   // Eat up enum class ...
1434   if (FormatTok->Tok.is(tok::kw_class) || FormatTok->Tok.is(tok::kw_struct))
1435     nextToken();
1436   while (FormatTok->Tok.getIdentifierInfo() ||
1437          FormatTok->isOneOf(tok::colon, tok::coloncolon, tok::less,
1438                             tok::greater, tok::comma, tok::question)) {
1439     nextToken();
1440     // We can have macros or attributes in between 'enum' and the enum name.
1441     if (FormatTok->is(tok::l_paren))
1442       parseParens();
1443     if (FormatTok->is(tok::identifier))
1444       nextToken();
1445   }
1446 
1447   // Just a declaration or something is wrong.
1448   if (FormatTok->isNot(tok::l_brace))
1449     return;
1450   FormatTok->BlockKind = BK_Block;
1451 
1452   if (Style.Language == FormatStyle::LK_Java) {
1453     // Java enums are different.
1454     parseJavaEnumBody();
1455     return;
1456   }
1457 
1458   // Parse enum body.
1459   bool HasError = !parseBracedList(/*ContinueOnSemicolons=*/true);
1460   if (HasError) {
1461     if (FormatTok->is(tok::semi))
1462       nextToken();
1463     addUnwrappedLine();
1464   }
1465 
1466   // We fall through to parsing a structural element afterwards, so that in
1467   // enum A {} n, m;
1468   // "} n, m;" will end up in one unwrapped line.
1469 }
1470 
1471 void UnwrappedLineParser::parseJavaEnumBody() {
1472   // Determine whether the enum is simple, i.e. does not have a semicolon or
1473   // constants with class bodies. Simple enums can be formatted like braced
1474   // lists, contracted to a single line, etc.
1475   unsigned StoredPosition = Tokens->getPosition();
1476   bool IsSimple = true;
1477   FormatToken *Tok = Tokens->getNextToken();
1478   while (Tok) {
1479     if (Tok->is(tok::r_brace))
1480       break;
1481     if (Tok->isOneOf(tok::l_brace, tok::semi)) {
1482       IsSimple = false;
1483       break;
1484     }
1485     // FIXME: This will also mark enums with braces in the arguments to enum
1486     // constants as "not simple". This is probably fine in practice, though.
1487     Tok = Tokens->getNextToken();
1488   }
1489   FormatTok = Tokens->setPosition(StoredPosition);
1490 
1491   if (IsSimple) {
1492     parseBracedList();
1493     addUnwrappedLine();
1494     return;
1495   }
1496 
1497   // Parse the body of a more complex enum.
1498   // First add a line for everything up to the "{".
1499   nextToken();
1500   addUnwrappedLine();
1501   ++Line->Level;
1502 
1503   // Parse the enum constants.
1504   while (FormatTok) {
1505     if (FormatTok->is(tok::l_brace)) {
1506       // Parse the constant's class body.
1507       parseBlock(/*MustBeDeclaration=*/true, /*AddLevel=*/true,
1508                  /*MunchSemi=*/false);
1509     } else if (FormatTok->is(tok::l_paren)) {
1510       parseParens();
1511     } else if (FormatTok->is(tok::comma)) {
1512       nextToken();
1513       addUnwrappedLine();
1514     } else if (FormatTok->is(tok::semi)) {
1515       nextToken();
1516       addUnwrappedLine();
1517       break;
1518     } else if (FormatTok->is(tok::r_brace)) {
1519       addUnwrappedLine();
1520       break;
1521     } else {
1522       nextToken();
1523     }
1524   }
1525 
1526   // Parse the class body after the enum's ";" if any.
1527   parseLevel(/*HasOpeningBrace=*/true);
1528   nextToken();
1529   --Line->Level;
1530   addUnwrappedLine();
1531 }
1532 
1533 void UnwrappedLineParser::parseRecord() {
1534   const FormatToken &InitialToken = *FormatTok;
1535   nextToken();
1536 
1537 
1538   // The actual identifier can be a nested name specifier, and in macros
1539   // it is often token-pasted.
1540   while (FormatTok->isOneOf(tok::identifier, tok::coloncolon, tok::hashhash,
1541                             tok::kw___attribute, tok::kw___declspec,
1542                             tok::kw_alignas) ||
1543          ((Style.Language == FormatStyle::LK_Java ||
1544            Style.Language == FormatStyle::LK_JavaScript) &&
1545           FormatTok->isOneOf(tok::period, tok::comma))) {
1546     bool IsNonMacroIdentifier =
1547         FormatTok->is(tok::identifier) &&
1548         FormatTok->TokenText != FormatTok->TokenText.upper();
1549     nextToken();
1550     // We can have macros or attributes in between 'class' and the class name.
1551     if (!IsNonMacroIdentifier && FormatTok->Tok.is(tok::l_paren))
1552       parseParens();
1553   }
1554 
1555   // Note that parsing away template declarations here leads to incorrectly
1556   // accepting function declarations as record declarations.
1557   // In general, we cannot solve this problem. Consider:
1558   // class A<int> B() {}
1559   // which can be a function definition or a class definition when B() is a
1560   // macro. If we find enough real-world cases where this is a problem, we
1561   // can parse for the 'template' keyword in the beginning of the statement,
1562   // and thus rule out the record production in case there is no template
1563   // (this would still leave us with an ambiguity between template function
1564   // and class declarations).
1565   if (FormatTok->Tok.is(tok::colon) || FormatTok->Tok.is(tok::less)) {
1566     while (!eof() && FormatTok->Tok.isNot(tok::l_brace)) {
1567       if (FormatTok->Tok.is(tok::semi))
1568         return;
1569       nextToken();
1570     }
1571   }
1572   if (FormatTok->Tok.is(tok::l_brace)) {
1573     if (ShouldBreakBeforeBrace(Style, InitialToken))
1574       addUnwrappedLine();
1575 
1576     parseBlock(/*MustBeDeclaration=*/true, /*AddLevel=*/true,
1577                /*MunchSemi=*/false);
1578   }
1579   // We fall through to parsing a structural element afterwards, so
1580   // class A {} n, m;
1581   // will end up in one unwrapped line.
1582   // This does not apply for Java and JavaScript.
1583   if (Style.Language == FormatStyle::LK_Java ||
1584       Style.Language == FormatStyle::LK_JavaScript)
1585     addUnwrappedLine();
1586 }
1587 
1588 void UnwrappedLineParser::parseObjCProtocolList() {
1589   assert(FormatTok->Tok.is(tok::less) && "'<' expected.");
1590   do
1591     nextToken();
1592   while (!eof() && FormatTok->Tok.isNot(tok::greater));
1593   nextToken(); // Skip '>'.
1594 }
1595 
1596 void UnwrappedLineParser::parseObjCUntilAtEnd() {
1597   do {
1598     if (FormatTok->Tok.isObjCAtKeyword(tok::objc_end)) {
1599       nextToken();
1600       addUnwrappedLine();
1601       break;
1602     }
1603     if (FormatTok->is(tok::l_brace)) {
1604       parseBlock(/*MustBeDeclaration=*/false);
1605       // In ObjC interfaces, nothing should be following the "}".
1606       addUnwrappedLine();
1607     } else if (FormatTok->is(tok::r_brace)) {
1608       // Ignore stray "}". parseStructuralElement doesn't consume them.
1609       nextToken();
1610       addUnwrappedLine();
1611     } else {
1612       parseStructuralElement();
1613     }
1614   } while (!eof());
1615 }
1616 
1617 void UnwrappedLineParser::parseObjCInterfaceOrImplementation() {
1618   nextToken();
1619   nextToken(); // interface name
1620 
1621   // @interface can be followed by either a base class, or a category.
1622   if (FormatTok->Tok.is(tok::colon)) {
1623     nextToken();
1624     nextToken(); // base class name
1625   } else if (FormatTok->Tok.is(tok::l_paren))
1626     // Skip category, if present.
1627     parseParens();
1628 
1629   if (FormatTok->Tok.is(tok::less))
1630     parseObjCProtocolList();
1631 
1632   if (FormatTok->Tok.is(tok::l_brace)) {
1633     if (Style.BreakBeforeBraces == FormatStyle::BS_Allman ||
1634         Style.BreakBeforeBraces == FormatStyle::BS_GNU)
1635       addUnwrappedLine();
1636     parseBlock(/*MustBeDeclaration=*/true);
1637   }
1638 
1639   // With instance variables, this puts '}' on its own line.  Without instance
1640   // variables, this ends the @interface line.
1641   addUnwrappedLine();
1642 
1643   parseObjCUntilAtEnd();
1644 }
1645 
1646 void UnwrappedLineParser::parseObjCProtocol() {
1647   nextToken();
1648   nextToken(); // protocol name
1649 
1650   if (FormatTok->Tok.is(tok::less))
1651     parseObjCProtocolList();
1652 
1653   // Check for protocol declaration.
1654   if (FormatTok->Tok.is(tok::semi)) {
1655     nextToken();
1656     return addUnwrappedLine();
1657   }
1658 
1659   addUnwrappedLine();
1660   parseObjCUntilAtEnd();
1661 }
1662 
1663 void UnwrappedLineParser::parseJavaScriptEs6ImportExport() {
1664   assert(FormatTok->isOneOf(Keywords.kw_import, tok::kw_export));
1665   nextToken();
1666 
1667   if (FormatTok->isOneOf(tok::kw_const, tok::kw_class, Keywords.kw_function,
1668                          Keywords.kw_var))
1669     return; // Fall through to parsing the corresponding structure.
1670 
1671   if (FormatTok->is(tok::kw_default)) {
1672     nextToken(); // export default ..., fall through after eating 'default'.
1673     return;
1674   }
1675 
1676   if (FormatTok->is(tok::l_brace)) {
1677     FormatTok->BlockKind = BK_Block;
1678     parseBracedList();
1679   }
1680 
1681   while (!eof() && FormatTok->isNot(tok::semi) &&
1682          FormatTok->isNot(tok::l_brace)) {
1683     nextToken();
1684   }
1685 }
1686 
1687 LLVM_ATTRIBUTE_UNUSED static void printDebugInfo(const UnwrappedLine &Line,
1688                                                  StringRef Prefix = "") {
1689   llvm::dbgs() << Prefix << "Line(" << Line.Level << ")"
1690                << (Line.InPPDirective ? " MACRO" : "") << ": ";
1691   for (std::list<UnwrappedLineNode>::const_iterator I = Line.Tokens.begin(),
1692                                                     E = Line.Tokens.end();
1693        I != E; ++I) {
1694     llvm::dbgs() << I->Tok->Tok.getName() << "[" << I->Tok->Type << "] ";
1695   }
1696   for (std::list<UnwrappedLineNode>::const_iterator I = Line.Tokens.begin(),
1697                                                     E = Line.Tokens.end();
1698        I != E; ++I) {
1699     const UnwrappedLineNode &Node = *I;
1700     for (SmallVectorImpl<UnwrappedLine>::const_iterator
1701              I = Node.Children.begin(),
1702              E = Node.Children.end();
1703          I != E; ++I) {
1704       printDebugInfo(*I, "\nChild: ");
1705     }
1706   }
1707   llvm::dbgs() << "\n";
1708 }
1709 
1710 void UnwrappedLineParser::addUnwrappedLine() {
1711   if (Line->Tokens.empty())
1712     return;
1713   DEBUG({
1714     if (CurrentLines == &Lines)
1715       printDebugInfo(*Line);
1716   });
1717   CurrentLines->push_back(*Line);
1718   Line->Tokens.clear();
1719   if (CurrentLines == &Lines && !PreprocessorDirectives.empty()) {
1720     for (SmallVectorImpl<UnwrappedLine>::iterator
1721              I = PreprocessorDirectives.begin(),
1722              E = PreprocessorDirectives.end();
1723          I != E; ++I) {
1724       CurrentLines->push_back(*I);
1725     }
1726     PreprocessorDirectives.clear();
1727   }
1728 }
1729 
1730 bool UnwrappedLineParser::eof() const { return FormatTok->Tok.is(tok::eof); }
1731 
1732 bool UnwrappedLineParser::isOnNewLine(const FormatToken &FormatTok) {
1733   return (Line->InPPDirective || FormatTok.HasUnescapedNewline) &&
1734          FormatTok.NewlinesBefore > 0;
1735 }
1736 
1737 void UnwrappedLineParser::flushComments(bool NewlineBeforeNext) {
1738   bool JustComments = Line->Tokens.empty();
1739   for (SmallVectorImpl<FormatToken *>::const_iterator
1740            I = CommentsBeforeNextToken.begin(),
1741            E = CommentsBeforeNextToken.end();
1742        I != E; ++I) {
1743     if (isOnNewLine(**I) && JustComments) {
1744       addUnwrappedLine();
1745     }
1746     pushToken(*I);
1747   }
1748   if (NewlineBeforeNext && JustComments) {
1749     addUnwrappedLine();
1750   }
1751   CommentsBeforeNextToken.clear();
1752 }
1753 
1754 void UnwrappedLineParser::nextToken() {
1755   if (eof())
1756     return;
1757   flushComments(isOnNewLine(*FormatTok));
1758   pushToken(FormatTok);
1759   readToken();
1760 }
1761 
1762 void UnwrappedLineParser::readToken() {
1763   bool CommentsInCurrentLine = true;
1764   do {
1765     FormatTok = Tokens->getNextToken();
1766     assert(FormatTok);
1767     while (!Line->InPPDirective && FormatTok->Tok.is(tok::hash) &&
1768            (FormatTok->HasUnescapedNewline || FormatTok->IsFirst)) {
1769       // If there is an unfinished unwrapped line, we flush the preprocessor
1770       // directives only after that unwrapped line was finished later.
1771       bool SwitchToPreprocessorLines = !Line->Tokens.empty();
1772       ScopedLineState BlockState(*this, SwitchToPreprocessorLines);
1773       // Comments stored before the preprocessor directive need to be output
1774       // before the preprocessor directive, at the same level as the
1775       // preprocessor directive, as we consider them to apply to the directive.
1776       flushComments(isOnNewLine(*FormatTok));
1777       parsePPDirective();
1778     }
1779     while (FormatTok->Type == TT_ConflictStart ||
1780            FormatTok->Type == TT_ConflictEnd ||
1781            FormatTok->Type == TT_ConflictAlternative) {
1782       if (FormatTok->Type == TT_ConflictStart) {
1783         conditionalCompilationStart(/*Unreachable=*/false);
1784       } else if (FormatTok->Type == TT_ConflictAlternative) {
1785         conditionalCompilationAlternative();
1786       } else if (FormatTok->Type == TT_ConflictEnd) {
1787         conditionalCompilationEnd();
1788       }
1789       FormatTok = Tokens->getNextToken();
1790       FormatTok->MustBreakBefore = true;
1791     }
1792 
1793     if (!PPStack.empty() && (PPStack.back() == PP_Unreachable) &&
1794         !Line->InPPDirective) {
1795       continue;
1796     }
1797 
1798     if (!FormatTok->Tok.is(tok::comment))
1799       return;
1800     if (isOnNewLine(*FormatTok) || FormatTok->IsFirst) {
1801       CommentsInCurrentLine = false;
1802     }
1803     if (CommentsInCurrentLine) {
1804       pushToken(FormatTok);
1805     } else {
1806       CommentsBeforeNextToken.push_back(FormatTok);
1807     }
1808   } while (!eof());
1809 }
1810 
1811 void UnwrappedLineParser::pushToken(FormatToken *Tok) {
1812   Line->Tokens.push_back(UnwrappedLineNode(Tok));
1813   if (MustBreakBeforeNextToken) {
1814     Line->Tokens.back().Tok->MustBreakBefore = true;
1815     MustBreakBeforeNextToken = false;
1816   }
1817 }
1818 
1819 } // end namespace format
1820 } // end namespace clang
1821