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