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 static bool isLineComment(const FormatToken &FormatTok) {
59   return FormatTok.is(tok::comment) &&
60          FormatTok.TokenText.startswith("//");
61 }
62 
63 // Checks if \p FormatTok is a line comment that continues the line comment
64 // \p Previous. The original column of \p MinColumnToken is used to determine
65 // whether \p FormatTok is indented enough to the right to continue \p Previous.
66 static bool continuesLineComment(const FormatToken &FormatTok,
67                                  const FormatToken *Previous,
68                                  const FormatToken *MinColumnToken) {
69   if (!Previous || !MinColumnToken)
70     return false;
71   unsigned MinContinueColumn =
72       MinColumnToken->OriginalColumn + (isLineComment(*MinColumnToken) ? 0 : 1);
73   return isLineComment(FormatTok) && FormatTok.NewlinesBefore == 1 &&
74          isLineComment(*Previous) &&
75          FormatTok.OriginalColumn >= MinContinueColumn;
76 }
77 
78 class ScopedMacroState : public FormatTokenSource {
79 public:
80   ScopedMacroState(UnwrappedLine &Line, FormatTokenSource *&TokenSource,
81                    FormatToken *&ResetToken)
82       : Line(Line), TokenSource(TokenSource), ResetToken(ResetToken),
83         PreviousLineLevel(Line.Level), PreviousTokenSource(TokenSource),
84         Token(nullptr), PreviousToken(nullptr) {
85     TokenSource = this;
86     Line.Level = 0;
87     Line.InPPDirective = true;
88   }
89 
90   ~ScopedMacroState() override {
91     TokenSource = PreviousTokenSource;
92     ResetToken = Token;
93     Line.InPPDirective = false;
94     Line.Level = PreviousLineLevel;
95   }
96 
97   FormatToken *getNextToken() override {
98     // The \c UnwrappedLineParser guards against this by never calling
99     // \c getNextToken() after it has encountered the first eof token.
100     assert(!eof());
101     PreviousToken = Token;
102     Token = PreviousTokenSource->getNextToken();
103     if (eof())
104       return getFakeEOF();
105     return Token;
106   }
107 
108   unsigned getPosition() override { return PreviousTokenSource->getPosition(); }
109 
110   FormatToken *setPosition(unsigned Position) override {
111     PreviousToken = nullptr;
112     Token = PreviousTokenSource->setPosition(Position);
113     return Token;
114   }
115 
116 private:
117   bool eof() {
118     return Token && Token->HasUnescapedNewline &&
119            !continuesLineComment(*Token, PreviousToken,
120                                  /*MinColumnToken=*/PreviousToken);
121   }
122 
123   FormatToken *getFakeEOF() {
124     static bool EOFInitialized = false;
125     static FormatToken FormatTok;
126     if (!EOFInitialized) {
127       FormatTok.Tok.startToken();
128       FormatTok.Tok.setKind(tok::eof);
129       EOFInitialized = true;
130     }
131     return &FormatTok;
132   }
133 
134   UnwrappedLine &Line;
135   FormatTokenSource *&TokenSource;
136   FormatToken *&ResetToken;
137   unsigned PreviousLineLevel;
138   FormatTokenSource *PreviousTokenSource;
139 
140   FormatToken *Token;
141   FormatToken *PreviousToken;
142 };
143 
144 } // end anonymous namespace
145 
146 class ScopedLineState {
147 public:
148   ScopedLineState(UnwrappedLineParser &Parser,
149                   bool SwitchToPreprocessorLines = false)
150       : Parser(Parser), OriginalLines(Parser.CurrentLines) {
151     if (SwitchToPreprocessorLines)
152       Parser.CurrentLines = &Parser.PreprocessorDirectives;
153     else if (!Parser.Line->Tokens.empty())
154       Parser.CurrentLines = &Parser.Line->Tokens.back().Children;
155     PreBlockLine = std::move(Parser.Line);
156     Parser.Line = llvm::make_unique<UnwrappedLine>();
157     Parser.Line->Level = PreBlockLine->Level;
158     Parser.Line->InPPDirective = PreBlockLine->InPPDirective;
159   }
160 
161   ~ScopedLineState() {
162     if (!Parser.Line->Tokens.empty()) {
163       Parser.addUnwrappedLine();
164     }
165     assert(Parser.Line->Tokens.empty());
166     Parser.Line = std::move(PreBlockLine);
167     if (Parser.CurrentLines == &Parser.PreprocessorDirectives)
168       Parser.MustBreakBeforeNextToken = true;
169     Parser.CurrentLines = OriginalLines;
170   }
171 
172 private:
173   UnwrappedLineParser &Parser;
174 
175   std::unique_ptr<UnwrappedLine> PreBlockLine;
176   SmallVectorImpl<UnwrappedLine> *OriginalLines;
177 };
178 
179 class CompoundStatementIndenter {
180 public:
181   CompoundStatementIndenter(UnwrappedLineParser *Parser,
182                             const FormatStyle &Style, unsigned &LineLevel)
183       : LineLevel(LineLevel), OldLineLevel(LineLevel) {
184     if (Style.BraceWrapping.AfterControlStatement)
185       Parser->addUnwrappedLine();
186     if (Style.BraceWrapping.IndentBraces)
187       ++LineLevel;
188   }
189   ~CompoundStatementIndenter() { LineLevel = OldLineLevel; }
190 
191 private:
192   unsigned &LineLevel;
193   unsigned OldLineLevel;
194 };
195 
196 namespace {
197 
198 class IndexedTokenSource : public FormatTokenSource {
199 public:
200   IndexedTokenSource(ArrayRef<FormatToken *> Tokens)
201       : Tokens(Tokens), Position(-1) {}
202 
203   FormatToken *getNextToken() override {
204     ++Position;
205     return Tokens[Position];
206   }
207 
208   unsigned getPosition() override {
209     assert(Position >= 0);
210     return Position;
211   }
212 
213   FormatToken *setPosition(unsigned P) override {
214     Position = P;
215     return Tokens[Position];
216   }
217 
218   void reset() { Position = -1; }
219 
220 private:
221   ArrayRef<FormatToken *> Tokens;
222   int Position;
223 };
224 
225 } // end anonymous namespace
226 
227 UnwrappedLineParser::UnwrappedLineParser(const FormatStyle &Style,
228                                          const AdditionalKeywords &Keywords,
229                                          ArrayRef<FormatToken *> Tokens,
230                                          UnwrappedLineConsumer &Callback)
231     : Line(new UnwrappedLine), MustBreakBeforeNextToken(false),
232       CurrentLines(&Lines), Style(Style), Keywords(Keywords),
233       CommentPragmasRegex(Style.CommentPragmas), Tokens(nullptr),
234       Callback(Callback), AllTokens(Tokens), PPBranchLevel(-1) {}
235 
236 void UnwrappedLineParser::reset() {
237   PPBranchLevel = -1;
238   Line.reset(new UnwrappedLine);
239   CommentsBeforeNextToken.clear();
240   FormatTok = nullptr;
241   MustBreakBeforeNextToken = false;
242   PreprocessorDirectives.clear();
243   CurrentLines = &Lines;
244   DeclarationScopeStack.clear();
245   PPStack.clear();
246 }
247 
248 void UnwrappedLineParser::parse() {
249   IndexedTokenSource TokenSource(AllTokens);
250   do {
251     DEBUG(llvm::dbgs() << "----\n");
252     reset();
253     Tokens = &TokenSource;
254     TokenSource.reset();
255 
256     readToken();
257     parseFile();
258     // Create line with eof token.
259     pushToken(FormatTok);
260     addUnwrappedLine();
261 
262     for (SmallVectorImpl<UnwrappedLine>::iterator I = Lines.begin(),
263                                                   E = Lines.end();
264          I != E; ++I) {
265       Callback.consumeUnwrappedLine(*I);
266     }
267     Callback.finishRun();
268     Lines.clear();
269     while (!PPLevelBranchIndex.empty() &&
270            PPLevelBranchIndex.back() + 1 >= PPLevelBranchCount.back()) {
271       PPLevelBranchIndex.resize(PPLevelBranchIndex.size() - 1);
272       PPLevelBranchCount.resize(PPLevelBranchCount.size() - 1);
273     }
274     if (!PPLevelBranchIndex.empty()) {
275       ++PPLevelBranchIndex.back();
276       assert(PPLevelBranchIndex.size() == PPLevelBranchCount.size());
277       assert(PPLevelBranchIndex.back() <= PPLevelBranchCount.back());
278     }
279   } while (!PPLevelBranchIndex.empty());
280 }
281 
282 void UnwrappedLineParser::parseFile() {
283   // The top-level context in a file always has declarations, except for pre-
284   // processor directives and JavaScript files.
285   bool MustBeDeclaration =
286       !Line->InPPDirective && Style.Language != FormatStyle::LK_JavaScript;
287   ScopedDeclarationState DeclarationState(*Line, DeclarationScopeStack,
288                                           MustBeDeclaration);
289   parseLevel(/*HasOpeningBrace=*/false);
290   // Make sure to format the remaining tokens.
291   flushComments(true);
292   addUnwrappedLine();
293 }
294 
295 void UnwrappedLineParser::parseLevel(bool HasOpeningBrace) {
296   bool SwitchLabelEncountered = false;
297   do {
298     tok::TokenKind kind = FormatTok->Tok.getKind();
299     if (FormatTok->Type == TT_MacroBlockBegin) {
300       kind = tok::l_brace;
301     } else if (FormatTok->Type == TT_MacroBlockEnd) {
302       kind = tok::r_brace;
303     }
304 
305     switch (kind) {
306     case tok::comment:
307       nextToken();
308       addUnwrappedLine();
309       break;
310     case tok::l_brace:
311       // FIXME: Add parameter whether this can happen - if this happens, we must
312       // be in a non-declaration context.
313       if (!FormatTok->is(TT_MacroBlockBegin) && tryToParseBracedList())
314         continue;
315       parseBlock(/*MustBeDeclaration=*/false);
316       addUnwrappedLine();
317       break;
318     case tok::r_brace:
319       if (HasOpeningBrace)
320         return;
321       nextToken();
322       addUnwrappedLine();
323       break;
324     case tok::kw_default:
325     case tok::kw_case:
326       if (!SwitchLabelEncountered &&
327           (Style.IndentCaseLabels || (Line->InPPDirective && Line->Level == 1)))
328         ++Line->Level;
329       SwitchLabelEncountered = true;
330       parseStructuralElement();
331       break;
332     default:
333       parseStructuralElement();
334       break;
335     }
336   } while (!eof());
337 }
338 
339 void UnwrappedLineParser::calculateBraceTypes(bool ExpectClassBody) {
340   // We'll parse forward through the tokens until we hit
341   // a closing brace or eof - note that getNextToken() will
342   // parse macros, so this will magically work inside macro
343   // definitions, too.
344   unsigned StoredPosition = Tokens->getPosition();
345   FormatToken *Tok = FormatTok;
346   const FormatToken *PrevTok = getPreviousToken();
347   // Keep a stack of positions of lbrace tokens. We will
348   // update information about whether an lbrace starts a
349   // braced init list or a different block during the loop.
350   SmallVector<FormatToken *, 8> LBraceStack;
351   assert(Tok->Tok.is(tok::l_brace));
352   do {
353     // Get next non-comment token.
354     FormatToken *NextTok;
355     unsigned ReadTokens = 0;
356     do {
357       NextTok = Tokens->getNextToken();
358       ++ReadTokens;
359     } while (NextTok->is(tok::comment));
360 
361     switch (Tok->Tok.getKind()) {
362     case tok::l_brace:
363       if (Style.Language == FormatStyle::LK_JavaScript && PrevTok) {
364         if (PrevTok->is(tok::colon))
365           // A colon indicates this code is in a type, or a braced list
366           // following a label in an object literal ({a: {b: 1}}). The code
367           // below could be confused by semicolons between the individual
368           // members in a type member list, which would normally trigger
369           // BK_Block. In both cases, this must be parsed as an inline braced
370           // init.
371           Tok->BlockKind = BK_BracedInit;
372         else if (PrevTok->is(tok::r_paren))
373           // `) { }` can only occur in function or method declarations in JS.
374           Tok->BlockKind = BK_Block;
375       } else {
376         Tok->BlockKind = BK_Unknown;
377       }
378       LBraceStack.push_back(Tok);
379       break;
380     case tok::r_brace:
381       if (LBraceStack.empty())
382         break;
383       if (LBraceStack.back()->BlockKind == BK_Unknown) {
384         bool ProbablyBracedList = false;
385         if (Style.Language == FormatStyle::LK_Proto) {
386           ProbablyBracedList = NextTok->isOneOf(tok::comma, tok::r_square);
387         } else {
388           // Using OriginalColumn to distinguish between ObjC methods and
389           // binary operators is a bit hacky.
390           bool NextIsObjCMethod = NextTok->isOneOf(tok::plus, tok::minus) &&
391                                   NextTok->OriginalColumn == 0;
392 
393           // If there is a comma, semicolon or right paren after the closing
394           // brace, we assume this is a braced initializer list.  Note that
395           // regardless how we mark inner braces here, we will overwrite the
396           // BlockKind later if we parse a braced list (where all blocks
397           // inside are by default braced lists), or when we explicitly detect
398           // blocks (for example while parsing lambdas).
399           // FIXME: Some of these do not apply to JS, e.g. "} {" can never be a
400           // braced list in JS.
401           ProbablyBracedList =
402               (Style.Language == FormatStyle::LK_JavaScript &&
403                NextTok->isOneOf(Keywords.kw_of, Keywords.kw_in,
404                                 Keywords.kw_as)) ||
405               (Style.isCpp() && NextTok->is(tok::l_paren)) ||
406               NextTok->isOneOf(tok::comma, tok::period, tok::colon,
407                                tok::r_paren, tok::r_square, tok::l_brace,
408                                tok::l_square, tok::ellipsis) ||
409               (NextTok->is(tok::identifier) &&
410                !PrevTok->isOneOf(tok::semi, tok::r_brace, tok::l_brace)) ||
411               (NextTok->is(tok::semi) &&
412                (!ExpectClassBody || LBraceStack.size() != 1)) ||
413               (NextTok->isBinaryOperator() && !NextIsObjCMethod);
414         }
415         if (ProbablyBracedList) {
416           Tok->BlockKind = BK_BracedInit;
417           LBraceStack.back()->BlockKind = BK_BracedInit;
418         } else {
419           Tok->BlockKind = BK_Block;
420           LBraceStack.back()->BlockKind = BK_Block;
421         }
422       }
423       LBraceStack.pop_back();
424       break;
425     case tok::at:
426     case tok::semi:
427     case tok::kw_if:
428     case tok::kw_while:
429     case tok::kw_for:
430     case tok::kw_switch:
431     case tok::kw_try:
432     case tok::kw___try:
433       if (!LBraceStack.empty() && LBraceStack.back()->BlockKind == BK_Unknown)
434         LBraceStack.back()->BlockKind = BK_Block;
435       break;
436     default:
437       break;
438     }
439     PrevTok = Tok;
440     Tok = NextTok;
441   } while (Tok->Tok.isNot(tok::eof) && !LBraceStack.empty());
442 
443   // Assume other blocks for all unclosed opening braces.
444   for (unsigned i = 0, e = LBraceStack.size(); i != e; ++i) {
445     if (LBraceStack[i]->BlockKind == BK_Unknown)
446       LBraceStack[i]->BlockKind = BK_Block;
447   }
448 
449   FormatTok = Tokens->setPosition(StoredPosition);
450 }
451 
452 void UnwrappedLineParser::parseBlock(bool MustBeDeclaration, bool AddLevel,
453                                      bool MunchSemi) {
454   assert(FormatTok->isOneOf(tok::l_brace, TT_MacroBlockBegin) &&
455          "'{' or macro block token expected");
456   const bool MacroBlock = FormatTok->is(TT_MacroBlockBegin);
457   FormatTok->BlockKind = BK_Block;
458 
459   unsigned InitialLevel = Line->Level;
460   nextToken();
461 
462   if (MacroBlock && FormatTok->is(tok::l_paren))
463     parseParens();
464 
465   addUnwrappedLine();
466   size_t OpeningLineIndex = CurrentLines->empty()
467                                 ? (UnwrappedLine::kInvalidIndex)
468                                 : (CurrentLines->size() - 1);
469 
470   ScopedDeclarationState DeclarationState(*Line, DeclarationScopeStack,
471                                           MustBeDeclaration);
472   if (AddLevel)
473     ++Line->Level;
474   parseLevel(/*HasOpeningBrace=*/true);
475 
476   if (eof())
477     return;
478 
479   if (MacroBlock ? !FormatTok->is(TT_MacroBlockEnd)
480                  : !FormatTok->is(tok::r_brace)) {
481     Line->Level = InitialLevel;
482     FormatTok->BlockKind = BK_Block;
483     return;
484   }
485 
486   nextToken(); // Munch the closing brace.
487 
488   if (MacroBlock && FormatTok->is(tok::l_paren))
489     parseParens();
490 
491   if (MunchSemi && FormatTok->Tok.is(tok::semi))
492     nextToken();
493   Line->Level = InitialLevel;
494   Line->MatchingOpeningBlockLineIndex = OpeningLineIndex;
495   if (OpeningLineIndex != UnwrappedLine::kInvalidIndex) {
496     // Update the opening line to add the forward reference as well
497     (*CurrentLines)[OpeningLineIndex].MatchingOpeningBlockLineIndex =
498             CurrentLines->size() - 1;
499   }
500 }
501 
502 static bool isGoogScope(const UnwrappedLine &Line) {
503   // FIXME: Closure-library specific stuff should not be hard-coded but be
504   // configurable.
505   if (Line.Tokens.size() < 4)
506     return false;
507   auto I = Line.Tokens.begin();
508   if (I->Tok->TokenText != "goog")
509     return false;
510   ++I;
511   if (I->Tok->isNot(tok::period))
512     return false;
513   ++I;
514   if (I->Tok->TokenText != "scope")
515     return false;
516   ++I;
517   return I->Tok->is(tok::l_paren);
518 }
519 
520 static bool isIIFE(const UnwrappedLine &Line,
521                    const AdditionalKeywords &Keywords) {
522   // Look for the start of an immediately invoked anonymous function.
523   // https://en.wikipedia.org/wiki/Immediately-invoked_function_expression
524   // This is commonly done in JavaScript to create a new, anonymous scope.
525   // Example: (function() { ... })()
526   if (Line.Tokens.size() < 3)
527     return false;
528   auto I = Line.Tokens.begin();
529   if (I->Tok->isNot(tok::l_paren))
530     return false;
531   ++I;
532   if (I->Tok->isNot(Keywords.kw_function))
533     return false;
534   ++I;
535   return I->Tok->is(tok::l_paren);
536 }
537 
538 static bool ShouldBreakBeforeBrace(const FormatStyle &Style,
539                                    const FormatToken &InitialToken) {
540   if (InitialToken.is(tok::kw_namespace))
541     return Style.BraceWrapping.AfterNamespace;
542   if (InitialToken.is(tok::kw_class))
543     return Style.BraceWrapping.AfterClass;
544   if (InitialToken.is(tok::kw_union))
545     return Style.BraceWrapping.AfterUnion;
546   if (InitialToken.is(tok::kw_struct))
547     return Style.BraceWrapping.AfterStruct;
548   return false;
549 }
550 
551 void UnwrappedLineParser::parseChildBlock() {
552   FormatTok->BlockKind = BK_Block;
553   nextToken();
554   {
555     bool SkipIndent =
556         (Style.Language == FormatStyle::LK_JavaScript &&
557          (isGoogScope(*Line) || isIIFE(*Line, Keywords)));
558     ScopedLineState LineState(*this);
559     ScopedDeclarationState DeclarationState(*Line, DeclarationScopeStack,
560                                             /*MustBeDeclaration=*/false);
561     Line->Level += SkipIndent ? 0 : 1;
562     parseLevel(/*HasOpeningBrace=*/true);
563     flushComments(isOnNewLine(*FormatTok));
564     Line->Level -= SkipIndent ? 0 : 1;
565   }
566   nextToken();
567 }
568 
569 void UnwrappedLineParser::parsePPDirective() {
570   assert(FormatTok->Tok.is(tok::hash) && "'#' expected");
571   ScopedMacroState MacroState(*Line, Tokens, FormatTok);
572   nextToken();
573 
574   if (!FormatTok->Tok.getIdentifierInfo()) {
575     parsePPUnknown();
576     return;
577   }
578 
579   switch (FormatTok->Tok.getIdentifierInfo()->getPPKeywordID()) {
580   case tok::pp_define:
581     parsePPDefine();
582     return;
583   case tok::pp_if:
584     parsePPIf(/*IfDef=*/false);
585     break;
586   case tok::pp_ifdef:
587   case tok::pp_ifndef:
588     parsePPIf(/*IfDef=*/true);
589     break;
590   case tok::pp_else:
591     parsePPElse();
592     break;
593   case tok::pp_elif:
594     parsePPElIf();
595     break;
596   case tok::pp_endif:
597     parsePPEndIf();
598     break;
599   default:
600     parsePPUnknown();
601     break;
602   }
603 }
604 
605 void UnwrappedLineParser::conditionalCompilationCondition(bool Unreachable) {
606   if (Unreachable || (!PPStack.empty() && PPStack.back() == PP_Unreachable))
607     PPStack.push_back(PP_Unreachable);
608   else
609     PPStack.push_back(PP_Conditional);
610 }
611 
612 void UnwrappedLineParser::conditionalCompilationStart(bool Unreachable) {
613   ++PPBranchLevel;
614   assert(PPBranchLevel >= 0 && PPBranchLevel <= (int)PPLevelBranchIndex.size());
615   if (PPBranchLevel == (int)PPLevelBranchIndex.size()) {
616     PPLevelBranchIndex.push_back(0);
617     PPLevelBranchCount.push_back(0);
618   }
619   PPChainBranchIndex.push(0);
620   bool Skip = PPLevelBranchIndex[PPBranchLevel] > 0;
621   conditionalCompilationCondition(Unreachable || Skip);
622 }
623 
624 void UnwrappedLineParser::conditionalCompilationAlternative() {
625   if (!PPStack.empty())
626     PPStack.pop_back();
627   assert(PPBranchLevel < (int)PPLevelBranchIndex.size());
628   if (!PPChainBranchIndex.empty())
629     ++PPChainBranchIndex.top();
630   conditionalCompilationCondition(
631       PPBranchLevel >= 0 && !PPChainBranchIndex.empty() &&
632       PPLevelBranchIndex[PPBranchLevel] != PPChainBranchIndex.top());
633 }
634 
635 void UnwrappedLineParser::conditionalCompilationEnd() {
636   assert(PPBranchLevel < (int)PPLevelBranchIndex.size());
637   if (PPBranchLevel >= 0 && !PPChainBranchIndex.empty()) {
638     if (PPChainBranchIndex.top() + 1 > PPLevelBranchCount[PPBranchLevel]) {
639       PPLevelBranchCount[PPBranchLevel] = PPChainBranchIndex.top() + 1;
640     }
641   }
642   // Guard against #endif's without #if.
643   if (PPBranchLevel > 0)
644     --PPBranchLevel;
645   if (!PPChainBranchIndex.empty())
646     PPChainBranchIndex.pop();
647   if (!PPStack.empty())
648     PPStack.pop_back();
649 }
650 
651 void UnwrappedLineParser::parsePPIf(bool IfDef) {
652   bool IfNDef = FormatTok->is(tok::pp_ifndef);
653   nextToken();
654   bool Unreachable = false;
655   if (!IfDef && (FormatTok->is(tok::kw_false) || FormatTok->TokenText == "0"))
656     Unreachable = true;
657   if (IfDef && !IfNDef && FormatTok->TokenText == "SWIG")
658     Unreachable = true;
659   conditionalCompilationStart(Unreachable);
660   parsePPUnknown();
661 }
662 
663 void UnwrappedLineParser::parsePPElse() {
664   conditionalCompilationAlternative();
665   parsePPUnknown();
666 }
667 
668 void UnwrappedLineParser::parsePPElIf() { parsePPElse(); }
669 
670 void UnwrappedLineParser::parsePPEndIf() {
671   conditionalCompilationEnd();
672   parsePPUnknown();
673 }
674 
675 void UnwrappedLineParser::parsePPDefine() {
676   nextToken();
677 
678   if (FormatTok->Tok.getKind() != tok::identifier) {
679     parsePPUnknown();
680     return;
681   }
682   nextToken();
683   if (FormatTok->Tok.getKind() == tok::l_paren &&
684       FormatTok->WhitespaceRange.getBegin() ==
685           FormatTok->WhitespaceRange.getEnd()) {
686     parseParens();
687   }
688   addUnwrappedLine();
689   Line->Level = 1;
690 
691   // Errors during a preprocessor directive can only affect the layout of the
692   // preprocessor directive, and thus we ignore them. An alternative approach
693   // would be to use the same approach we use on the file level (no
694   // re-indentation if there was a structural error) within the macro
695   // definition.
696   parseFile();
697 }
698 
699 void UnwrappedLineParser::parsePPUnknown() {
700   do {
701     nextToken();
702   } while (!eof());
703   addUnwrappedLine();
704 }
705 
706 // Here we blacklist certain tokens that are not usually the first token in an
707 // unwrapped line. This is used in attempt to distinguish macro calls without
708 // trailing semicolons from other constructs split to several lines.
709 static bool tokenCanStartNewLine(const clang::Token &Tok) {
710   // Semicolon can be a null-statement, l_square can be a start of a macro or
711   // a C++11 attribute, but this doesn't seem to be common.
712   return Tok.isNot(tok::semi) && Tok.isNot(tok::l_brace) &&
713          Tok.isNot(tok::l_square) &&
714          // Tokens that can only be used as binary operators and a part of
715          // overloaded operator names.
716          Tok.isNot(tok::period) && Tok.isNot(tok::periodstar) &&
717          Tok.isNot(tok::arrow) && Tok.isNot(tok::arrowstar) &&
718          Tok.isNot(tok::less) && Tok.isNot(tok::greater) &&
719          Tok.isNot(tok::slash) && Tok.isNot(tok::percent) &&
720          Tok.isNot(tok::lessless) && Tok.isNot(tok::greatergreater) &&
721          Tok.isNot(tok::equal) && Tok.isNot(tok::plusequal) &&
722          Tok.isNot(tok::minusequal) && Tok.isNot(tok::starequal) &&
723          Tok.isNot(tok::slashequal) && Tok.isNot(tok::percentequal) &&
724          Tok.isNot(tok::ampequal) && Tok.isNot(tok::pipeequal) &&
725          Tok.isNot(tok::caretequal) && Tok.isNot(tok::greatergreaterequal) &&
726          Tok.isNot(tok::lesslessequal) &&
727          // Colon is used in labels, base class lists, initializer lists,
728          // range-based for loops, ternary operator, but should never be the
729          // first token in an unwrapped line.
730          Tok.isNot(tok::colon) &&
731          // 'noexcept' is a trailing annotation.
732          Tok.isNot(tok::kw_noexcept);
733 }
734 
735 static bool mustBeJSIdent(const AdditionalKeywords &Keywords,
736                           const FormatToken *FormatTok) {
737   // FIXME: This returns true for C/C++ keywords like 'struct'.
738   return FormatTok->is(tok::identifier) &&
739          (FormatTok->Tok.getIdentifierInfo() == nullptr ||
740           !FormatTok->isOneOf(
741               Keywords.kw_in, Keywords.kw_of, Keywords.kw_as, Keywords.kw_async,
742               Keywords.kw_await, Keywords.kw_yield, Keywords.kw_finally,
743               Keywords.kw_function, Keywords.kw_import, Keywords.kw_is,
744               Keywords.kw_let, Keywords.kw_var, tok::kw_const,
745               Keywords.kw_abstract, Keywords.kw_extends, Keywords.kw_implements,
746               Keywords.kw_instanceof, Keywords.kw_interface,
747               Keywords.kw_throws));
748 }
749 
750 static bool mustBeJSIdentOrValue(const AdditionalKeywords &Keywords,
751                                  const FormatToken *FormatTok) {
752   return FormatTok->Tok.isLiteral() ||
753          FormatTok->isOneOf(tok::kw_true, tok::kw_false) ||
754          mustBeJSIdent(Keywords, FormatTok);
755 }
756 
757 // isJSDeclOrStmt returns true if |FormatTok| starts a declaration or statement
758 // when encountered after a value (see mustBeJSIdentOrValue).
759 static bool isJSDeclOrStmt(const AdditionalKeywords &Keywords,
760                            const FormatToken *FormatTok) {
761   return FormatTok->isOneOf(
762       tok::kw_return, Keywords.kw_yield,
763       // conditionals
764       tok::kw_if, tok::kw_else,
765       // loops
766       tok::kw_for, tok::kw_while, tok::kw_do, tok::kw_continue, tok::kw_break,
767       // switch/case
768       tok::kw_switch, tok::kw_case,
769       // exceptions
770       tok::kw_throw, tok::kw_try, tok::kw_catch, Keywords.kw_finally,
771       // declaration
772       tok::kw_const, tok::kw_class, Keywords.kw_var, Keywords.kw_let,
773       Keywords.kw_async, Keywords.kw_function,
774       // import/export
775       Keywords.kw_import, tok::kw_export);
776 }
777 
778 // readTokenWithJavaScriptASI reads the next token and terminates the current
779 // line if JavaScript Automatic Semicolon Insertion must
780 // happen between the current token and the next token.
781 //
782 // This method is conservative - it cannot cover all edge cases of JavaScript,
783 // but only aims to correctly handle certain well known cases. It *must not*
784 // return true in speculative cases.
785 void UnwrappedLineParser::readTokenWithJavaScriptASI() {
786   FormatToken *Previous = FormatTok;
787   readToken();
788   FormatToken *Next = FormatTok;
789 
790   bool IsOnSameLine =
791       CommentsBeforeNextToken.empty()
792           ? Next->NewlinesBefore == 0
793           : CommentsBeforeNextToken.front()->NewlinesBefore == 0;
794   if (IsOnSameLine)
795     return;
796 
797   bool PreviousMustBeValue = mustBeJSIdentOrValue(Keywords, Previous);
798   bool PreviousStartsTemplateExpr =
799       Previous->is(TT_TemplateString) && Previous->TokenText.endswith("${");
800   if (PreviousMustBeValue && Line && Line->Tokens.size() > 1) {
801     // If the token before the previous one is an '@', the previous token is an
802     // annotation and can precede another identifier/value.
803     const FormatToken *PrePrevious = std::prev(Line->Tokens.end(), 2)->Tok;
804     if (PrePrevious->is(tok::at))
805       return;
806   }
807   if (Next->is(tok::exclaim) && PreviousMustBeValue)
808     return addUnwrappedLine();
809   bool NextMustBeValue = mustBeJSIdentOrValue(Keywords, Next);
810   bool NextEndsTemplateExpr =
811       Next->is(TT_TemplateString) && Next->TokenText.startswith("}");
812   if (NextMustBeValue && !NextEndsTemplateExpr && !PreviousStartsTemplateExpr &&
813       (PreviousMustBeValue ||
814        Previous->isOneOf(tok::r_square, tok::r_paren, tok::plusplus,
815                          tok::minusminus)))
816     return addUnwrappedLine();
817   if (PreviousMustBeValue && isJSDeclOrStmt(Keywords, Next))
818     return addUnwrappedLine();
819 }
820 
821 void UnwrappedLineParser::parseStructuralElement() {
822   assert(!FormatTok->is(tok::l_brace));
823   if (Style.Language == FormatStyle::LK_TableGen &&
824       FormatTok->is(tok::pp_include)) {
825     nextToken();
826     if (FormatTok->is(tok::string_literal))
827       nextToken();
828     addUnwrappedLine();
829     return;
830   }
831   switch (FormatTok->Tok.getKind()) {
832   case tok::at:
833     nextToken();
834     if (FormatTok->Tok.is(tok::l_brace)) {
835       parseBracedList();
836       break;
837     }
838     switch (FormatTok->Tok.getObjCKeywordID()) {
839     case tok::objc_public:
840     case tok::objc_protected:
841     case tok::objc_package:
842     case tok::objc_private:
843       return parseAccessSpecifier();
844     case tok::objc_interface:
845     case tok::objc_implementation:
846       return parseObjCInterfaceOrImplementation();
847     case tok::objc_protocol:
848       return parseObjCProtocol();
849     case tok::objc_end:
850       return; // Handled by the caller.
851     case tok::objc_optional:
852     case tok::objc_required:
853       nextToken();
854       addUnwrappedLine();
855       return;
856     case tok::objc_autoreleasepool:
857       nextToken();
858       if (FormatTok->Tok.is(tok::l_brace)) {
859         if (Style.BraceWrapping.AfterObjCDeclaration)
860           addUnwrappedLine();
861         parseBlock(/*MustBeDeclaration=*/false);
862       }
863       addUnwrappedLine();
864       return;
865     case tok::objc_try:
866       // This branch isn't strictly necessary (the kw_try case below would
867       // do this too after the tok::at is parsed above).  But be explicit.
868       parseTryCatch();
869       return;
870     default:
871       break;
872     }
873     break;
874   case tok::kw_asm:
875     nextToken();
876     if (FormatTok->is(tok::l_brace)) {
877       FormatTok->Type = TT_InlineASMBrace;
878       nextToken();
879       while (FormatTok && FormatTok->isNot(tok::eof)) {
880         if (FormatTok->is(tok::r_brace)) {
881           FormatTok->Type = TT_InlineASMBrace;
882           nextToken();
883           addUnwrappedLine();
884           break;
885         }
886         FormatTok->Finalized = true;
887         nextToken();
888       }
889     }
890     break;
891   case tok::kw_namespace:
892     parseNamespace();
893     return;
894   case tok::kw_inline:
895     nextToken();
896     if (FormatTok->Tok.is(tok::kw_namespace)) {
897       parseNamespace();
898       return;
899     }
900     break;
901   case tok::kw_public:
902   case tok::kw_protected:
903   case tok::kw_private:
904     if (Style.Language == FormatStyle::LK_Java ||
905         Style.Language == FormatStyle::LK_JavaScript)
906       nextToken();
907     else
908       parseAccessSpecifier();
909     return;
910   case tok::kw_if:
911     parseIfThenElse();
912     return;
913   case tok::kw_for:
914   case tok::kw_while:
915     parseForOrWhileLoop();
916     return;
917   case tok::kw_do:
918     parseDoWhile();
919     return;
920   case tok::kw_switch:
921     parseSwitch();
922     return;
923   case tok::kw_default:
924     nextToken();
925     parseLabel();
926     return;
927   case tok::kw_case:
928     parseCaseLabel();
929     return;
930   case tok::kw_try:
931   case tok::kw___try:
932     parseTryCatch();
933     return;
934   case tok::kw_extern:
935     nextToken();
936     if (FormatTok->Tok.is(tok::string_literal)) {
937       nextToken();
938       if (FormatTok->Tok.is(tok::l_brace)) {
939         parseBlock(/*MustBeDeclaration=*/true, /*AddLevel=*/false);
940         addUnwrappedLine();
941         return;
942       }
943     }
944     break;
945   case tok::kw_export:
946     if (Style.Language == FormatStyle::LK_JavaScript) {
947       parseJavaScriptEs6ImportExport();
948       return;
949     }
950     break;
951   case tok::identifier:
952     if (FormatTok->is(TT_ForEachMacro)) {
953       parseForOrWhileLoop();
954       return;
955     }
956     if (FormatTok->is(TT_MacroBlockBegin)) {
957       parseBlock(/*MustBeDeclaration=*/false, /*AddLevel=*/true,
958                  /*MunchSemi=*/false);
959       return;
960     }
961     if (FormatTok->is(Keywords.kw_import)) {
962       if (Style.Language == FormatStyle::LK_JavaScript) {
963         parseJavaScriptEs6ImportExport();
964         return;
965       }
966       if (Style.Language == FormatStyle::LK_Proto) {
967         nextToken();
968         if (FormatTok->is(tok::kw_public))
969           nextToken();
970         if (!FormatTok->is(tok::string_literal))
971           return;
972         nextToken();
973         if (FormatTok->is(tok::semi))
974           nextToken();
975         addUnwrappedLine();
976         return;
977       }
978     }
979     if (Style.isCpp() &&
980         FormatTok->isOneOf(Keywords.kw_signals, Keywords.kw_qsignals,
981                            Keywords.kw_slots, Keywords.kw_qslots)) {
982       nextToken();
983       if (FormatTok->is(tok::colon)) {
984         nextToken();
985         addUnwrappedLine();
986         return;
987       }
988     }
989     // In all other cases, parse the declaration.
990     break;
991   default:
992     break;
993   }
994   do {
995     const FormatToken *Previous = getPreviousToken();
996     switch (FormatTok->Tok.getKind()) {
997     case tok::at:
998       nextToken();
999       if (FormatTok->Tok.is(tok::l_brace))
1000         parseBracedList();
1001       break;
1002     case tok::kw_enum:
1003       // Ignore if this is part of "template <enum ...".
1004       if (Previous && Previous->is(tok::less)) {
1005         nextToken();
1006         break;
1007       }
1008 
1009       // parseEnum falls through and does not yet add an unwrapped line as an
1010       // enum definition can start a structural element.
1011       if (!parseEnum())
1012         break;
1013       // This only applies for C++.
1014       if (!Style.isCpp()) {
1015         addUnwrappedLine();
1016         return;
1017       }
1018       break;
1019     case tok::kw_typedef:
1020       nextToken();
1021       if (FormatTok->isOneOf(Keywords.kw_NS_ENUM, Keywords.kw_NS_OPTIONS,
1022                              Keywords.kw_CF_ENUM, Keywords.kw_CF_OPTIONS))
1023         parseEnum();
1024       break;
1025     case tok::kw_struct:
1026     case tok::kw_union:
1027     case tok::kw_class:
1028       // parseRecord falls through and does not yet add an unwrapped line as a
1029       // record declaration or definition can start a structural element.
1030       parseRecord();
1031       // This does not apply for Java and JavaScript.
1032       if (Style.Language == FormatStyle::LK_Java ||
1033           Style.Language == FormatStyle::LK_JavaScript) {
1034         if (FormatTok->is(tok::semi))
1035           nextToken();
1036         addUnwrappedLine();
1037         return;
1038       }
1039       break;
1040     case tok::period:
1041       nextToken();
1042       // In Java, classes have an implicit static member "class".
1043       if (Style.Language == FormatStyle::LK_Java && FormatTok &&
1044           FormatTok->is(tok::kw_class))
1045         nextToken();
1046       if (Style.Language == FormatStyle::LK_JavaScript && FormatTok &&
1047           FormatTok->Tok.getIdentifierInfo())
1048         // JavaScript only has pseudo keywords, all keywords are allowed to
1049         // appear in "IdentifierName" positions. See http://es5.github.io/#x7.6
1050         nextToken();
1051       break;
1052     case tok::semi:
1053       nextToken();
1054       addUnwrappedLine();
1055       return;
1056     case tok::r_brace:
1057       addUnwrappedLine();
1058       return;
1059     case tok::l_paren:
1060       parseParens();
1061       break;
1062     case tok::kw_operator:
1063       nextToken();
1064       if (FormatTok->isBinaryOperator())
1065         nextToken();
1066       break;
1067     case tok::caret:
1068       nextToken();
1069       if (FormatTok->Tok.isAnyIdentifier() ||
1070           FormatTok->isSimpleTypeSpecifier())
1071         nextToken();
1072       if (FormatTok->is(tok::l_paren))
1073         parseParens();
1074       if (FormatTok->is(tok::l_brace))
1075         parseChildBlock();
1076       break;
1077     case tok::l_brace:
1078       if (!tryToParseBracedList()) {
1079         // A block outside of parentheses must be the last part of a
1080         // structural element.
1081         // FIXME: Figure out cases where this is not true, and add projections
1082         // for them (the one we know is missing are lambdas).
1083         if (Style.BraceWrapping.AfterFunction)
1084           addUnwrappedLine();
1085         FormatTok->Type = TT_FunctionLBrace;
1086         parseBlock(/*MustBeDeclaration=*/false);
1087         addUnwrappedLine();
1088         return;
1089       }
1090       // Otherwise this was a braced init list, and the structural
1091       // element continues.
1092       break;
1093     case tok::kw_try:
1094       // We arrive here when parsing function-try blocks.
1095       parseTryCatch();
1096       return;
1097     case tok::identifier: {
1098       if (FormatTok->is(TT_MacroBlockEnd)) {
1099         addUnwrappedLine();
1100         return;
1101       }
1102 
1103       // Function declarations (as opposed to function expressions) are parsed
1104       // on their own unwrapped line by continuing this loop. Function
1105       // expressions (functions that are not on their own line) must not create
1106       // a new unwrapped line, so they are special cased below.
1107       size_t TokenCount = Line->Tokens.size();
1108       if (Style.Language == FormatStyle::LK_JavaScript &&
1109           FormatTok->is(Keywords.kw_function) &&
1110           (TokenCount > 1 || (TokenCount == 1 && !Line->Tokens.front().Tok->is(
1111                                                      Keywords.kw_async)))) {
1112         tryToParseJSFunction();
1113         break;
1114       }
1115       if ((Style.Language == FormatStyle::LK_JavaScript ||
1116            Style.Language == FormatStyle::LK_Java) &&
1117           FormatTok->is(Keywords.kw_interface)) {
1118         if (Style.Language == FormatStyle::LK_JavaScript) {
1119           // In JavaScript/TypeScript, "interface" can be used as a standalone
1120           // identifier, e.g. in `var interface = 1;`. If "interface" is
1121           // followed by another identifier, it is very like to be an actual
1122           // interface declaration.
1123           unsigned StoredPosition = Tokens->getPosition();
1124           FormatToken *Next = Tokens->getNextToken();
1125           FormatTok = Tokens->setPosition(StoredPosition);
1126           if (Next && !mustBeJSIdent(Keywords, Next)) {
1127             nextToken();
1128             break;
1129           }
1130         }
1131         parseRecord();
1132         addUnwrappedLine();
1133         return;
1134       }
1135 
1136       // See if the following token should start a new unwrapped line.
1137       StringRef Text = FormatTok->TokenText;
1138       nextToken();
1139       if (Line->Tokens.size() == 1 &&
1140           // JS doesn't have macros, and within classes colons indicate fields,
1141           // not labels.
1142           Style.Language != FormatStyle::LK_JavaScript) {
1143         if (FormatTok->Tok.is(tok::colon) && !Line->MustBeDeclaration) {
1144           Line->Tokens.begin()->Tok->MustBreakBefore = true;
1145           parseLabel();
1146           return;
1147         }
1148         // Recognize function-like macro usages without trailing semicolon as
1149         // well as free-standing macros like Q_OBJECT.
1150         bool FunctionLike = FormatTok->is(tok::l_paren);
1151         if (FunctionLike)
1152           parseParens();
1153 
1154         bool FollowedByNewline =
1155             CommentsBeforeNextToken.empty()
1156                 ? FormatTok->NewlinesBefore > 0
1157                 : CommentsBeforeNextToken.front()->NewlinesBefore > 0;
1158 
1159         if (FollowedByNewline && (Text.size() >= 5 || FunctionLike) &&
1160             tokenCanStartNewLine(FormatTok->Tok) && Text == Text.upper()) {
1161           addUnwrappedLine();
1162           return;
1163         }
1164       }
1165       break;
1166     }
1167     case tok::equal:
1168       // Fat arrows (=>) have tok::TokenKind tok::equal but TokenType
1169       // TT_JsFatArrow. The always start an expression or a child block if
1170       // followed by a curly.
1171       if (FormatTok->is(TT_JsFatArrow)) {
1172         nextToken();
1173         if (FormatTok->is(tok::l_brace))
1174           parseChildBlock();
1175         break;
1176       }
1177 
1178       nextToken();
1179       if (FormatTok->Tok.is(tok::l_brace)) {
1180         parseBracedList();
1181       }
1182       break;
1183     case tok::l_square:
1184       parseSquare();
1185       break;
1186     case tok::kw_new:
1187       parseNew();
1188       break;
1189     default:
1190       nextToken();
1191       break;
1192     }
1193   } while (!eof());
1194 }
1195 
1196 bool UnwrappedLineParser::tryToParseLambda() {
1197   if (!Style.isCpp()) {
1198     nextToken();
1199     return false;
1200   }
1201   const FormatToken* Previous = getPreviousToken();
1202   if (Previous &&
1203       (Previous->isOneOf(tok::identifier, tok::kw_operator, tok::kw_new,
1204                          tok::kw_delete) ||
1205        Previous->closesScope() || Previous->isSimpleTypeSpecifier())) {
1206     nextToken();
1207     return false;
1208   }
1209   assert(FormatTok->is(tok::l_square));
1210   FormatToken &LSquare = *FormatTok;
1211   if (!tryToParseLambdaIntroducer())
1212     return false;
1213 
1214   while (FormatTok->isNot(tok::l_brace)) {
1215     if (FormatTok->isSimpleTypeSpecifier()) {
1216       nextToken();
1217       continue;
1218     }
1219     switch (FormatTok->Tok.getKind()) {
1220     case tok::l_brace:
1221       break;
1222     case tok::l_paren:
1223       parseParens();
1224       break;
1225     case tok::amp:
1226     case tok::star:
1227     case tok::kw_const:
1228     case tok::comma:
1229     case tok::less:
1230     case tok::greater:
1231     case tok::identifier:
1232     case tok::numeric_constant:
1233     case tok::coloncolon:
1234     case tok::kw_mutable:
1235       nextToken();
1236       break;
1237     case tok::arrow:
1238       FormatTok->Type = TT_LambdaArrow;
1239       nextToken();
1240       break;
1241     default:
1242       return true;
1243     }
1244   }
1245   LSquare.Type = TT_LambdaLSquare;
1246   parseChildBlock();
1247   return true;
1248 }
1249 
1250 bool UnwrappedLineParser::tryToParseLambdaIntroducer() {
1251   nextToken();
1252   if (FormatTok->is(tok::equal)) {
1253     nextToken();
1254     if (FormatTok->is(tok::r_square)) {
1255       nextToken();
1256       return true;
1257     }
1258     if (FormatTok->isNot(tok::comma))
1259       return false;
1260     nextToken();
1261   } else if (FormatTok->is(tok::amp)) {
1262     nextToken();
1263     if (FormatTok->is(tok::r_square)) {
1264       nextToken();
1265       return true;
1266     }
1267     if (!FormatTok->isOneOf(tok::comma, tok::identifier)) {
1268       return false;
1269     }
1270     if (FormatTok->is(tok::comma))
1271       nextToken();
1272   } else if (FormatTok->is(tok::r_square)) {
1273     nextToken();
1274     return true;
1275   }
1276   do {
1277     if (FormatTok->is(tok::amp))
1278       nextToken();
1279     if (!FormatTok->isOneOf(tok::identifier, tok::kw_this))
1280       return false;
1281     nextToken();
1282     if (FormatTok->is(tok::ellipsis))
1283       nextToken();
1284     if (FormatTok->is(tok::comma)) {
1285       nextToken();
1286     } else if (FormatTok->is(tok::r_square)) {
1287       nextToken();
1288       return true;
1289     } else {
1290       return false;
1291     }
1292   } while (!eof());
1293   return false;
1294 }
1295 
1296 void UnwrappedLineParser::tryToParseJSFunction() {
1297   assert(FormatTok->is(Keywords.kw_function) ||
1298          FormatTok->startsSequence(Keywords.kw_async, Keywords.kw_function));
1299   if (FormatTok->is(Keywords.kw_async))
1300     nextToken();
1301   // Consume "function".
1302   nextToken();
1303 
1304   // Consume * (generator function). Treat it like C++'s overloaded operators.
1305   if (FormatTok->is(tok::star)) {
1306     FormatTok->Type = TT_OverloadedOperator;
1307     nextToken();
1308   }
1309 
1310   // Consume function name.
1311   if (FormatTok->is(tok::identifier))
1312     nextToken();
1313 
1314   if (FormatTok->isNot(tok::l_paren))
1315     return;
1316 
1317   // Parse formal parameter list.
1318   parseParens();
1319 
1320   if (FormatTok->is(tok::colon)) {
1321     // Parse a type definition.
1322     nextToken();
1323 
1324     // Eat the type declaration. For braced inline object types, balance braces,
1325     // otherwise just parse until finding an l_brace for the function body.
1326     if (FormatTok->is(tok::l_brace))
1327       tryToParseBracedList();
1328     else
1329       while (!FormatTok->isOneOf(tok::l_brace, tok::semi) && !eof())
1330         nextToken();
1331   }
1332 
1333   if (FormatTok->is(tok::semi))
1334     return;
1335 
1336   parseChildBlock();
1337 }
1338 
1339 bool UnwrappedLineParser::tryToParseBracedList() {
1340   if (FormatTok->BlockKind == BK_Unknown)
1341     calculateBraceTypes();
1342   assert(FormatTok->BlockKind != BK_Unknown);
1343   if (FormatTok->BlockKind == BK_Block)
1344     return false;
1345   parseBracedList();
1346   return true;
1347 }
1348 
1349 bool UnwrappedLineParser::parseBracedList(bool ContinueOnSemicolons) {
1350   bool HasError = false;
1351   nextToken();
1352 
1353   // FIXME: Once we have an expression parser in the UnwrappedLineParser,
1354   // replace this by using parseAssigmentExpression() inside.
1355   do {
1356     if (Style.Language == FormatStyle::LK_JavaScript) {
1357       if (FormatTok->is(Keywords.kw_function) ||
1358           FormatTok->startsSequence(Keywords.kw_async, Keywords.kw_function)) {
1359         tryToParseJSFunction();
1360         continue;
1361       }
1362       if (FormatTok->is(TT_JsFatArrow)) {
1363         nextToken();
1364         // Fat arrows can be followed by simple expressions or by child blocks
1365         // in curly braces.
1366         if (FormatTok->is(tok::l_brace)) {
1367           parseChildBlock();
1368           continue;
1369         }
1370       }
1371       if (FormatTok->is(tok::l_brace)) {
1372         // Could be a method inside of a braced list `{a() { return 1; }}`.
1373         if (tryToParseBracedList())
1374           continue;
1375         parseChildBlock();
1376       }
1377     }
1378     switch (FormatTok->Tok.getKind()) {
1379     case tok::caret:
1380       nextToken();
1381       if (FormatTok->is(tok::l_brace)) {
1382         parseChildBlock();
1383       }
1384       break;
1385     case tok::l_square:
1386       tryToParseLambda();
1387       break;
1388     case tok::l_paren:
1389       parseParens();
1390       // JavaScript can just have free standing methods and getters/setters in
1391       // object literals. Detect them by a "{" following ")".
1392       if (Style.Language == FormatStyle::LK_JavaScript) {
1393         if (FormatTok->is(tok::l_brace))
1394           parseChildBlock();
1395         break;
1396       }
1397       break;
1398     case tok::l_brace:
1399       // Assume there are no blocks inside a braced init list apart
1400       // from the ones we explicitly parse out (like lambdas).
1401       FormatTok->BlockKind = BK_BracedInit;
1402       parseBracedList();
1403       break;
1404     case tok::r_brace:
1405       nextToken();
1406       return !HasError;
1407     case tok::semi:
1408       // JavaScript (or more precisely TypeScript) can have semicolons in braced
1409       // lists (in so-called TypeMemberLists). Thus, the semicolon cannot be
1410       // used for error recovery if we have otherwise determined that this is
1411       // a braced list.
1412       if (Style.Language == FormatStyle::LK_JavaScript) {
1413         nextToken();
1414         break;
1415       }
1416       HasError = true;
1417       if (!ContinueOnSemicolons)
1418         return !HasError;
1419       nextToken();
1420       break;
1421     case tok::comma:
1422       nextToken();
1423       break;
1424     default:
1425       nextToken();
1426       break;
1427     }
1428   } while (!eof());
1429   return false;
1430 }
1431 
1432 void UnwrappedLineParser::parseParens() {
1433   assert(FormatTok->Tok.is(tok::l_paren) && "'(' expected.");
1434   nextToken();
1435   do {
1436     switch (FormatTok->Tok.getKind()) {
1437     case tok::l_paren:
1438       parseParens();
1439       if (Style.Language == FormatStyle::LK_Java && FormatTok->is(tok::l_brace))
1440         parseChildBlock();
1441       break;
1442     case tok::r_paren:
1443       nextToken();
1444       return;
1445     case tok::r_brace:
1446       // A "}" inside parenthesis is an error if there wasn't a matching "{".
1447       return;
1448     case tok::l_square:
1449       tryToParseLambda();
1450       break;
1451     case tok::l_brace:
1452       if (!tryToParseBracedList())
1453         parseChildBlock();
1454       break;
1455     case tok::at:
1456       nextToken();
1457       if (FormatTok->Tok.is(tok::l_brace))
1458         parseBracedList();
1459       break;
1460     case tok::kw_class:
1461       if (Style.Language == FormatStyle::LK_JavaScript)
1462         parseRecord(/*ParseAsExpr=*/true);
1463       else
1464         nextToken();
1465       break;
1466     case tok::identifier:
1467       if (Style.Language == FormatStyle::LK_JavaScript &&
1468           (FormatTok->is(Keywords.kw_function) ||
1469            FormatTok->startsSequence(Keywords.kw_async, Keywords.kw_function)))
1470         tryToParseJSFunction();
1471       else
1472         nextToken();
1473       break;
1474     default:
1475       nextToken();
1476       break;
1477     }
1478   } while (!eof());
1479 }
1480 
1481 void UnwrappedLineParser::parseSquare() {
1482   assert(FormatTok->Tok.is(tok::l_square) && "'[' expected.");
1483   if (tryToParseLambda())
1484     return;
1485   do {
1486     switch (FormatTok->Tok.getKind()) {
1487     case tok::l_paren:
1488       parseParens();
1489       break;
1490     case tok::r_square:
1491       nextToken();
1492       return;
1493     case tok::r_brace:
1494       // A "}" inside parenthesis is an error if there wasn't a matching "{".
1495       return;
1496     case tok::l_square:
1497       parseSquare();
1498       break;
1499     case tok::l_brace: {
1500       if (!tryToParseBracedList())
1501         parseChildBlock();
1502       break;
1503     }
1504     case tok::at:
1505       nextToken();
1506       if (FormatTok->Tok.is(tok::l_brace))
1507         parseBracedList();
1508       break;
1509     default:
1510       nextToken();
1511       break;
1512     }
1513   } while (!eof());
1514 }
1515 
1516 void UnwrappedLineParser::parseIfThenElse() {
1517   assert(FormatTok->Tok.is(tok::kw_if) && "'if' expected");
1518   nextToken();
1519   if (FormatTok->Tok.is(tok::kw_constexpr))
1520     nextToken();
1521   if (FormatTok->Tok.is(tok::l_paren))
1522     parseParens();
1523   bool NeedsUnwrappedLine = false;
1524   if (FormatTok->Tok.is(tok::l_brace)) {
1525     CompoundStatementIndenter Indenter(this, Style, Line->Level);
1526     parseBlock(/*MustBeDeclaration=*/false);
1527     if (Style.BraceWrapping.BeforeElse)
1528       addUnwrappedLine();
1529     else
1530       NeedsUnwrappedLine = true;
1531   } else {
1532     addUnwrappedLine();
1533     ++Line->Level;
1534     parseStructuralElement();
1535     --Line->Level;
1536   }
1537   if (FormatTok->Tok.is(tok::kw_else)) {
1538     nextToken();
1539     if (FormatTok->Tok.is(tok::l_brace)) {
1540       CompoundStatementIndenter Indenter(this, Style, Line->Level);
1541       parseBlock(/*MustBeDeclaration=*/false);
1542       addUnwrappedLine();
1543     } else if (FormatTok->Tok.is(tok::kw_if)) {
1544       parseIfThenElse();
1545     } else {
1546       addUnwrappedLine();
1547       ++Line->Level;
1548       parseStructuralElement();
1549       if (FormatTok->is(tok::eof))
1550         addUnwrappedLine();
1551       --Line->Level;
1552     }
1553   } else if (NeedsUnwrappedLine) {
1554     addUnwrappedLine();
1555   }
1556 }
1557 
1558 void UnwrappedLineParser::parseTryCatch() {
1559   assert(FormatTok->isOneOf(tok::kw_try, tok::kw___try) && "'try' expected");
1560   nextToken();
1561   bool NeedsUnwrappedLine = false;
1562   if (FormatTok->is(tok::colon)) {
1563     // We are in a function try block, what comes is an initializer list.
1564     nextToken();
1565     while (FormatTok->is(tok::identifier)) {
1566       nextToken();
1567       if (FormatTok->is(tok::l_paren))
1568         parseParens();
1569       if (FormatTok->is(tok::comma))
1570         nextToken();
1571     }
1572   }
1573   // Parse try with resource.
1574   if (Style.Language == FormatStyle::LK_Java && FormatTok->is(tok::l_paren)) {
1575     parseParens();
1576   }
1577   if (FormatTok->is(tok::l_brace)) {
1578     CompoundStatementIndenter Indenter(this, Style, Line->Level);
1579     parseBlock(/*MustBeDeclaration=*/false);
1580     if (Style.BraceWrapping.BeforeCatch) {
1581       addUnwrappedLine();
1582     } else {
1583       NeedsUnwrappedLine = true;
1584     }
1585   } else if (!FormatTok->is(tok::kw_catch)) {
1586     // The C++ standard requires a compound-statement after a try.
1587     // If there's none, we try to assume there's a structuralElement
1588     // and try to continue.
1589     addUnwrappedLine();
1590     ++Line->Level;
1591     parseStructuralElement();
1592     --Line->Level;
1593   }
1594   while (1) {
1595     if (FormatTok->is(tok::at))
1596       nextToken();
1597     if (!(FormatTok->isOneOf(tok::kw_catch, Keywords.kw___except,
1598                              tok::kw___finally) ||
1599           ((Style.Language == FormatStyle::LK_Java ||
1600             Style.Language == FormatStyle::LK_JavaScript) &&
1601            FormatTok->is(Keywords.kw_finally)) ||
1602           (FormatTok->Tok.isObjCAtKeyword(tok::objc_catch) ||
1603            FormatTok->Tok.isObjCAtKeyword(tok::objc_finally))))
1604       break;
1605     nextToken();
1606     while (FormatTok->isNot(tok::l_brace)) {
1607       if (FormatTok->is(tok::l_paren)) {
1608         parseParens();
1609         continue;
1610       }
1611       if (FormatTok->isOneOf(tok::semi, tok::r_brace, tok::eof))
1612         return;
1613       nextToken();
1614     }
1615     NeedsUnwrappedLine = false;
1616     CompoundStatementIndenter Indenter(this, Style, Line->Level);
1617     parseBlock(/*MustBeDeclaration=*/false);
1618     if (Style.BraceWrapping.BeforeCatch)
1619       addUnwrappedLine();
1620     else
1621       NeedsUnwrappedLine = true;
1622   }
1623   if (NeedsUnwrappedLine)
1624     addUnwrappedLine();
1625 }
1626 
1627 void UnwrappedLineParser::parseNamespace() {
1628   assert(FormatTok->Tok.is(tok::kw_namespace) && "'namespace' expected");
1629 
1630   const FormatToken &InitialToken = *FormatTok;
1631   nextToken();
1632   while (FormatTok->isOneOf(tok::identifier, tok::coloncolon))
1633     nextToken();
1634   if (FormatTok->Tok.is(tok::l_brace)) {
1635     if (ShouldBreakBeforeBrace(Style, InitialToken))
1636       addUnwrappedLine();
1637 
1638     bool AddLevel = Style.NamespaceIndentation == FormatStyle::NI_All ||
1639                     (Style.NamespaceIndentation == FormatStyle::NI_Inner &&
1640                      DeclarationScopeStack.size() > 1);
1641     parseBlock(/*MustBeDeclaration=*/true, AddLevel);
1642     // Munch the semicolon after a namespace. This is more common than one would
1643     // think. Puttin the semicolon into its own line is very ugly.
1644     if (FormatTok->Tok.is(tok::semi))
1645       nextToken();
1646     addUnwrappedLine();
1647   }
1648   // FIXME: Add error handling.
1649 }
1650 
1651 void UnwrappedLineParser::parseNew() {
1652   assert(FormatTok->is(tok::kw_new) && "'new' expected");
1653   nextToken();
1654   if (Style.Language != FormatStyle::LK_Java)
1655     return;
1656 
1657   // In Java, we can parse everything up to the parens, which aren't optional.
1658   do {
1659     // There should not be a ;, { or } before the new's open paren.
1660     if (FormatTok->isOneOf(tok::semi, tok::l_brace, tok::r_brace))
1661       return;
1662 
1663     // Consume the parens.
1664     if (FormatTok->is(tok::l_paren)) {
1665       parseParens();
1666 
1667       // If there is a class body of an anonymous class, consume that as child.
1668       if (FormatTok->is(tok::l_brace))
1669         parseChildBlock();
1670       return;
1671     }
1672     nextToken();
1673   } while (!eof());
1674 }
1675 
1676 void UnwrappedLineParser::parseForOrWhileLoop() {
1677   assert(FormatTok->isOneOf(tok::kw_for, tok::kw_while, TT_ForEachMacro) &&
1678          "'for', 'while' or foreach macro expected");
1679   nextToken();
1680   // JS' for await ( ...
1681   if (Style.Language == FormatStyle::LK_JavaScript &&
1682       FormatTok->is(Keywords.kw_await))
1683     nextToken();
1684   if (FormatTok->Tok.is(tok::l_paren))
1685     parseParens();
1686   if (FormatTok->Tok.is(tok::l_brace)) {
1687     CompoundStatementIndenter Indenter(this, Style, Line->Level);
1688     parseBlock(/*MustBeDeclaration=*/false);
1689     addUnwrappedLine();
1690   } else {
1691     addUnwrappedLine();
1692     ++Line->Level;
1693     parseStructuralElement();
1694     --Line->Level;
1695   }
1696 }
1697 
1698 void UnwrappedLineParser::parseDoWhile() {
1699   assert(FormatTok->Tok.is(tok::kw_do) && "'do' expected");
1700   nextToken();
1701   if (FormatTok->Tok.is(tok::l_brace)) {
1702     CompoundStatementIndenter Indenter(this, Style, Line->Level);
1703     parseBlock(/*MustBeDeclaration=*/false);
1704     if (Style.BraceWrapping.IndentBraces)
1705       addUnwrappedLine();
1706   } else {
1707     addUnwrappedLine();
1708     ++Line->Level;
1709     parseStructuralElement();
1710     --Line->Level;
1711   }
1712 
1713   // FIXME: Add error handling.
1714   if (!FormatTok->Tok.is(tok::kw_while)) {
1715     addUnwrappedLine();
1716     return;
1717   }
1718 
1719   nextToken();
1720   parseStructuralElement();
1721 }
1722 
1723 void UnwrappedLineParser::parseLabel() {
1724   nextToken();
1725   unsigned OldLineLevel = Line->Level;
1726   if (Line->Level > 1 || (!Line->InPPDirective && Line->Level > 0))
1727     --Line->Level;
1728   if (CommentsBeforeNextToken.empty() && FormatTok->Tok.is(tok::l_brace)) {
1729     CompoundStatementIndenter Indenter(this, Style, Line->Level);
1730     parseBlock(/*MustBeDeclaration=*/false);
1731     if (FormatTok->Tok.is(tok::kw_break)) {
1732       if (Style.BraceWrapping.AfterControlStatement)
1733         addUnwrappedLine();
1734       parseStructuralElement();
1735     }
1736     addUnwrappedLine();
1737   } else {
1738     if (FormatTok->is(tok::semi))
1739       nextToken();
1740     addUnwrappedLine();
1741   }
1742   Line->Level = OldLineLevel;
1743   if (FormatTok->isNot(tok::l_brace)) {
1744     parseStructuralElement();
1745     addUnwrappedLine();
1746   }
1747 }
1748 
1749 void UnwrappedLineParser::parseCaseLabel() {
1750   assert(FormatTok->Tok.is(tok::kw_case) && "'case' expected");
1751   // FIXME: fix handling of complex expressions here.
1752   do {
1753     nextToken();
1754   } while (!eof() && !FormatTok->Tok.is(tok::colon));
1755   parseLabel();
1756 }
1757 
1758 void UnwrappedLineParser::parseSwitch() {
1759   assert(FormatTok->Tok.is(tok::kw_switch) && "'switch' expected");
1760   nextToken();
1761   if (FormatTok->Tok.is(tok::l_paren))
1762     parseParens();
1763   if (FormatTok->Tok.is(tok::l_brace)) {
1764     CompoundStatementIndenter Indenter(this, Style, Line->Level);
1765     parseBlock(/*MustBeDeclaration=*/false);
1766     addUnwrappedLine();
1767   } else {
1768     addUnwrappedLine();
1769     ++Line->Level;
1770     parseStructuralElement();
1771     --Line->Level;
1772   }
1773 }
1774 
1775 void UnwrappedLineParser::parseAccessSpecifier() {
1776   nextToken();
1777   // Understand Qt's slots.
1778   if (FormatTok->isOneOf(Keywords.kw_slots, Keywords.kw_qslots))
1779     nextToken();
1780   // Otherwise, we don't know what it is, and we'd better keep the next token.
1781   if (FormatTok->Tok.is(tok::colon))
1782     nextToken();
1783   addUnwrappedLine();
1784 }
1785 
1786 bool UnwrappedLineParser::parseEnum() {
1787   // Won't be 'enum' for NS_ENUMs.
1788   if (FormatTok->Tok.is(tok::kw_enum))
1789     nextToken();
1790 
1791   // In TypeScript, "enum" can also be used as property name, e.g. in interface
1792   // declarations. An "enum" keyword followed by a colon would be a syntax
1793   // error and thus assume it is just an identifier.
1794   if (Style.Language == FormatStyle::LK_JavaScript &&
1795       FormatTok->isOneOf(tok::colon, tok::question))
1796     return false;
1797 
1798   // Eat up enum class ...
1799   if (FormatTok->Tok.is(tok::kw_class) || FormatTok->Tok.is(tok::kw_struct))
1800     nextToken();
1801 
1802   while (FormatTok->Tok.getIdentifierInfo() ||
1803          FormatTok->isOneOf(tok::colon, tok::coloncolon, tok::less,
1804                             tok::greater, tok::comma, tok::question)) {
1805     nextToken();
1806     // We can have macros or attributes in between 'enum' and the enum name.
1807     if (FormatTok->is(tok::l_paren))
1808       parseParens();
1809     if (FormatTok->is(tok::identifier)) {
1810       nextToken();
1811       // If there are two identifiers in a row, this is likely an elaborate
1812       // return type. In Java, this can be "implements", etc.
1813       if (Style.isCpp() && FormatTok->is(tok::identifier))
1814         return false;
1815     }
1816   }
1817 
1818   // Just a declaration or something is wrong.
1819   if (FormatTok->isNot(tok::l_brace))
1820     return true;
1821   FormatTok->BlockKind = BK_Block;
1822 
1823   if (Style.Language == FormatStyle::LK_Java) {
1824     // Java enums are different.
1825     parseJavaEnumBody();
1826     return true;
1827   }
1828   if (Style.Language == FormatStyle::LK_Proto) {
1829     parseBlock(/*MustBeDeclaration=*/true);
1830     return true;
1831   }
1832 
1833   // Parse enum body.
1834   bool HasError = !parseBracedList(/*ContinueOnSemicolons=*/true);
1835   if (HasError) {
1836     if (FormatTok->is(tok::semi))
1837       nextToken();
1838     addUnwrappedLine();
1839   }
1840   return true;
1841 
1842   // There is no addUnwrappedLine() here so that we fall through to parsing a
1843   // structural element afterwards. Thus, in "enum A {} n, m;",
1844   // "} n, m;" will end up in one unwrapped line.
1845 }
1846 
1847 void UnwrappedLineParser::parseJavaEnumBody() {
1848   // Determine whether the enum is simple, i.e. does not have a semicolon or
1849   // constants with class bodies. Simple enums can be formatted like braced
1850   // lists, contracted to a single line, etc.
1851   unsigned StoredPosition = Tokens->getPosition();
1852   bool IsSimple = true;
1853   FormatToken *Tok = Tokens->getNextToken();
1854   while (Tok) {
1855     if (Tok->is(tok::r_brace))
1856       break;
1857     if (Tok->isOneOf(tok::l_brace, tok::semi)) {
1858       IsSimple = false;
1859       break;
1860     }
1861     // FIXME: This will also mark enums with braces in the arguments to enum
1862     // constants as "not simple". This is probably fine in practice, though.
1863     Tok = Tokens->getNextToken();
1864   }
1865   FormatTok = Tokens->setPosition(StoredPosition);
1866 
1867   if (IsSimple) {
1868     parseBracedList();
1869     addUnwrappedLine();
1870     return;
1871   }
1872 
1873   // Parse the body of a more complex enum.
1874   // First add a line for everything up to the "{".
1875   nextToken();
1876   addUnwrappedLine();
1877   ++Line->Level;
1878 
1879   // Parse the enum constants.
1880   while (FormatTok) {
1881     if (FormatTok->is(tok::l_brace)) {
1882       // Parse the constant's class body.
1883       parseBlock(/*MustBeDeclaration=*/true, /*AddLevel=*/true,
1884                  /*MunchSemi=*/false);
1885     } else if (FormatTok->is(tok::l_paren)) {
1886       parseParens();
1887     } else if (FormatTok->is(tok::comma)) {
1888       nextToken();
1889       addUnwrappedLine();
1890     } else if (FormatTok->is(tok::semi)) {
1891       nextToken();
1892       addUnwrappedLine();
1893       break;
1894     } else if (FormatTok->is(tok::r_brace)) {
1895       addUnwrappedLine();
1896       break;
1897     } else {
1898       nextToken();
1899     }
1900   }
1901 
1902   // Parse the class body after the enum's ";" if any.
1903   parseLevel(/*HasOpeningBrace=*/true);
1904   nextToken();
1905   --Line->Level;
1906   addUnwrappedLine();
1907 }
1908 
1909 void UnwrappedLineParser::parseRecord(bool ParseAsExpr) {
1910   const FormatToken &InitialToken = *FormatTok;
1911   nextToken();
1912 
1913   // The actual identifier can be a nested name specifier, and in macros
1914   // it is often token-pasted.
1915   while (FormatTok->isOneOf(tok::identifier, tok::coloncolon, tok::hashhash,
1916                             tok::kw___attribute, tok::kw___declspec,
1917                             tok::kw_alignas) ||
1918          ((Style.Language == FormatStyle::LK_Java ||
1919            Style.Language == FormatStyle::LK_JavaScript) &&
1920           FormatTok->isOneOf(tok::period, tok::comma))) {
1921     bool IsNonMacroIdentifier =
1922         FormatTok->is(tok::identifier) &&
1923         FormatTok->TokenText != FormatTok->TokenText.upper();
1924     nextToken();
1925     // We can have macros or attributes in between 'class' and the class name.
1926     if (!IsNonMacroIdentifier && FormatTok->Tok.is(tok::l_paren))
1927       parseParens();
1928   }
1929 
1930   // Note that parsing away template declarations here leads to incorrectly
1931   // accepting function declarations as record declarations.
1932   // In general, we cannot solve this problem. Consider:
1933   // class A<int> B() {}
1934   // which can be a function definition or a class definition when B() is a
1935   // macro. If we find enough real-world cases where this is a problem, we
1936   // can parse for the 'template' keyword in the beginning of the statement,
1937   // and thus rule out the record production in case there is no template
1938   // (this would still leave us with an ambiguity between template function
1939   // and class declarations).
1940   if (FormatTok->isOneOf(tok::colon, tok::less)) {
1941     while (!eof()) {
1942       if (FormatTok->is(tok::l_brace)) {
1943         calculateBraceTypes(/*ExpectClassBody=*/true);
1944         if (!tryToParseBracedList())
1945           break;
1946       }
1947       if (FormatTok->Tok.is(tok::semi))
1948         return;
1949       nextToken();
1950     }
1951   }
1952   if (FormatTok->Tok.is(tok::l_brace)) {
1953     if (ParseAsExpr) {
1954       parseChildBlock();
1955     } else {
1956       if (ShouldBreakBeforeBrace(Style, InitialToken))
1957         addUnwrappedLine();
1958 
1959       parseBlock(/*MustBeDeclaration=*/true, /*AddLevel=*/true,
1960                  /*MunchSemi=*/false);
1961     }
1962   }
1963   // There is no addUnwrappedLine() here so that we fall through to parsing a
1964   // structural element afterwards. Thus, in "class A {} n, m;",
1965   // "} n, m;" will end up in one unwrapped line.
1966 }
1967 
1968 void UnwrappedLineParser::parseObjCProtocolList() {
1969   assert(FormatTok->Tok.is(tok::less) && "'<' expected.");
1970   do
1971     nextToken();
1972   while (!eof() && FormatTok->Tok.isNot(tok::greater));
1973   nextToken(); // Skip '>'.
1974 }
1975 
1976 void UnwrappedLineParser::parseObjCUntilAtEnd() {
1977   do {
1978     if (FormatTok->Tok.isObjCAtKeyword(tok::objc_end)) {
1979       nextToken();
1980       addUnwrappedLine();
1981       break;
1982     }
1983     if (FormatTok->is(tok::l_brace)) {
1984       parseBlock(/*MustBeDeclaration=*/false);
1985       // In ObjC interfaces, nothing should be following the "}".
1986       addUnwrappedLine();
1987     } else if (FormatTok->is(tok::r_brace)) {
1988       // Ignore stray "}". parseStructuralElement doesn't consume them.
1989       nextToken();
1990       addUnwrappedLine();
1991     } else {
1992       parseStructuralElement();
1993     }
1994   } while (!eof());
1995 }
1996 
1997 void UnwrappedLineParser::parseObjCInterfaceOrImplementation() {
1998   nextToken();
1999   nextToken(); // interface name
2000 
2001   // @interface can be followed by either a base class, or a category.
2002   if (FormatTok->Tok.is(tok::colon)) {
2003     nextToken();
2004     nextToken(); // base class name
2005   } else if (FormatTok->Tok.is(tok::l_paren))
2006     // Skip category, if present.
2007     parseParens();
2008 
2009   if (FormatTok->Tok.is(tok::less))
2010     parseObjCProtocolList();
2011 
2012   if (FormatTok->Tok.is(tok::l_brace)) {
2013     if (Style.BraceWrapping.AfterObjCDeclaration)
2014       addUnwrappedLine();
2015     parseBlock(/*MustBeDeclaration=*/true);
2016   }
2017 
2018   // With instance variables, this puts '}' on its own line.  Without instance
2019   // variables, this ends the @interface line.
2020   addUnwrappedLine();
2021 
2022   parseObjCUntilAtEnd();
2023 }
2024 
2025 void UnwrappedLineParser::parseObjCProtocol() {
2026   nextToken();
2027   nextToken(); // protocol name
2028 
2029   if (FormatTok->Tok.is(tok::less))
2030     parseObjCProtocolList();
2031 
2032   // Check for protocol declaration.
2033   if (FormatTok->Tok.is(tok::semi)) {
2034     nextToken();
2035     return addUnwrappedLine();
2036   }
2037 
2038   addUnwrappedLine();
2039   parseObjCUntilAtEnd();
2040 }
2041 
2042 void UnwrappedLineParser::parseJavaScriptEs6ImportExport() {
2043   bool IsImport = FormatTok->is(Keywords.kw_import);
2044   assert(IsImport || FormatTok->is(tok::kw_export));
2045   nextToken();
2046 
2047   // Consume the "default" in "export default class/function".
2048   if (FormatTok->is(tok::kw_default))
2049     nextToken();
2050 
2051   // Consume "async function", "function" and "default function", so that these
2052   // get parsed as free-standing JS functions, i.e. do not require a trailing
2053   // semicolon.
2054   if (FormatTok->is(Keywords.kw_async))
2055     nextToken();
2056   if (FormatTok->is(Keywords.kw_function)) {
2057     nextToken();
2058     return;
2059   }
2060 
2061   // For imports, `export *`, `export {...}`, consume the rest of the line up
2062   // to the terminating `;`. For everything else, just return and continue
2063   // parsing the structural element, i.e. the declaration or expression for
2064   // `export default`.
2065   if (!IsImport && !FormatTok->isOneOf(tok::l_brace, tok::star) &&
2066       !FormatTok->isStringLiteral())
2067     return;
2068 
2069   while (!eof()) {
2070     if (FormatTok->is(tok::semi))
2071       return;
2072     if (Line->Tokens.size() == 0) {
2073       // Common issue: Automatic Semicolon Insertion wrapped the line, so the
2074       // import statement should terminate.
2075       return;
2076     }
2077     if (FormatTok->is(tok::l_brace)) {
2078       FormatTok->BlockKind = BK_Block;
2079       parseBracedList();
2080     } else {
2081       nextToken();
2082     }
2083   }
2084 }
2085 
2086 LLVM_ATTRIBUTE_UNUSED static void printDebugInfo(const UnwrappedLine &Line,
2087                                                  StringRef Prefix = "") {
2088   llvm::dbgs() << Prefix << "Line(" << Line.Level << ")"
2089                << (Line.InPPDirective ? " MACRO" : "") << ": ";
2090   for (std::list<UnwrappedLineNode>::const_iterator I = Line.Tokens.begin(),
2091                                                     E = Line.Tokens.end();
2092        I != E; ++I) {
2093     llvm::dbgs() << I->Tok->Tok.getName() << "["
2094                  << "T=" << I->Tok->Type
2095                  << ", OC=" << I->Tok->OriginalColumn << "] ";
2096   }
2097   for (std::list<UnwrappedLineNode>::const_iterator I = Line.Tokens.begin(),
2098                                                     E = Line.Tokens.end();
2099        I != E; ++I) {
2100     const UnwrappedLineNode &Node = *I;
2101     for (SmallVectorImpl<UnwrappedLine>::const_iterator
2102              I = Node.Children.begin(),
2103              E = Node.Children.end();
2104          I != E; ++I) {
2105       printDebugInfo(*I, "\nChild: ");
2106     }
2107   }
2108   llvm::dbgs() << "\n";
2109 }
2110 
2111 void UnwrappedLineParser::addUnwrappedLine() {
2112   if (Line->Tokens.empty())
2113     return;
2114   DEBUG({
2115     if (CurrentLines == &Lines)
2116       printDebugInfo(*Line);
2117   });
2118   CurrentLines->push_back(std::move(*Line));
2119   Line->Tokens.clear();
2120   Line->MatchingOpeningBlockLineIndex = UnwrappedLine::kInvalidIndex;
2121   if (CurrentLines == &Lines && !PreprocessorDirectives.empty()) {
2122     CurrentLines->append(
2123         std::make_move_iterator(PreprocessorDirectives.begin()),
2124         std::make_move_iterator(PreprocessorDirectives.end()));
2125     PreprocessorDirectives.clear();
2126   }
2127 }
2128 
2129 bool UnwrappedLineParser::eof() const { return FormatTok->Tok.is(tok::eof); }
2130 
2131 bool UnwrappedLineParser::isOnNewLine(const FormatToken &FormatTok) {
2132   return (Line->InPPDirective || FormatTok.HasUnescapedNewline) &&
2133          FormatTok.NewlinesBefore > 0;
2134 }
2135 
2136 // Checks if \p FormatTok is a line comment that continues the line comment
2137 // section on \p Line.
2138 static bool continuesLineCommentSection(const FormatToken &FormatTok,
2139                                         const UnwrappedLine &Line,
2140                                         llvm::Regex &CommentPragmasRegex) {
2141   if (Line.Tokens.empty())
2142     return false;
2143 
2144   StringRef IndentContent = FormatTok.TokenText;
2145   if (FormatTok.TokenText.startswith("//") ||
2146       FormatTok.TokenText.startswith("/*"))
2147     IndentContent = FormatTok.TokenText.substr(2);
2148   if (CommentPragmasRegex.match(IndentContent))
2149     return false;
2150 
2151   // If Line starts with a line comment, then FormatTok continues the comment
2152   // section if its original column is greater or equal to the original start
2153   // column of the line.
2154   //
2155   // Define the min column token of a line as follows: if a line ends in '{' or
2156   // contains a '{' followed by a line comment, then the min column token is
2157   // that '{'. Otherwise, the min column token of the line is the first token of
2158   // the line.
2159   //
2160   // If Line starts with a token other than a line comment, then FormatTok
2161   // continues the comment section if its original column is greater than the
2162   // original start column of the min column token of the line.
2163   //
2164   // For example, the second line comment continues the first in these cases:
2165   //
2166   // // first line
2167   // // second line
2168   //
2169   // and:
2170   //
2171   // // first line
2172   //  // second line
2173   //
2174   // and:
2175   //
2176   // int i; // first line
2177   //  // second line
2178   //
2179   // and:
2180   //
2181   // do { // first line
2182   //      // second line
2183   //   int i;
2184   // } while (true);
2185   //
2186   // and:
2187   //
2188   // enum {
2189   //   a, // first line
2190   //    // second line
2191   //   b
2192   // };
2193   //
2194   // The second line comment doesn't continue the first in these cases:
2195   //
2196   //   // first line
2197   //  // second line
2198   //
2199   // and:
2200   //
2201   // int i; // first line
2202   // // second line
2203   //
2204   // and:
2205   //
2206   // do { // first line
2207   //   // second line
2208   //   int i;
2209   // } while (true);
2210   //
2211   // and:
2212   //
2213   // enum {
2214   //   a, // first line
2215   //   // second line
2216   // };
2217   const FormatToken *MinColumnToken = Line.Tokens.front().Tok;
2218 
2219   // Scan for '{//'. If found, use the column of '{' as a min column for line
2220   // comment section continuation.
2221   const FormatToken *PreviousToken = nullptr;
2222   for (const UnwrappedLineNode &Node : Line.Tokens) {
2223     if (PreviousToken && PreviousToken->is(tok::l_brace) &&
2224         isLineComment(*Node.Tok)) {
2225       MinColumnToken = PreviousToken;
2226       break;
2227     }
2228     PreviousToken = Node.Tok;
2229 
2230     // Grab the last newline preceding a token in this unwrapped line.
2231     if (Node.Tok->NewlinesBefore > 0) {
2232       MinColumnToken = Node.Tok;
2233     }
2234   }
2235   if (PreviousToken && PreviousToken->is(tok::l_brace)) {
2236     MinColumnToken = PreviousToken;
2237   }
2238 
2239   return continuesLineComment(FormatTok, /*Previous=*/Line.Tokens.back().Tok,
2240                               MinColumnToken);
2241 }
2242 
2243 void UnwrappedLineParser::flushComments(bool NewlineBeforeNext) {
2244   bool JustComments = Line->Tokens.empty();
2245   for (SmallVectorImpl<FormatToken *>::const_iterator
2246            I = CommentsBeforeNextToken.begin(),
2247            E = CommentsBeforeNextToken.end();
2248        I != E; ++I) {
2249     // Line comments that belong to the same line comment section are put on the
2250     // same line since later we might want to reflow content between them.
2251     // Additional fine-grained breaking of line comment sections is controlled
2252     // by the class BreakableLineCommentSection in case it is desirable to keep
2253     // several line comment sections in the same unwrapped line.
2254     //
2255     // FIXME: Consider putting separate line comment sections as children to the
2256     // unwrapped line instead.
2257     (*I)->ContinuesLineCommentSection =
2258         continuesLineCommentSection(**I, *Line, CommentPragmasRegex);
2259     if (isOnNewLine(**I) && JustComments && !(*I)->ContinuesLineCommentSection)
2260       addUnwrappedLine();
2261     pushToken(*I);
2262   }
2263   if (NewlineBeforeNext && JustComments)
2264     addUnwrappedLine();
2265   CommentsBeforeNextToken.clear();
2266 }
2267 
2268 void UnwrappedLineParser::nextToken() {
2269   if (eof())
2270     return;
2271   flushComments(isOnNewLine(*FormatTok));
2272   pushToken(FormatTok);
2273   if (Style.Language != FormatStyle::LK_JavaScript)
2274     readToken();
2275   else
2276     readTokenWithJavaScriptASI();
2277 }
2278 
2279 const FormatToken *UnwrappedLineParser::getPreviousToken() {
2280   // FIXME: This is a dirty way to access the previous token. Find a better
2281   // solution.
2282   if (!Line || Line->Tokens.empty())
2283     return nullptr;
2284   return Line->Tokens.back().Tok;
2285 }
2286 
2287 void UnwrappedLineParser::distributeComments(
2288     const SmallVectorImpl<FormatToken *> &Comments,
2289     const FormatToken *NextTok) {
2290   // Whether or not a line comment token continues a line is controlled by
2291   // the method continuesLineCommentSection, with the following caveat:
2292   //
2293   // Define a trail of Comments to be a nonempty proper postfix of Comments such
2294   // that each comment line from the trail is aligned with the next token, if
2295   // the next token exists. If a trail exists, the beginning of the maximal
2296   // trail is marked as a start of a new comment section.
2297   //
2298   // For example in this code:
2299   //
2300   // int a; // line about a
2301   //   // line 1 about b
2302   //   // line 2 about b
2303   //   int b;
2304   //
2305   // the two lines about b form a maximal trail, so there are two sections, the
2306   // first one consisting of the single comment "// line about a" and the
2307   // second one consisting of the next two comments.
2308   if (Comments.empty())
2309     return;
2310   bool ShouldPushCommentsInCurrentLine = true;
2311   bool HasTrailAlignedWithNextToken = false;
2312   unsigned StartOfTrailAlignedWithNextToken = 0;
2313   if (NextTok) {
2314     // We are skipping the first element intentionally.
2315     for (unsigned i = Comments.size() - 1; i > 0; --i) {
2316       if (Comments[i]->OriginalColumn == NextTok->OriginalColumn) {
2317         HasTrailAlignedWithNextToken = true;
2318         StartOfTrailAlignedWithNextToken = i;
2319       }
2320     }
2321   }
2322   for (unsigned i = 0, e = Comments.size(); i < e; ++i) {
2323     FormatToken *FormatTok = Comments[i];
2324     if (HasTrailAlignedWithNextToken &&
2325         i == StartOfTrailAlignedWithNextToken) {
2326       FormatTok->ContinuesLineCommentSection = false;
2327     } else {
2328       FormatTok->ContinuesLineCommentSection =
2329           continuesLineCommentSection(*FormatTok, *Line, CommentPragmasRegex);
2330     }
2331     if (!FormatTok->ContinuesLineCommentSection &&
2332         (isOnNewLine(*FormatTok) || FormatTok->IsFirst)) {
2333       ShouldPushCommentsInCurrentLine = false;
2334     }
2335     if (ShouldPushCommentsInCurrentLine) {
2336       pushToken(FormatTok);
2337     } else {
2338       CommentsBeforeNextToken.push_back(FormatTok);
2339     }
2340   }
2341 }
2342 
2343 void UnwrappedLineParser::readToken() {
2344   SmallVector<FormatToken *, 1> Comments;
2345   do {
2346     FormatTok = Tokens->getNextToken();
2347     assert(FormatTok);
2348     while (!Line->InPPDirective && FormatTok->Tok.is(tok::hash) &&
2349            (FormatTok->HasUnescapedNewline || FormatTok->IsFirst)) {
2350       distributeComments(Comments, FormatTok);
2351       Comments.clear();
2352       // If there is an unfinished unwrapped line, we flush the preprocessor
2353       // directives only after that unwrapped line was finished later.
2354       bool SwitchToPreprocessorLines = !Line->Tokens.empty();
2355       ScopedLineState BlockState(*this, SwitchToPreprocessorLines);
2356       // Comments stored before the preprocessor directive need to be output
2357       // before the preprocessor directive, at the same level as the
2358       // preprocessor directive, as we consider them to apply to the directive.
2359       flushComments(isOnNewLine(*FormatTok));
2360       parsePPDirective();
2361     }
2362     while (FormatTok->Type == TT_ConflictStart ||
2363            FormatTok->Type == TT_ConflictEnd ||
2364            FormatTok->Type == TT_ConflictAlternative) {
2365       if (FormatTok->Type == TT_ConflictStart) {
2366         conditionalCompilationStart(/*Unreachable=*/false);
2367       } else if (FormatTok->Type == TT_ConflictAlternative) {
2368         conditionalCompilationAlternative();
2369       } else if (FormatTok->Type == TT_ConflictEnd) {
2370         conditionalCompilationEnd();
2371       }
2372       FormatTok = Tokens->getNextToken();
2373       FormatTok->MustBreakBefore = true;
2374     }
2375 
2376     if (!PPStack.empty() && (PPStack.back() == PP_Unreachable) &&
2377         !Line->InPPDirective) {
2378       continue;
2379     }
2380 
2381     if (!FormatTok->Tok.is(tok::comment)) {
2382       distributeComments(Comments, FormatTok);
2383       Comments.clear();
2384       return;
2385     }
2386 
2387     Comments.push_back(FormatTok);
2388   } while (!eof());
2389 
2390   distributeComments(Comments, nullptr);
2391   Comments.clear();
2392 }
2393 
2394 void UnwrappedLineParser::pushToken(FormatToken *Tok) {
2395   Line->Tokens.push_back(UnwrappedLineNode(Tok));
2396   if (MustBreakBeforeNextToken) {
2397     Line->Tokens.back().Tok->MustBreakBefore = true;
2398     MustBreakBeforeNextToken = false;
2399   }
2400 }
2401 
2402 } // end namespace format
2403 } // end namespace clang
2404