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::kw_operator:
859       nextToken();
860       if (FormatTok->isBinaryOperator())
861         nextToken();
862       break;
863     case tok::caret:
864       nextToken();
865       if (FormatTok->Tok.isAnyIdentifier() ||
866           FormatTok->isSimpleTypeSpecifier())
867         nextToken();
868       if (FormatTok->is(tok::l_paren))
869         parseParens();
870       if (FormatTok->is(tok::l_brace))
871         parseChildBlock();
872       break;
873     case tok::l_brace:
874       if (!tryToParseBracedList()) {
875         // A block outside of parentheses must be the last part of a
876         // structural element.
877         // FIXME: Figure out cases where this is not true, and add projections
878         // for them (the one we know is missing are lambdas).
879         if (Style.BraceWrapping.AfterFunction)
880           addUnwrappedLine();
881         FormatTok->Type = TT_FunctionLBrace;
882         parseBlock(/*MustBeDeclaration=*/false);
883         addUnwrappedLine();
884         return;
885       }
886       // Otherwise this was a braced init list, and the structural
887       // element continues.
888       break;
889     case tok::kw_try:
890       // We arrive here when parsing function-try blocks.
891       parseTryCatch();
892       return;
893     case tok::identifier: {
894       if (FormatTok->is(TT_MacroBlockEnd)) {
895         addUnwrappedLine();
896         return;
897       }
898 
899       // Parse function literal unless 'function' is the first token in a line
900       // in which case this should be treated as a free-standing function.
901       if (Style.Language == FormatStyle::LK_JavaScript &&
902           FormatTok->is(Keywords.kw_function) && Line->Tokens.size() > 0) {
903         tryToParseJSFunction();
904         break;
905       }
906       if ((Style.Language == FormatStyle::LK_JavaScript ||
907            Style.Language == FormatStyle::LK_Java) &&
908           FormatTok->is(Keywords.kw_interface)) {
909         parseRecord();
910         addUnwrappedLine();
911         return;
912       }
913 
914       StringRef Text = FormatTok->TokenText;
915       nextToken();
916       if (Line->Tokens.size() == 1 &&
917           // JS doesn't have macros, and within classes colons indicate fields,
918           // not labels.
919           Style.Language != FormatStyle::LK_JavaScript) {
920         if (FormatTok->Tok.is(tok::colon) && !Line->MustBeDeclaration) {
921           parseLabel();
922           return;
923         }
924         // Recognize function-like macro usages without trailing semicolon as
925         // well as free-standing macros like Q_OBJECT.
926         bool FunctionLike = FormatTok->is(tok::l_paren);
927         if (FunctionLike)
928           parseParens();
929 
930         bool FollowedByNewline =
931             CommentsBeforeNextToken.empty()
932                 ? FormatTok->NewlinesBefore > 0
933                 : CommentsBeforeNextToken.front()->NewlinesBefore > 0;
934 
935         if (FollowedByNewline && (Text.size() >= 5 || FunctionLike) &&
936             tokenCanStartNewLine(FormatTok->Tok) && Text == Text.upper()) {
937           addUnwrappedLine();
938           return;
939         }
940       }
941       break;
942     }
943     case tok::equal:
944       // Fat arrows (=>) have tok::TokenKind tok::equal but TokenType
945       // TT_JsFatArrow. The always start an expression or a child block if
946       // followed by a curly.
947       if (FormatTok->is(TT_JsFatArrow)) {
948         nextToken();
949         if (FormatTok->is(tok::l_brace))
950           parseChildBlock();
951         break;
952       }
953 
954       nextToken();
955       if (FormatTok->Tok.is(tok::l_brace)) {
956         parseBracedList();
957       }
958       break;
959     case tok::l_square:
960       parseSquare();
961       break;
962     case tok::kw_new:
963       parseNew();
964       break;
965     default:
966       nextToken();
967       break;
968     }
969   } while (!eof());
970 }
971 
972 bool UnwrappedLineParser::tryToParseLambda() {
973   if (Style.Language != FormatStyle::LK_Cpp) {
974     nextToken();
975     return false;
976   }
977   // FIXME: This is a dirty way to access the previous token. Find a better
978   // solution.
979   if (!Line->Tokens.empty() &&
980       (Line->Tokens.back().Tok->isOneOf(tok::identifier, tok::kw_operator,
981                                         tok::kw_new, tok::kw_delete) ||
982        Line->Tokens.back().Tok->closesScope() ||
983        Line->Tokens.back().Tok->isSimpleTypeSpecifier())) {
984     nextToken();
985     return false;
986   }
987   assert(FormatTok->is(tok::l_square));
988   FormatToken &LSquare = *FormatTok;
989   if (!tryToParseLambdaIntroducer())
990     return false;
991 
992   while (FormatTok->isNot(tok::l_brace)) {
993     if (FormatTok->isSimpleTypeSpecifier()) {
994       nextToken();
995       continue;
996     }
997     switch (FormatTok->Tok.getKind()) {
998     case tok::l_brace:
999       break;
1000     case tok::l_paren:
1001       parseParens();
1002       break;
1003     case tok::amp:
1004     case tok::star:
1005     case tok::kw_const:
1006     case tok::comma:
1007     case tok::less:
1008     case tok::greater:
1009     case tok::identifier:
1010     case tok::numeric_constant:
1011     case tok::coloncolon:
1012     case tok::kw_mutable:
1013       nextToken();
1014       break;
1015     case tok::arrow:
1016       FormatTok->Type = TT_LambdaArrow;
1017       nextToken();
1018       break;
1019     default:
1020       return true;
1021     }
1022   }
1023   LSquare.Type = TT_LambdaLSquare;
1024   parseChildBlock();
1025   return true;
1026 }
1027 
1028 bool UnwrappedLineParser::tryToParseLambdaIntroducer() {
1029   nextToken();
1030   if (FormatTok->is(tok::equal)) {
1031     nextToken();
1032     if (FormatTok->is(tok::r_square)) {
1033       nextToken();
1034       return true;
1035     }
1036     if (FormatTok->isNot(tok::comma))
1037       return false;
1038     nextToken();
1039   } else if (FormatTok->is(tok::amp)) {
1040     nextToken();
1041     if (FormatTok->is(tok::r_square)) {
1042       nextToken();
1043       return true;
1044     }
1045     if (!FormatTok->isOneOf(tok::comma, tok::identifier)) {
1046       return false;
1047     }
1048     if (FormatTok->is(tok::comma))
1049       nextToken();
1050   } else if (FormatTok->is(tok::r_square)) {
1051     nextToken();
1052     return true;
1053   }
1054   do {
1055     if (FormatTok->is(tok::amp))
1056       nextToken();
1057     if (!FormatTok->isOneOf(tok::identifier, tok::kw_this))
1058       return false;
1059     nextToken();
1060     if (FormatTok->is(tok::ellipsis))
1061       nextToken();
1062     if (FormatTok->is(tok::comma)) {
1063       nextToken();
1064     } else if (FormatTok->is(tok::r_square)) {
1065       nextToken();
1066       return true;
1067     } else {
1068       return false;
1069     }
1070   } while (!eof());
1071   return false;
1072 }
1073 
1074 void UnwrappedLineParser::tryToParseJSFunction() {
1075   nextToken();
1076 
1077   // Consume function name.
1078   if (FormatTok->is(tok::identifier))
1079     nextToken();
1080 
1081   if (FormatTok->isNot(tok::l_paren))
1082     return;
1083 
1084   // Parse formal parameter list.
1085   parseParens();
1086 
1087   if (FormatTok->is(tok::colon)) {
1088     // Parse a type definition.
1089     nextToken();
1090 
1091     // Eat the type declaration. For braced inline object types, balance braces,
1092     // otherwise just parse until finding an l_brace for the function body.
1093     if (FormatTok->is(tok::l_brace))
1094       tryToParseBracedList();
1095     else
1096       while (FormatTok->isNot(tok::l_brace) && !eof())
1097         nextToken();
1098   }
1099 
1100   parseChildBlock();
1101 }
1102 
1103 bool UnwrappedLineParser::tryToParseBracedList() {
1104   if (FormatTok->BlockKind == BK_Unknown)
1105     calculateBraceTypes();
1106   assert(FormatTok->BlockKind != BK_Unknown);
1107   if (FormatTok->BlockKind == BK_Block)
1108     return false;
1109   parseBracedList();
1110   return true;
1111 }
1112 
1113 bool UnwrappedLineParser::parseBracedList(bool ContinueOnSemicolons) {
1114   bool HasError = false;
1115   nextToken();
1116 
1117   // FIXME: Once we have an expression parser in the UnwrappedLineParser,
1118   // replace this by using parseAssigmentExpression() inside.
1119   do {
1120     if (Style.Language == FormatStyle::LK_JavaScript) {
1121       if (FormatTok->is(Keywords.kw_function)) {
1122         tryToParseJSFunction();
1123         continue;
1124       }
1125       if (FormatTok->is(TT_JsFatArrow)) {
1126         nextToken();
1127         // Fat arrows can be followed by simple expressions or by child blocks
1128         // in curly braces.
1129         if (FormatTok->is(tok::l_brace)) {
1130           parseChildBlock();
1131           continue;
1132         }
1133       }
1134     }
1135     switch (FormatTok->Tok.getKind()) {
1136     case tok::caret:
1137       nextToken();
1138       if (FormatTok->is(tok::l_brace)) {
1139         parseChildBlock();
1140       }
1141       break;
1142     case tok::l_square:
1143       tryToParseLambda();
1144       break;
1145     case tok::l_brace:
1146       // Assume there are no blocks inside a braced init list apart
1147       // from the ones we explicitly parse out (like lambdas).
1148       FormatTok->BlockKind = BK_BracedInit;
1149       parseBracedList();
1150       break;
1151     case tok::l_paren:
1152       parseParens();
1153       // JavaScript can just have free standing methods and getters/setters in
1154       // object literals. Detect them by a "{" following ")".
1155       if (Style.Language == FormatStyle::LK_JavaScript) {
1156         if (FormatTok->is(tok::l_brace))
1157           parseChildBlock();
1158         break;
1159       }
1160       break;
1161     case tok::r_brace:
1162       nextToken();
1163       return !HasError;
1164     case tok::semi:
1165       HasError = true;
1166       if (!ContinueOnSemicolons)
1167         return !HasError;
1168       nextToken();
1169       break;
1170     case tok::comma:
1171       nextToken();
1172       break;
1173     default:
1174       nextToken();
1175       break;
1176     }
1177   } while (!eof());
1178   return false;
1179 }
1180 
1181 void UnwrappedLineParser::parseParens() {
1182   assert(FormatTok->Tok.is(tok::l_paren) && "'(' expected.");
1183   nextToken();
1184   do {
1185     switch (FormatTok->Tok.getKind()) {
1186     case tok::l_paren:
1187       parseParens();
1188       if (Style.Language == FormatStyle::LK_Java && FormatTok->is(tok::l_brace))
1189         parseChildBlock();
1190       break;
1191     case tok::r_paren:
1192       nextToken();
1193       return;
1194     case tok::r_brace:
1195       // A "}" inside parenthesis is an error if there wasn't a matching "{".
1196       return;
1197     case tok::l_square:
1198       tryToParseLambda();
1199       break;
1200     case tok::l_brace:
1201       if (!tryToParseBracedList())
1202         parseChildBlock();
1203       break;
1204     case tok::at:
1205       nextToken();
1206       if (FormatTok->Tok.is(tok::l_brace))
1207         parseBracedList();
1208       break;
1209     case tok::identifier:
1210       if (Style.Language == FormatStyle::LK_JavaScript &&
1211           FormatTok->is(Keywords.kw_function))
1212         tryToParseJSFunction();
1213       else
1214         nextToken();
1215       break;
1216     default:
1217       nextToken();
1218       break;
1219     }
1220   } while (!eof());
1221 }
1222 
1223 void UnwrappedLineParser::parseSquare() {
1224   assert(FormatTok->Tok.is(tok::l_square) && "'[' expected.");
1225   if (tryToParseLambda())
1226     return;
1227   do {
1228     switch (FormatTok->Tok.getKind()) {
1229     case tok::l_paren:
1230       parseParens();
1231       break;
1232     case tok::r_square:
1233       nextToken();
1234       return;
1235     case tok::r_brace:
1236       // A "}" inside parenthesis is an error if there wasn't a matching "{".
1237       return;
1238     case tok::l_square:
1239       parseSquare();
1240       break;
1241     case tok::l_brace: {
1242       if (!tryToParseBracedList())
1243         parseChildBlock();
1244       break;
1245     }
1246     case tok::at:
1247       nextToken();
1248       if (FormatTok->Tok.is(tok::l_brace))
1249         parseBracedList();
1250       break;
1251     default:
1252       nextToken();
1253       break;
1254     }
1255   } while (!eof());
1256 }
1257 
1258 void UnwrappedLineParser::parseIfThenElse() {
1259   assert(FormatTok->Tok.is(tok::kw_if) && "'if' expected");
1260   nextToken();
1261   if (FormatTok->Tok.is(tok::l_paren))
1262     parseParens();
1263   bool NeedsUnwrappedLine = false;
1264   if (FormatTok->Tok.is(tok::l_brace)) {
1265     CompoundStatementIndenter Indenter(this, Style, Line->Level);
1266     parseBlock(/*MustBeDeclaration=*/false);
1267     if (Style.BraceWrapping.BeforeElse)
1268       addUnwrappedLine();
1269     else
1270       NeedsUnwrappedLine = true;
1271   } else {
1272     addUnwrappedLine();
1273     ++Line->Level;
1274     parseStructuralElement();
1275     --Line->Level;
1276   }
1277   if (FormatTok->Tok.is(tok::kw_else)) {
1278     nextToken();
1279     if (FormatTok->Tok.is(tok::l_brace)) {
1280       CompoundStatementIndenter Indenter(this, Style, Line->Level);
1281       parseBlock(/*MustBeDeclaration=*/false);
1282       addUnwrappedLine();
1283     } else if (FormatTok->Tok.is(tok::kw_if)) {
1284       parseIfThenElse();
1285     } else {
1286       addUnwrappedLine();
1287       ++Line->Level;
1288       parseStructuralElement();
1289       --Line->Level;
1290     }
1291   } else if (NeedsUnwrappedLine) {
1292     addUnwrappedLine();
1293   }
1294 }
1295 
1296 void UnwrappedLineParser::parseTryCatch() {
1297   assert(FormatTok->isOneOf(tok::kw_try, tok::kw___try) && "'try' expected");
1298   nextToken();
1299   bool NeedsUnwrappedLine = false;
1300   if (FormatTok->is(tok::colon)) {
1301     // We are in a function try block, what comes is an initializer list.
1302     nextToken();
1303     while (FormatTok->is(tok::identifier)) {
1304       nextToken();
1305       if (FormatTok->is(tok::l_paren))
1306         parseParens();
1307       if (FormatTok->is(tok::comma))
1308         nextToken();
1309     }
1310   }
1311   // Parse try with resource.
1312   if (Style.Language == FormatStyle::LK_Java && FormatTok->is(tok::l_paren)) {
1313     parseParens();
1314   }
1315   if (FormatTok->is(tok::l_brace)) {
1316     CompoundStatementIndenter Indenter(this, Style, Line->Level);
1317     parseBlock(/*MustBeDeclaration=*/false);
1318     if (Style.BraceWrapping.BeforeCatch) {
1319       addUnwrappedLine();
1320     } else {
1321       NeedsUnwrappedLine = true;
1322     }
1323   } else if (!FormatTok->is(tok::kw_catch)) {
1324     // The C++ standard requires a compound-statement after a try.
1325     // If there's none, we try to assume there's a structuralElement
1326     // and try to continue.
1327     addUnwrappedLine();
1328     ++Line->Level;
1329     parseStructuralElement();
1330     --Line->Level;
1331   }
1332   while (1) {
1333     if (FormatTok->is(tok::at))
1334       nextToken();
1335     if (!(FormatTok->isOneOf(tok::kw_catch, Keywords.kw___except,
1336                              tok::kw___finally) ||
1337           ((Style.Language == FormatStyle::LK_Java ||
1338             Style.Language == FormatStyle::LK_JavaScript) &&
1339            FormatTok->is(Keywords.kw_finally)) ||
1340           (FormatTok->Tok.isObjCAtKeyword(tok::objc_catch) ||
1341            FormatTok->Tok.isObjCAtKeyword(tok::objc_finally))))
1342       break;
1343     nextToken();
1344     while (FormatTok->isNot(tok::l_brace)) {
1345       if (FormatTok->is(tok::l_paren)) {
1346         parseParens();
1347         continue;
1348       }
1349       if (FormatTok->isOneOf(tok::semi, tok::r_brace, tok::eof))
1350         return;
1351       nextToken();
1352     }
1353     NeedsUnwrappedLine = false;
1354     CompoundStatementIndenter Indenter(this, Style, Line->Level);
1355     parseBlock(/*MustBeDeclaration=*/false);
1356     if (Style.BraceWrapping.BeforeCatch)
1357       addUnwrappedLine();
1358     else
1359       NeedsUnwrappedLine = true;
1360   }
1361   if (NeedsUnwrappedLine)
1362     addUnwrappedLine();
1363 }
1364 
1365 void UnwrappedLineParser::parseNamespace() {
1366   assert(FormatTok->Tok.is(tok::kw_namespace) && "'namespace' expected");
1367 
1368   const FormatToken &InitialToken = *FormatTok;
1369   nextToken();
1370   while (FormatTok->isOneOf(tok::identifier, tok::coloncolon))
1371     nextToken();
1372   if (FormatTok->Tok.is(tok::l_brace)) {
1373     if (ShouldBreakBeforeBrace(Style, InitialToken))
1374       addUnwrappedLine();
1375 
1376     bool AddLevel = Style.NamespaceIndentation == FormatStyle::NI_All ||
1377                     (Style.NamespaceIndentation == FormatStyle::NI_Inner &&
1378                      DeclarationScopeStack.size() > 1);
1379     parseBlock(/*MustBeDeclaration=*/true, AddLevel);
1380     // Munch the semicolon after a namespace. This is more common than one would
1381     // think. Puttin the semicolon into its own line is very ugly.
1382     if (FormatTok->Tok.is(tok::semi))
1383       nextToken();
1384     addUnwrappedLine();
1385   }
1386   // FIXME: Add error handling.
1387 }
1388 
1389 void UnwrappedLineParser::parseNew() {
1390   assert(FormatTok->is(tok::kw_new) && "'new' expected");
1391   nextToken();
1392   if (Style.Language != FormatStyle::LK_Java)
1393     return;
1394 
1395   // In Java, we can parse everything up to the parens, which aren't optional.
1396   do {
1397     // There should not be a ;, { or } before the new's open paren.
1398     if (FormatTok->isOneOf(tok::semi, tok::l_brace, tok::r_brace))
1399       return;
1400 
1401     // Consume the parens.
1402     if (FormatTok->is(tok::l_paren)) {
1403       parseParens();
1404 
1405       // If there is a class body of an anonymous class, consume that as child.
1406       if (FormatTok->is(tok::l_brace))
1407         parseChildBlock();
1408       return;
1409     }
1410     nextToken();
1411   } while (!eof());
1412 }
1413 
1414 void UnwrappedLineParser::parseForOrWhileLoop() {
1415   assert(FormatTok->isOneOf(tok::kw_for, tok::kw_while, TT_ForEachMacro) &&
1416          "'for', 'while' or foreach macro expected");
1417   nextToken();
1418   if (FormatTok->Tok.is(tok::l_paren))
1419     parseParens();
1420   if (FormatTok->Tok.is(tok::l_brace)) {
1421     CompoundStatementIndenter Indenter(this, Style, Line->Level);
1422     parseBlock(/*MustBeDeclaration=*/false);
1423     addUnwrappedLine();
1424   } else {
1425     addUnwrappedLine();
1426     ++Line->Level;
1427     parseStructuralElement();
1428     --Line->Level;
1429   }
1430 }
1431 
1432 void UnwrappedLineParser::parseDoWhile() {
1433   assert(FormatTok->Tok.is(tok::kw_do) && "'do' expected");
1434   nextToken();
1435   if (FormatTok->Tok.is(tok::l_brace)) {
1436     CompoundStatementIndenter Indenter(this, Style, Line->Level);
1437     parseBlock(/*MustBeDeclaration=*/false);
1438     if (Style.BraceWrapping.IndentBraces)
1439       addUnwrappedLine();
1440   } else {
1441     addUnwrappedLine();
1442     ++Line->Level;
1443     parseStructuralElement();
1444     --Line->Level;
1445   }
1446 
1447   // FIXME: Add error handling.
1448   if (!FormatTok->Tok.is(tok::kw_while)) {
1449     addUnwrappedLine();
1450     return;
1451   }
1452 
1453   nextToken();
1454   parseStructuralElement();
1455 }
1456 
1457 void UnwrappedLineParser::parseLabel() {
1458   nextToken();
1459   unsigned OldLineLevel = Line->Level;
1460   if (Line->Level > 1 || (!Line->InPPDirective && Line->Level > 0))
1461     --Line->Level;
1462   if (CommentsBeforeNextToken.empty() && FormatTok->Tok.is(tok::l_brace)) {
1463     CompoundStatementIndenter Indenter(this, Style, Line->Level);
1464     parseBlock(/*MustBeDeclaration=*/false);
1465     if (FormatTok->Tok.is(tok::kw_break)) {
1466       if (Style.BraceWrapping.AfterControlStatement)
1467         addUnwrappedLine();
1468       parseStructuralElement();
1469     }
1470     addUnwrappedLine();
1471   } else {
1472     if (FormatTok->is(tok::semi))
1473       nextToken();
1474     addUnwrappedLine();
1475   }
1476   Line->Level = OldLineLevel;
1477 }
1478 
1479 void UnwrappedLineParser::parseCaseLabel() {
1480   assert(FormatTok->Tok.is(tok::kw_case) && "'case' expected");
1481   // FIXME: fix handling of complex expressions here.
1482   do {
1483     nextToken();
1484   } while (!eof() && !FormatTok->Tok.is(tok::colon));
1485   parseLabel();
1486 }
1487 
1488 void UnwrappedLineParser::parseSwitch() {
1489   assert(FormatTok->Tok.is(tok::kw_switch) && "'switch' expected");
1490   nextToken();
1491   if (FormatTok->Tok.is(tok::l_paren))
1492     parseParens();
1493   if (FormatTok->Tok.is(tok::l_brace)) {
1494     CompoundStatementIndenter Indenter(this, Style, Line->Level);
1495     parseBlock(/*MustBeDeclaration=*/false);
1496     addUnwrappedLine();
1497   } else {
1498     addUnwrappedLine();
1499     ++Line->Level;
1500     parseStructuralElement();
1501     --Line->Level;
1502   }
1503 }
1504 
1505 void UnwrappedLineParser::parseAccessSpecifier() {
1506   nextToken();
1507   // Understand Qt's slots.
1508   if (FormatTok->isOneOf(Keywords.kw_slots, Keywords.kw_qslots))
1509     nextToken();
1510   // Otherwise, we don't know what it is, and we'd better keep the next token.
1511   if (FormatTok->Tok.is(tok::colon))
1512     nextToken();
1513   addUnwrappedLine();
1514 }
1515 
1516 void UnwrappedLineParser::parseEnum() {
1517   // Won't be 'enum' for NS_ENUMs.
1518   if (FormatTok->Tok.is(tok::kw_enum))
1519     nextToken();
1520 
1521   // Eat up enum class ...
1522   if (FormatTok->Tok.is(tok::kw_class) || FormatTok->Tok.is(tok::kw_struct))
1523     nextToken();
1524 
1525   while (FormatTok->Tok.getIdentifierInfo() ||
1526          FormatTok->isOneOf(tok::colon, tok::coloncolon, tok::less,
1527                             tok::greater, tok::comma, tok::question)) {
1528     nextToken();
1529     // We can have macros or attributes in between 'enum' and the enum name.
1530     if (FormatTok->is(tok::l_paren))
1531       parseParens();
1532     if (FormatTok->is(tok::identifier)) {
1533       nextToken();
1534       // If there are two identifiers in a row, this is likely an elaborate
1535       // return type. In Java, this can be "implements", etc.
1536       if (Style.Language == FormatStyle::LK_Cpp &&
1537           FormatTok->is(tok::identifier))
1538         return;
1539     }
1540   }
1541 
1542   // Just a declaration or something is wrong.
1543   if (FormatTok->isNot(tok::l_brace))
1544     return;
1545   FormatTok->BlockKind = BK_Block;
1546 
1547   if (Style.Language == FormatStyle::LK_Java) {
1548     // Java enums are different.
1549     parseJavaEnumBody();
1550     return;
1551   } else if (Style.Language == FormatStyle::LK_Proto) {
1552     parseBlock(/*MustBeDeclaration=*/true);
1553     return;
1554   }
1555 
1556   // Parse enum body.
1557   bool HasError = !parseBracedList(/*ContinueOnSemicolons=*/true);
1558   if (HasError) {
1559     if (FormatTok->is(tok::semi))
1560       nextToken();
1561     addUnwrappedLine();
1562   }
1563 
1564   // There is no addUnwrappedLine() here so that we fall through to parsing a
1565   // structural element afterwards. Thus, in "enum A {} n, m;",
1566   // "} n, m;" will end up in one unwrapped line.
1567 }
1568 
1569 void UnwrappedLineParser::parseJavaEnumBody() {
1570   // Determine whether the enum is simple, i.e. does not have a semicolon or
1571   // constants with class bodies. Simple enums can be formatted like braced
1572   // lists, contracted to a single line, etc.
1573   unsigned StoredPosition = Tokens->getPosition();
1574   bool IsSimple = true;
1575   FormatToken *Tok = Tokens->getNextToken();
1576   while (Tok) {
1577     if (Tok->is(tok::r_brace))
1578       break;
1579     if (Tok->isOneOf(tok::l_brace, tok::semi)) {
1580       IsSimple = false;
1581       break;
1582     }
1583     // FIXME: This will also mark enums with braces in the arguments to enum
1584     // constants as "not simple". This is probably fine in practice, though.
1585     Tok = Tokens->getNextToken();
1586   }
1587   FormatTok = Tokens->setPosition(StoredPosition);
1588 
1589   if (IsSimple) {
1590     parseBracedList();
1591     addUnwrappedLine();
1592     return;
1593   }
1594 
1595   // Parse the body of a more complex enum.
1596   // First add a line for everything up to the "{".
1597   nextToken();
1598   addUnwrappedLine();
1599   ++Line->Level;
1600 
1601   // Parse the enum constants.
1602   while (FormatTok) {
1603     if (FormatTok->is(tok::l_brace)) {
1604       // Parse the constant's class body.
1605       parseBlock(/*MustBeDeclaration=*/true, /*AddLevel=*/true,
1606                  /*MunchSemi=*/false);
1607     } else if (FormatTok->is(tok::l_paren)) {
1608       parseParens();
1609     } else if (FormatTok->is(tok::comma)) {
1610       nextToken();
1611       addUnwrappedLine();
1612     } else if (FormatTok->is(tok::semi)) {
1613       nextToken();
1614       addUnwrappedLine();
1615       break;
1616     } else if (FormatTok->is(tok::r_brace)) {
1617       addUnwrappedLine();
1618       break;
1619     } else {
1620       nextToken();
1621     }
1622   }
1623 
1624   // Parse the class body after the enum's ";" if any.
1625   parseLevel(/*HasOpeningBrace=*/true);
1626   nextToken();
1627   --Line->Level;
1628   addUnwrappedLine();
1629 }
1630 
1631 void UnwrappedLineParser::parseRecord() {
1632   const FormatToken &InitialToken = *FormatTok;
1633   nextToken();
1634 
1635   // The actual identifier can be a nested name specifier, and in macros
1636   // it is often token-pasted.
1637   while (FormatTok->isOneOf(tok::identifier, tok::coloncolon, tok::hashhash,
1638                             tok::kw___attribute, tok::kw___declspec,
1639                             tok::kw_alignas) ||
1640          ((Style.Language == FormatStyle::LK_Java ||
1641            Style.Language == FormatStyle::LK_JavaScript) &&
1642           FormatTok->isOneOf(tok::period, tok::comma))) {
1643     bool IsNonMacroIdentifier =
1644         FormatTok->is(tok::identifier) &&
1645         FormatTok->TokenText != FormatTok->TokenText.upper();
1646     nextToken();
1647     // We can have macros or attributes in between 'class' and the class name.
1648     if (!IsNonMacroIdentifier && FormatTok->Tok.is(tok::l_paren))
1649       parseParens();
1650   }
1651 
1652   // Note that parsing away template declarations here leads to incorrectly
1653   // accepting function declarations as record declarations.
1654   // In general, we cannot solve this problem. Consider:
1655   // class A<int> B() {}
1656   // which can be a function definition or a class definition when B() is a
1657   // macro. If we find enough real-world cases where this is a problem, we
1658   // can parse for the 'template' keyword in the beginning of the statement,
1659   // and thus rule out the record production in case there is no template
1660   // (this would still leave us with an ambiguity between template function
1661   // and class declarations).
1662   if (FormatTok->isOneOf(tok::colon, tok::less)) {
1663     while (!eof()) {
1664       if (FormatTok->is(tok::l_brace)) {
1665         calculateBraceTypes(/*ExpectClassBody=*/true);
1666         if (!tryToParseBracedList())
1667           break;
1668       }
1669       if (FormatTok->Tok.is(tok::semi))
1670         return;
1671       nextToken();
1672     }
1673   }
1674   if (FormatTok->Tok.is(tok::l_brace)) {
1675     if (ShouldBreakBeforeBrace(Style, InitialToken))
1676       addUnwrappedLine();
1677 
1678     parseBlock(/*MustBeDeclaration=*/true, /*AddLevel=*/true,
1679                /*MunchSemi=*/false);
1680   }
1681   // There is no addUnwrappedLine() here so that we fall through to parsing a
1682   // structural element afterwards. Thus, in "class A {} n, m;",
1683   // "} n, m;" will end up in one unwrapped line.
1684 }
1685 
1686 void UnwrappedLineParser::parseObjCProtocolList() {
1687   assert(FormatTok->Tok.is(tok::less) && "'<' expected.");
1688   do
1689     nextToken();
1690   while (!eof() && FormatTok->Tok.isNot(tok::greater));
1691   nextToken(); // Skip '>'.
1692 }
1693 
1694 void UnwrappedLineParser::parseObjCUntilAtEnd() {
1695   do {
1696     if (FormatTok->Tok.isObjCAtKeyword(tok::objc_end)) {
1697       nextToken();
1698       addUnwrappedLine();
1699       break;
1700     }
1701     if (FormatTok->is(tok::l_brace)) {
1702       parseBlock(/*MustBeDeclaration=*/false);
1703       // In ObjC interfaces, nothing should be following the "}".
1704       addUnwrappedLine();
1705     } else if (FormatTok->is(tok::r_brace)) {
1706       // Ignore stray "}". parseStructuralElement doesn't consume them.
1707       nextToken();
1708       addUnwrappedLine();
1709     } else {
1710       parseStructuralElement();
1711     }
1712   } while (!eof());
1713 }
1714 
1715 void UnwrappedLineParser::parseObjCInterfaceOrImplementation() {
1716   nextToken();
1717   nextToken(); // interface name
1718 
1719   // @interface can be followed by either a base class, or a category.
1720   if (FormatTok->Tok.is(tok::colon)) {
1721     nextToken();
1722     nextToken(); // base class name
1723   } else if (FormatTok->Tok.is(tok::l_paren))
1724     // Skip category, if present.
1725     parseParens();
1726 
1727   if (FormatTok->Tok.is(tok::less))
1728     parseObjCProtocolList();
1729 
1730   if (FormatTok->Tok.is(tok::l_brace)) {
1731     if (Style.BraceWrapping.AfterObjCDeclaration)
1732       addUnwrappedLine();
1733     parseBlock(/*MustBeDeclaration=*/true);
1734   }
1735 
1736   // With instance variables, this puts '}' on its own line.  Without instance
1737   // variables, this ends the @interface line.
1738   addUnwrappedLine();
1739 
1740   parseObjCUntilAtEnd();
1741 }
1742 
1743 void UnwrappedLineParser::parseObjCProtocol() {
1744   nextToken();
1745   nextToken(); // protocol name
1746 
1747   if (FormatTok->Tok.is(tok::less))
1748     parseObjCProtocolList();
1749 
1750   // Check for protocol declaration.
1751   if (FormatTok->Tok.is(tok::semi)) {
1752     nextToken();
1753     return addUnwrappedLine();
1754   }
1755 
1756   addUnwrappedLine();
1757   parseObjCUntilAtEnd();
1758 }
1759 
1760 void UnwrappedLineParser::parseJavaScriptEs6ImportExport() {
1761   assert(FormatTok->isOneOf(Keywords.kw_import, tok::kw_export));
1762   nextToken();
1763 
1764   // Consume the "default" in "export default class/function".
1765   if (FormatTok->is(tok::kw_default))
1766     nextToken();
1767 
1768   // Consume "function" and "default function", so that these get parsed as
1769   // free-standing JS functions, i.e. do not require a trailing semicolon.
1770   if (FormatTok->is(Keywords.kw_function)) {
1771     nextToken();
1772     return;
1773   }
1774 
1775   if (FormatTok->isOneOf(tok::kw_const, tok::kw_class, tok::kw_enum,
1776                          Keywords.kw_let, Keywords.kw_var))
1777     return; // Fall through to parsing the corresponding structure.
1778 
1779   if (FormatTok->is(tok::l_brace)) {
1780     FormatTok->BlockKind = BK_Block;
1781     parseBracedList();
1782   }
1783 
1784   while (!eof() && FormatTok->isNot(tok::semi) &&
1785          FormatTok->isNot(tok::l_brace)) {
1786     nextToken();
1787   }
1788 }
1789 
1790 LLVM_ATTRIBUTE_UNUSED static void printDebugInfo(const UnwrappedLine &Line,
1791                                                  StringRef Prefix = "") {
1792   llvm::dbgs() << Prefix << "Line(" << Line.Level << ")"
1793                << (Line.InPPDirective ? " MACRO" : "") << ": ";
1794   for (std::list<UnwrappedLineNode>::const_iterator I = Line.Tokens.begin(),
1795                                                     E = Line.Tokens.end();
1796        I != E; ++I) {
1797     llvm::dbgs() << I->Tok->Tok.getName() << "[" << I->Tok->Type << "] ";
1798   }
1799   for (std::list<UnwrappedLineNode>::const_iterator I = Line.Tokens.begin(),
1800                                                     E = Line.Tokens.end();
1801        I != E; ++I) {
1802     const UnwrappedLineNode &Node = *I;
1803     for (SmallVectorImpl<UnwrappedLine>::const_iterator
1804              I = Node.Children.begin(),
1805              E = Node.Children.end();
1806          I != E; ++I) {
1807       printDebugInfo(*I, "\nChild: ");
1808     }
1809   }
1810   llvm::dbgs() << "\n";
1811 }
1812 
1813 void UnwrappedLineParser::addUnwrappedLine() {
1814   if (Line->Tokens.empty())
1815     return;
1816   DEBUG({
1817     if (CurrentLines == &Lines)
1818       printDebugInfo(*Line);
1819   });
1820   CurrentLines->push_back(std::move(*Line));
1821   Line->Tokens.clear();
1822   if (CurrentLines == &Lines && !PreprocessorDirectives.empty()) {
1823     CurrentLines->append(
1824         std::make_move_iterator(PreprocessorDirectives.begin()),
1825         std::make_move_iterator(PreprocessorDirectives.end()));
1826     PreprocessorDirectives.clear();
1827   }
1828 }
1829 
1830 bool UnwrappedLineParser::eof() const { return FormatTok->Tok.is(tok::eof); }
1831 
1832 bool UnwrappedLineParser::isOnNewLine(const FormatToken &FormatTok) {
1833   return (Line->InPPDirective || FormatTok.HasUnescapedNewline) &&
1834          FormatTok.NewlinesBefore > 0;
1835 }
1836 
1837 void UnwrappedLineParser::flushComments(bool NewlineBeforeNext) {
1838   bool JustComments = Line->Tokens.empty();
1839   for (SmallVectorImpl<FormatToken *>::const_iterator
1840            I = CommentsBeforeNextToken.begin(),
1841            E = CommentsBeforeNextToken.end();
1842        I != E; ++I) {
1843     if (isOnNewLine(**I) && JustComments)
1844       addUnwrappedLine();
1845     pushToken(*I);
1846   }
1847   if (NewlineBeforeNext && JustComments)
1848     addUnwrappedLine();
1849   CommentsBeforeNextToken.clear();
1850 }
1851 
1852 void UnwrappedLineParser::nextToken() {
1853   if (eof())
1854     return;
1855   flushComments(isOnNewLine(*FormatTok));
1856   pushToken(FormatTok);
1857   readToken();
1858 }
1859 
1860 void UnwrappedLineParser::readToken() {
1861   bool CommentsInCurrentLine = true;
1862   do {
1863     FormatTok = Tokens->getNextToken();
1864     assert(FormatTok);
1865     while (!Line->InPPDirective && FormatTok->Tok.is(tok::hash) &&
1866            (FormatTok->HasUnescapedNewline || FormatTok->IsFirst)) {
1867       // If there is an unfinished unwrapped line, we flush the preprocessor
1868       // directives only after that unwrapped line was finished later.
1869       bool SwitchToPreprocessorLines = !Line->Tokens.empty();
1870       ScopedLineState BlockState(*this, SwitchToPreprocessorLines);
1871       // Comments stored before the preprocessor directive need to be output
1872       // before the preprocessor directive, at the same level as the
1873       // preprocessor directive, as we consider them to apply to the directive.
1874       flushComments(isOnNewLine(*FormatTok));
1875       parsePPDirective();
1876     }
1877     while (FormatTok->Type == TT_ConflictStart ||
1878            FormatTok->Type == TT_ConflictEnd ||
1879            FormatTok->Type == TT_ConflictAlternative) {
1880       if (FormatTok->Type == TT_ConflictStart) {
1881         conditionalCompilationStart(/*Unreachable=*/false);
1882       } else if (FormatTok->Type == TT_ConflictAlternative) {
1883         conditionalCompilationAlternative();
1884       } else if (FormatTok->Type == TT_ConflictEnd) {
1885         conditionalCompilationEnd();
1886       }
1887       FormatTok = Tokens->getNextToken();
1888       FormatTok->MustBreakBefore = true;
1889     }
1890 
1891     if (!PPStack.empty() && (PPStack.back() == PP_Unreachable) &&
1892         !Line->InPPDirective) {
1893       continue;
1894     }
1895 
1896     if (!FormatTok->Tok.is(tok::comment))
1897       return;
1898     if (isOnNewLine(*FormatTok) || FormatTok->IsFirst) {
1899       CommentsInCurrentLine = false;
1900     }
1901     if (CommentsInCurrentLine) {
1902       pushToken(FormatTok);
1903     } else {
1904       CommentsBeforeNextToken.push_back(FormatTok);
1905     }
1906   } while (!eof());
1907 }
1908 
1909 void UnwrappedLineParser::pushToken(FormatToken *Tok) {
1910   Line->Tokens.push_back(UnwrappedLineNode(Tok));
1911   if (MustBreakBeforeNextToken) {
1912     Line->Tokens.back().Tok->MustBreakBefore = true;
1913     MustBreakBeforeNextToken = false;
1914   }
1915 }
1916 
1917 } // end namespace format
1918 } // end namespace clang
1919