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::l_paren))
1520     parseParens();
1521   bool NeedsUnwrappedLine = false;
1522   if (FormatTok->Tok.is(tok::l_brace)) {
1523     CompoundStatementIndenter Indenter(this, Style, Line->Level);
1524     parseBlock(/*MustBeDeclaration=*/false);
1525     if (Style.BraceWrapping.BeforeElse)
1526       addUnwrappedLine();
1527     else
1528       NeedsUnwrappedLine = true;
1529   } else {
1530     addUnwrappedLine();
1531     ++Line->Level;
1532     parseStructuralElement();
1533     --Line->Level;
1534   }
1535   if (FormatTok->Tok.is(tok::kw_else)) {
1536     nextToken();
1537     if (FormatTok->Tok.is(tok::l_brace)) {
1538       CompoundStatementIndenter Indenter(this, Style, Line->Level);
1539       parseBlock(/*MustBeDeclaration=*/false);
1540       addUnwrappedLine();
1541     } else if (FormatTok->Tok.is(tok::kw_if)) {
1542       parseIfThenElse();
1543     } else {
1544       addUnwrappedLine();
1545       ++Line->Level;
1546       parseStructuralElement();
1547       if (FormatTok->is(tok::eof))
1548         addUnwrappedLine();
1549       --Line->Level;
1550     }
1551   } else if (NeedsUnwrappedLine) {
1552     addUnwrappedLine();
1553   }
1554 }
1555 
1556 void UnwrappedLineParser::parseTryCatch() {
1557   assert(FormatTok->isOneOf(tok::kw_try, tok::kw___try) && "'try' expected");
1558   nextToken();
1559   bool NeedsUnwrappedLine = false;
1560   if (FormatTok->is(tok::colon)) {
1561     // We are in a function try block, what comes is an initializer list.
1562     nextToken();
1563     while (FormatTok->is(tok::identifier)) {
1564       nextToken();
1565       if (FormatTok->is(tok::l_paren))
1566         parseParens();
1567       if (FormatTok->is(tok::comma))
1568         nextToken();
1569     }
1570   }
1571   // Parse try with resource.
1572   if (Style.Language == FormatStyle::LK_Java && FormatTok->is(tok::l_paren)) {
1573     parseParens();
1574   }
1575   if (FormatTok->is(tok::l_brace)) {
1576     CompoundStatementIndenter Indenter(this, Style, Line->Level);
1577     parseBlock(/*MustBeDeclaration=*/false);
1578     if (Style.BraceWrapping.BeforeCatch) {
1579       addUnwrappedLine();
1580     } else {
1581       NeedsUnwrappedLine = true;
1582     }
1583   } else if (!FormatTok->is(tok::kw_catch)) {
1584     // The C++ standard requires a compound-statement after a try.
1585     // If there's none, we try to assume there's a structuralElement
1586     // and try to continue.
1587     addUnwrappedLine();
1588     ++Line->Level;
1589     parseStructuralElement();
1590     --Line->Level;
1591   }
1592   while (1) {
1593     if (FormatTok->is(tok::at))
1594       nextToken();
1595     if (!(FormatTok->isOneOf(tok::kw_catch, Keywords.kw___except,
1596                              tok::kw___finally) ||
1597           ((Style.Language == FormatStyle::LK_Java ||
1598             Style.Language == FormatStyle::LK_JavaScript) &&
1599            FormatTok->is(Keywords.kw_finally)) ||
1600           (FormatTok->Tok.isObjCAtKeyword(tok::objc_catch) ||
1601            FormatTok->Tok.isObjCAtKeyword(tok::objc_finally))))
1602       break;
1603     nextToken();
1604     while (FormatTok->isNot(tok::l_brace)) {
1605       if (FormatTok->is(tok::l_paren)) {
1606         parseParens();
1607         continue;
1608       }
1609       if (FormatTok->isOneOf(tok::semi, tok::r_brace, tok::eof))
1610         return;
1611       nextToken();
1612     }
1613     NeedsUnwrappedLine = false;
1614     CompoundStatementIndenter Indenter(this, Style, Line->Level);
1615     parseBlock(/*MustBeDeclaration=*/false);
1616     if (Style.BraceWrapping.BeforeCatch)
1617       addUnwrappedLine();
1618     else
1619       NeedsUnwrappedLine = true;
1620   }
1621   if (NeedsUnwrappedLine)
1622     addUnwrappedLine();
1623 }
1624 
1625 void UnwrappedLineParser::parseNamespace() {
1626   assert(FormatTok->Tok.is(tok::kw_namespace) && "'namespace' expected");
1627 
1628   const FormatToken &InitialToken = *FormatTok;
1629   nextToken();
1630   while (FormatTok->isOneOf(tok::identifier, tok::coloncolon))
1631     nextToken();
1632   if (FormatTok->Tok.is(tok::l_brace)) {
1633     if (ShouldBreakBeforeBrace(Style, InitialToken))
1634       addUnwrappedLine();
1635 
1636     bool AddLevel = Style.NamespaceIndentation == FormatStyle::NI_All ||
1637                     (Style.NamespaceIndentation == FormatStyle::NI_Inner &&
1638                      DeclarationScopeStack.size() > 1);
1639     parseBlock(/*MustBeDeclaration=*/true, AddLevel);
1640     // Munch the semicolon after a namespace. This is more common than one would
1641     // think. Puttin the semicolon into its own line is very ugly.
1642     if (FormatTok->Tok.is(tok::semi))
1643       nextToken();
1644     addUnwrappedLine();
1645   }
1646   // FIXME: Add error handling.
1647 }
1648 
1649 void UnwrappedLineParser::parseNew() {
1650   assert(FormatTok->is(tok::kw_new) && "'new' expected");
1651   nextToken();
1652   if (Style.Language != FormatStyle::LK_Java)
1653     return;
1654 
1655   // In Java, we can parse everything up to the parens, which aren't optional.
1656   do {
1657     // There should not be a ;, { or } before the new's open paren.
1658     if (FormatTok->isOneOf(tok::semi, tok::l_brace, tok::r_brace))
1659       return;
1660 
1661     // Consume the parens.
1662     if (FormatTok->is(tok::l_paren)) {
1663       parseParens();
1664 
1665       // If there is a class body of an anonymous class, consume that as child.
1666       if (FormatTok->is(tok::l_brace))
1667         parseChildBlock();
1668       return;
1669     }
1670     nextToken();
1671   } while (!eof());
1672 }
1673 
1674 void UnwrappedLineParser::parseForOrWhileLoop() {
1675   assert(FormatTok->isOneOf(tok::kw_for, tok::kw_while, TT_ForEachMacro) &&
1676          "'for', 'while' or foreach macro expected");
1677   nextToken();
1678   // JS' for await ( ...
1679   if (Style.Language == FormatStyle::LK_JavaScript &&
1680       FormatTok->is(Keywords.kw_await))
1681     nextToken();
1682   if (FormatTok->Tok.is(tok::l_paren))
1683     parseParens();
1684   if (FormatTok->Tok.is(tok::l_brace)) {
1685     CompoundStatementIndenter Indenter(this, Style, Line->Level);
1686     parseBlock(/*MustBeDeclaration=*/false);
1687     addUnwrappedLine();
1688   } else {
1689     addUnwrappedLine();
1690     ++Line->Level;
1691     parseStructuralElement();
1692     --Line->Level;
1693   }
1694 }
1695 
1696 void UnwrappedLineParser::parseDoWhile() {
1697   assert(FormatTok->Tok.is(tok::kw_do) && "'do' expected");
1698   nextToken();
1699   if (FormatTok->Tok.is(tok::l_brace)) {
1700     CompoundStatementIndenter Indenter(this, Style, Line->Level);
1701     parseBlock(/*MustBeDeclaration=*/false);
1702     if (Style.BraceWrapping.IndentBraces)
1703       addUnwrappedLine();
1704   } else {
1705     addUnwrappedLine();
1706     ++Line->Level;
1707     parseStructuralElement();
1708     --Line->Level;
1709   }
1710 
1711   // FIXME: Add error handling.
1712   if (!FormatTok->Tok.is(tok::kw_while)) {
1713     addUnwrappedLine();
1714     return;
1715   }
1716 
1717   nextToken();
1718   parseStructuralElement();
1719 }
1720 
1721 void UnwrappedLineParser::parseLabel() {
1722   nextToken();
1723   unsigned OldLineLevel = Line->Level;
1724   if (Line->Level > 1 || (!Line->InPPDirective && Line->Level > 0))
1725     --Line->Level;
1726   if (CommentsBeforeNextToken.empty() && FormatTok->Tok.is(tok::l_brace)) {
1727     CompoundStatementIndenter Indenter(this, Style, Line->Level);
1728     parseBlock(/*MustBeDeclaration=*/false);
1729     if (FormatTok->Tok.is(tok::kw_break)) {
1730       if (Style.BraceWrapping.AfterControlStatement)
1731         addUnwrappedLine();
1732       parseStructuralElement();
1733     }
1734     addUnwrappedLine();
1735   } else {
1736     if (FormatTok->is(tok::semi))
1737       nextToken();
1738     addUnwrappedLine();
1739   }
1740   Line->Level = OldLineLevel;
1741   if (FormatTok->isNot(tok::l_brace)) {
1742     parseStructuralElement();
1743     addUnwrappedLine();
1744   }
1745 }
1746 
1747 void UnwrappedLineParser::parseCaseLabel() {
1748   assert(FormatTok->Tok.is(tok::kw_case) && "'case' expected");
1749   // FIXME: fix handling of complex expressions here.
1750   do {
1751     nextToken();
1752   } while (!eof() && !FormatTok->Tok.is(tok::colon));
1753   parseLabel();
1754 }
1755 
1756 void UnwrappedLineParser::parseSwitch() {
1757   assert(FormatTok->Tok.is(tok::kw_switch) && "'switch' expected");
1758   nextToken();
1759   if (FormatTok->Tok.is(tok::l_paren))
1760     parseParens();
1761   if (FormatTok->Tok.is(tok::l_brace)) {
1762     CompoundStatementIndenter Indenter(this, Style, Line->Level);
1763     parseBlock(/*MustBeDeclaration=*/false);
1764     addUnwrappedLine();
1765   } else {
1766     addUnwrappedLine();
1767     ++Line->Level;
1768     parseStructuralElement();
1769     --Line->Level;
1770   }
1771 }
1772 
1773 void UnwrappedLineParser::parseAccessSpecifier() {
1774   nextToken();
1775   // Understand Qt's slots.
1776   if (FormatTok->isOneOf(Keywords.kw_slots, Keywords.kw_qslots))
1777     nextToken();
1778   // Otherwise, we don't know what it is, and we'd better keep the next token.
1779   if (FormatTok->Tok.is(tok::colon))
1780     nextToken();
1781   addUnwrappedLine();
1782 }
1783 
1784 bool UnwrappedLineParser::parseEnum() {
1785   // Won't be 'enum' for NS_ENUMs.
1786   if (FormatTok->Tok.is(tok::kw_enum))
1787     nextToken();
1788 
1789   // In TypeScript, "enum" can also be used as property name, e.g. in interface
1790   // declarations. An "enum" keyword followed by a colon would be a syntax
1791   // error and thus assume it is just an identifier.
1792   if (Style.Language == FormatStyle::LK_JavaScript &&
1793       FormatTok->isOneOf(tok::colon, tok::question))
1794     return false;
1795 
1796   // Eat up enum class ...
1797   if (FormatTok->Tok.is(tok::kw_class) || FormatTok->Tok.is(tok::kw_struct))
1798     nextToken();
1799 
1800   while (FormatTok->Tok.getIdentifierInfo() ||
1801          FormatTok->isOneOf(tok::colon, tok::coloncolon, tok::less,
1802                             tok::greater, tok::comma, tok::question)) {
1803     nextToken();
1804     // We can have macros or attributes in between 'enum' and the enum name.
1805     if (FormatTok->is(tok::l_paren))
1806       parseParens();
1807     if (FormatTok->is(tok::identifier)) {
1808       nextToken();
1809       // If there are two identifiers in a row, this is likely an elaborate
1810       // return type. In Java, this can be "implements", etc.
1811       if (Style.isCpp() && FormatTok->is(tok::identifier))
1812         return false;
1813     }
1814   }
1815 
1816   // Just a declaration or something is wrong.
1817   if (FormatTok->isNot(tok::l_brace))
1818     return true;
1819   FormatTok->BlockKind = BK_Block;
1820 
1821   if (Style.Language == FormatStyle::LK_Java) {
1822     // Java enums are different.
1823     parseJavaEnumBody();
1824     return true;
1825   }
1826   if (Style.Language == FormatStyle::LK_Proto) {
1827     parseBlock(/*MustBeDeclaration=*/true);
1828     return true;
1829   }
1830 
1831   // Parse enum body.
1832   bool HasError = !parseBracedList(/*ContinueOnSemicolons=*/true);
1833   if (HasError) {
1834     if (FormatTok->is(tok::semi))
1835       nextToken();
1836     addUnwrappedLine();
1837   }
1838   return true;
1839 
1840   // There is no addUnwrappedLine() here so that we fall through to parsing a
1841   // structural element afterwards. Thus, in "enum A {} n, m;",
1842   // "} n, m;" will end up in one unwrapped line.
1843 }
1844 
1845 void UnwrappedLineParser::parseJavaEnumBody() {
1846   // Determine whether the enum is simple, i.e. does not have a semicolon or
1847   // constants with class bodies. Simple enums can be formatted like braced
1848   // lists, contracted to a single line, etc.
1849   unsigned StoredPosition = Tokens->getPosition();
1850   bool IsSimple = true;
1851   FormatToken *Tok = Tokens->getNextToken();
1852   while (Tok) {
1853     if (Tok->is(tok::r_brace))
1854       break;
1855     if (Tok->isOneOf(tok::l_brace, tok::semi)) {
1856       IsSimple = false;
1857       break;
1858     }
1859     // FIXME: This will also mark enums with braces in the arguments to enum
1860     // constants as "not simple". This is probably fine in practice, though.
1861     Tok = Tokens->getNextToken();
1862   }
1863   FormatTok = Tokens->setPosition(StoredPosition);
1864 
1865   if (IsSimple) {
1866     parseBracedList();
1867     addUnwrappedLine();
1868     return;
1869   }
1870 
1871   // Parse the body of a more complex enum.
1872   // First add a line for everything up to the "{".
1873   nextToken();
1874   addUnwrappedLine();
1875   ++Line->Level;
1876 
1877   // Parse the enum constants.
1878   while (FormatTok) {
1879     if (FormatTok->is(tok::l_brace)) {
1880       // Parse the constant's class body.
1881       parseBlock(/*MustBeDeclaration=*/true, /*AddLevel=*/true,
1882                  /*MunchSemi=*/false);
1883     } else if (FormatTok->is(tok::l_paren)) {
1884       parseParens();
1885     } else if (FormatTok->is(tok::comma)) {
1886       nextToken();
1887       addUnwrappedLine();
1888     } else if (FormatTok->is(tok::semi)) {
1889       nextToken();
1890       addUnwrappedLine();
1891       break;
1892     } else if (FormatTok->is(tok::r_brace)) {
1893       addUnwrappedLine();
1894       break;
1895     } else {
1896       nextToken();
1897     }
1898   }
1899 
1900   // Parse the class body after the enum's ";" if any.
1901   parseLevel(/*HasOpeningBrace=*/true);
1902   nextToken();
1903   --Line->Level;
1904   addUnwrappedLine();
1905 }
1906 
1907 void UnwrappedLineParser::parseRecord(bool ParseAsExpr) {
1908   const FormatToken &InitialToken = *FormatTok;
1909   nextToken();
1910 
1911   // The actual identifier can be a nested name specifier, and in macros
1912   // it is often token-pasted.
1913   while (FormatTok->isOneOf(tok::identifier, tok::coloncolon, tok::hashhash,
1914                             tok::kw___attribute, tok::kw___declspec,
1915                             tok::kw_alignas) ||
1916          ((Style.Language == FormatStyle::LK_Java ||
1917            Style.Language == FormatStyle::LK_JavaScript) &&
1918           FormatTok->isOneOf(tok::period, tok::comma))) {
1919     bool IsNonMacroIdentifier =
1920         FormatTok->is(tok::identifier) &&
1921         FormatTok->TokenText != FormatTok->TokenText.upper();
1922     nextToken();
1923     // We can have macros or attributes in between 'class' and the class name.
1924     if (!IsNonMacroIdentifier && FormatTok->Tok.is(tok::l_paren))
1925       parseParens();
1926   }
1927 
1928   // Note that parsing away template declarations here leads to incorrectly
1929   // accepting function declarations as record declarations.
1930   // In general, we cannot solve this problem. Consider:
1931   // class A<int> B() {}
1932   // which can be a function definition or a class definition when B() is a
1933   // macro. If we find enough real-world cases where this is a problem, we
1934   // can parse for the 'template' keyword in the beginning of the statement,
1935   // and thus rule out the record production in case there is no template
1936   // (this would still leave us with an ambiguity between template function
1937   // and class declarations).
1938   if (FormatTok->isOneOf(tok::colon, tok::less)) {
1939     while (!eof()) {
1940       if (FormatTok->is(tok::l_brace)) {
1941         calculateBraceTypes(/*ExpectClassBody=*/true);
1942         if (!tryToParseBracedList())
1943           break;
1944       }
1945       if (FormatTok->Tok.is(tok::semi))
1946         return;
1947       nextToken();
1948     }
1949   }
1950   if (FormatTok->Tok.is(tok::l_brace)) {
1951     if (ParseAsExpr) {
1952       parseChildBlock();
1953     } else {
1954       if (ShouldBreakBeforeBrace(Style, InitialToken))
1955         addUnwrappedLine();
1956 
1957       parseBlock(/*MustBeDeclaration=*/true, /*AddLevel=*/true,
1958                  /*MunchSemi=*/false);
1959     }
1960   }
1961   // There is no addUnwrappedLine() here so that we fall through to parsing a
1962   // structural element afterwards. Thus, in "class A {} n, m;",
1963   // "} n, m;" will end up in one unwrapped line.
1964 }
1965 
1966 void UnwrappedLineParser::parseObjCProtocolList() {
1967   assert(FormatTok->Tok.is(tok::less) && "'<' expected.");
1968   do
1969     nextToken();
1970   while (!eof() && FormatTok->Tok.isNot(tok::greater));
1971   nextToken(); // Skip '>'.
1972 }
1973 
1974 void UnwrappedLineParser::parseObjCUntilAtEnd() {
1975   do {
1976     if (FormatTok->Tok.isObjCAtKeyword(tok::objc_end)) {
1977       nextToken();
1978       addUnwrappedLine();
1979       break;
1980     }
1981     if (FormatTok->is(tok::l_brace)) {
1982       parseBlock(/*MustBeDeclaration=*/false);
1983       // In ObjC interfaces, nothing should be following the "}".
1984       addUnwrappedLine();
1985     } else if (FormatTok->is(tok::r_brace)) {
1986       // Ignore stray "}". parseStructuralElement doesn't consume them.
1987       nextToken();
1988       addUnwrappedLine();
1989     } else {
1990       parseStructuralElement();
1991     }
1992   } while (!eof());
1993 }
1994 
1995 void UnwrappedLineParser::parseObjCInterfaceOrImplementation() {
1996   nextToken();
1997   nextToken(); // interface name
1998 
1999   // @interface can be followed by either a base class, or a category.
2000   if (FormatTok->Tok.is(tok::colon)) {
2001     nextToken();
2002     nextToken(); // base class name
2003   } else if (FormatTok->Tok.is(tok::l_paren))
2004     // Skip category, if present.
2005     parseParens();
2006 
2007   if (FormatTok->Tok.is(tok::less))
2008     parseObjCProtocolList();
2009 
2010   if (FormatTok->Tok.is(tok::l_brace)) {
2011     if (Style.BraceWrapping.AfterObjCDeclaration)
2012       addUnwrappedLine();
2013     parseBlock(/*MustBeDeclaration=*/true);
2014   }
2015 
2016   // With instance variables, this puts '}' on its own line.  Without instance
2017   // variables, this ends the @interface line.
2018   addUnwrappedLine();
2019 
2020   parseObjCUntilAtEnd();
2021 }
2022 
2023 void UnwrappedLineParser::parseObjCProtocol() {
2024   nextToken();
2025   nextToken(); // protocol name
2026 
2027   if (FormatTok->Tok.is(tok::less))
2028     parseObjCProtocolList();
2029 
2030   // Check for protocol declaration.
2031   if (FormatTok->Tok.is(tok::semi)) {
2032     nextToken();
2033     return addUnwrappedLine();
2034   }
2035 
2036   addUnwrappedLine();
2037   parseObjCUntilAtEnd();
2038 }
2039 
2040 void UnwrappedLineParser::parseJavaScriptEs6ImportExport() {
2041   bool IsImport = FormatTok->is(Keywords.kw_import);
2042   assert(IsImport || FormatTok->is(tok::kw_export));
2043   nextToken();
2044 
2045   // Consume the "default" in "export default class/function".
2046   if (FormatTok->is(tok::kw_default))
2047     nextToken();
2048 
2049   // Consume "async function", "function" and "default function", so that these
2050   // get parsed as free-standing JS functions, i.e. do not require a trailing
2051   // semicolon.
2052   if (FormatTok->is(Keywords.kw_async))
2053     nextToken();
2054   if (FormatTok->is(Keywords.kw_function)) {
2055     nextToken();
2056     return;
2057   }
2058 
2059   // For imports, `export *`, `export {...}`, consume the rest of the line up
2060   // to the terminating `;`. For everything else, just return and continue
2061   // parsing the structural element, i.e. the declaration or expression for
2062   // `export default`.
2063   if (!IsImport && !FormatTok->isOneOf(tok::l_brace, tok::star) &&
2064       !FormatTok->isStringLiteral())
2065     return;
2066 
2067   while (!eof()) {
2068     if (FormatTok->is(tok::semi))
2069       return;
2070     if (Line->Tokens.size() == 0) {
2071       // Common issue: Automatic Semicolon Insertion wrapped the line, so the
2072       // import statement should terminate.
2073       return;
2074     }
2075     if (FormatTok->is(tok::l_brace)) {
2076       FormatTok->BlockKind = BK_Block;
2077       parseBracedList();
2078     } else {
2079       nextToken();
2080     }
2081   }
2082 }
2083 
2084 LLVM_ATTRIBUTE_UNUSED static void printDebugInfo(const UnwrappedLine &Line,
2085                                                  StringRef Prefix = "") {
2086   llvm::dbgs() << Prefix << "Line(" << Line.Level << ")"
2087                << (Line.InPPDirective ? " MACRO" : "") << ": ";
2088   for (std::list<UnwrappedLineNode>::const_iterator I = Line.Tokens.begin(),
2089                                                     E = Line.Tokens.end();
2090        I != E; ++I) {
2091     llvm::dbgs() << I->Tok->Tok.getName() << "["
2092                  << "T=" << I->Tok->Type
2093                  << ", OC=" << I->Tok->OriginalColumn << "] ";
2094   }
2095   for (std::list<UnwrappedLineNode>::const_iterator I = Line.Tokens.begin(),
2096                                                     E = Line.Tokens.end();
2097        I != E; ++I) {
2098     const UnwrappedLineNode &Node = *I;
2099     for (SmallVectorImpl<UnwrappedLine>::const_iterator
2100              I = Node.Children.begin(),
2101              E = Node.Children.end();
2102          I != E; ++I) {
2103       printDebugInfo(*I, "\nChild: ");
2104     }
2105   }
2106   llvm::dbgs() << "\n";
2107 }
2108 
2109 void UnwrappedLineParser::addUnwrappedLine() {
2110   if (Line->Tokens.empty())
2111     return;
2112   DEBUG({
2113     if (CurrentLines == &Lines)
2114       printDebugInfo(*Line);
2115   });
2116   CurrentLines->push_back(std::move(*Line));
2117   Line->Tokens.clear();
2118   Line->MatchingOpeningBlockLineIndex = UnwrappedLine::kInvalidIndex;
2119   if (CurrentLines == &Lines && !PreprocessorDirectives.empty()) {
2120     CurrentLines->append(
2121         std::make_move_iterator(PreprocessorDirectives.begin()),
2122         std::make_move_iterator(PreprocessorDirectives.end()));
2123     PreprocessorDirectives.clear();
2124   }
2125 }
2126 
2127 bool UnwrappedLineParser::eof() const { return FormatTok->Tok.is(tok::eof); }
2128 
2129 bool UnwrappedLineParser::isOnNewLine(const FormatToken &FormatTok) {
2130   return (Line->InPPDirective || FormatTok.HasUnescapedNewline) &&
2131          FormatTok.NewlinesBefore > 0;
2132 }
2133 
2134 // Checks if \p FormatTok is a line comment that continues the line comment
2135 // section on \p Line.
2136 static bool continuesLineCommentSection(const FormatToken &FormatTok,
2137                                         const UnwrappedLine &Line,
2138                                         llvm::Regex &CommentPragmasRegex) {
2139   if (Line.Tokens.empty())
2140     return false;
2141 
2142   StringRef IndentContent = FormatTok.TokenText;
2143   if (FormatTok.TokenText.startswith("//") ||
2144       FormatTok.TokenText.startswith("/*"))
2145     IndentContent = FormatTok.TokenText.substr(2);
2146   if (CommentPragmasRegex.match(IndentContent))
2147     return false;
2148 
2149   // If Line starts with a line comment, then FormatTok continues the comment
2150   // section if its original column is greater or equal to the original start
2151   // column of the line.
2152   //
2153   // Define the min column token of a line as follows: if a line ends in '{' or
2154   // contains a '{' followed by a line comment, then the min column token is
2155   // that '{'. Otherwise, the min column token of the line is the first token of
2156   // the line.
2157   //
2158   // If Line starts with a token other than a line comment, then FormatTok
2159   // continues the comment section if its original column is greater than the
2160   // original start column of the min column token of the line.
2161   //
2162   // For example, the second line comment continues the first in these cases:
2163   //
2164   // // first line
2165   // // second line
2166   //
2167   // and:
2168   //
2169   // // first line
2170   //  // second line
2171   //
2172   // and:
2173   //
2174   // int i; // first line
2175   //  // second line
2176   //
2177   // and:
2178   //
2179   // do { // first line
2180   //      // second line
2181   //   int i;
2182   // } while (true);
2183   //
2184   // and:
2185   //
2186   // enum {
2187   //   a, // first line
2188   //    // second line
2189   //   b
2190   // };
2191   //
2192   // The second line comment doesn't continue the first in these cases:
2193   //
2194   //   // first line
2195   //  // second line
2196   //
2197   // and:
2198   //
2199   // int i; // first line
2200   // // second line
2201   //
2202   // and:
2203   //
2204   // do { // first line
2205   //   // second line
2206   //   int i;
2207   // } while (true);
2208   //
2209   // and:
2210   //
2211   // enum {
2212   //   a, // first line
2213   //   // second line
2214   // };
2215   const FormatToken *MinColumnToken = Line.Tokens.front().Tok;
2216 
2217   // Scan for '{//'. If found, use the column of '{' as a min column for line
2218   // comment section continuation.
2219   const FormatToken *PreviousToken = nullptr;
2220   for (const UnwrappedLineNode &Node : Line.Tokens) {
2221     if (PreviousToken && PreviousToken->is(tok::l_brace) &&
2222         isLineComment(*Node.Tok)) {
2223       MinColumnToken = PreviousToken;
2224       break;
2225     }
2226     PreviousToken = Node.Tok;
2227 
2228     // Grab the last newline preceding a token in this unwrapped line.
2229     if (Node.Tok->NewlinesBefore > 0) {
2230       MinColumnToken = Node.Tok;
2231     }
2232   }
2233   if (PreviousToken && PreviousToken->is(tok::l_brace)) {
2234     MinColumnToken = PreviousToken;
2235   }
2236 
2237   return continuesLineComment(FormatTok, /*Previous=*/Line.Tokens.back().Tok,
2238                               MinColumnToken);
2239 }
2240 
2241 void UnwrappedLineParser::flushComments(bool NewlineBeforeNext) {
2242   bool JustComments = Line->Tokens.empty();
2243   for (SmallVectorImpl<FormatToken *>::const_iterator
2244            I = CommentsBeforeNextToken.begin(),
2245            E = CommentsBeforeNextToken.end();
2246        I != E; ++I) {
2247     // Line comments that belong to the same line comment section are put on the
2248     // same line since later we might want to reflow content between them.
2249     // Additional fine-grained breaking of line comment sections is controlled
2250     // by the class BreakableLineCommentSection in case it is desirable to keep
2251     // several line comment sections in the same unwrapped line.
2252     //
2253     // FIXME: Consider putting separate line comment sections as children to the
2254     // unwrapped line instead.
2255     (*I)->ContinuesLineCommentSection =
2256         continuesLineCommentSection(**I, *Line, CommentPragmasRegex);
2257     if (isOnNewLine(**I) && JustComments && !(*I)->ContinuesLineCommentSection)
2258       addUnwrappedLine();
2259     pushToken(*I);
2260   }
2261   if (NewlineBeforeNext && JustComments)
2262     addUnwrappedLine();
2263   CommentsBeforeNextToken.clear();
2264 }
2265 
2266 void UnwrappedLineParser::nextToken() {
2267   if (eof())
2268     return;
2269   flushComments(isOnNewLine(*FormatTok));
2270   pushToken(FormatTok);
2271   if (Style.Language != FormatStyle::LK_JavaScript)
2272     readToken();
2273   else
2274     readTokenWithJavaScriptASI();
2275 }
2276 
2277 const FormatToken *UnwrappedLineParser::getPreviousToken() {
2278   // FIXME: This is a dirty way to access the previous token. Find a better
2279   // solution.
2280   if (!Line || Line->Tokens.empty())
2281     return nullptr;
2282   return Line->Tokens.back().Tok;
2283 }
2284 
2285 void UnwrappedLineParser::distributeComments(
2286     const SmallVectorImpl<FormatToken *> &Comments,
2287     const FormatToken *NextTok) {
2288   // Whether or not a line comment token continues a line is controlled by
2289   // the method continuesLineCommentSection, with the following caveat:
2290   //
2291   // Define a trail of Comments to be a nonempty proper postfix of Comments such
2292   // that each comment line from the trail is aligned with the next token, if
2293   // the next token exists. If a trail exists, the beginning of the maximal
2294   // trail is marked as a start of a new comment section.
2295   //
2296   // For example in this code:
2297   //
2298   // int a; // line about a
2299   //   // line 1 about b
2300   //   // line 2 about b
2301   //   int b;
2302   //
2303   // the two lines about b form a maximal trail, so there are two sections, the
2304   // first one consisting of the single comment "// line about a" and the
2305   // second one consisting of the next two comments.
2306   if (Comments.empty())
2307     return;
2308   bool ShouldPushCommentsInCurrentLine = true;
2309   bool HasTrailAlignedWithNextToken = false;
2310   unsigned StartOfTrailAlignedWithNextToken = 0;
2311   if (NextTok) {
2312     // We are skipping the first element intentionally.
2313     for (unsigned i = Comments.size() - 1; i > 0; --i) {
2314       if (Comments[i]->OriginalColumn == NextTok->OriginalColumn) {
2315         HasTrailAlignedWithNextToken = true;
2316         StartOfTrailAlignedWithNextToken = i;
2317       }
2318     }
2319   }
2320   for (unsigned i = 0, e = Comments.size(); i < e; ++i) {
2321     FormatToken *FormatTok = Comments[i];
2322     if (HasTrailAlignedWithNextToken &&
2323         i == StartOfTrailAlignedWithNextToken) {
2324       FormatTok->ContinuesLineCommentSection = false;
2325     } else {
2326       FormatTok->ContinuesLineCommentSection =
2327           continuesLineCommentSection(*FormatTok, *Line, CommentPragmasRegex);
2328     }
2329     if (!FormatTok->ContinuesLineCommentSection &&
2330         (isOnNewLine(*FormatTok) || FormatTok->IsFirst)) {
2331       ShouldPushCommentsInCurrentLine = false;
2332     }
2333     if (ShouldPushCommentsInCurrentLine) {
2334       pushToken(FormatTok);
2335     } else {
2336       CommentsBeforeNextToken.push_back(FormatTok);
2337     }
2338   }
2339 }
2340 
2341 void UnwrappedLineParser::readToken() {
2342   SmallVector<FormatToken *, 1> Comments;
2343   do {
2344     FormatTok = Tokens->getNextToken();
2345     assert(FormatTok);
2346     while (!Line->InPPDirective && FormatTok->Tok.is(tok::hash) &&
2347            (FormatTok->HasUnescapedNewline || FormatTok->IsFirst)) {
2348       distributeComments(Comments, FormatTok);
2349       Comments.clear();
2350       // If there is an unfinished unwrapped line, we flush the preprocessor
2351       // directives only after that unwrapped line was finished later.
2352       bool SwitchToPreprocessorLines = !Line->Tokens.empty();
2353       ScopedLineState BlockState(*this, SwitchToPreprocessorLines);
2354       // Comments stored before the preprocessor directive need to be output
2355       // before the preprocessor directive, at the same level as the
2356       // preprocessor directive, as we consider them to apply to the directive.
2357       flushComments(isOnNewLine(*FormatTok));
2358       parsePPDirective();
2359     }
2360     while (FormatTok->Type == TT_ConflictStart ||
2361            FormatTok->Type == TT_ConflictEnd ||
2362            FormatTok->Type == TT_ConflictAlternative) {
2363       if (FormatTok->Type == TT_ConflictStart) {
2364         conditionalCompilationStart(/*Unreachable=*/false);
2365       } else if (FormatTok->Type == TT_ConflictAlternative) {
2366         conditionalCompilationAlternative();
2367       } else if (FormatTok->Type == TT_ConflictEnd) {
2368         conditionalCompilationEnd();
2369       }
2370       FormatTok = Tokens->getNextToken();
2371       FormatTok->MustBreakBefore = true;
2372     }
2373 
2374     if (!PPStack.empty() && (PPStack.back() == PP_Unreachable) &&
2375         !Line->InPPDirective) {
2376       continue;
2377     }
2378 
2379     if (!FormatTok->Tok.is(tok::comment)) {
2380       distributeComments(Comments, FormatTok);
2381       Comments.clear();
2382       return;
2383     }
2384 
2385     Comments.push_back(FormatTok);
2386   } while (!eof());
2387 
2388   distributeComments(Comments, nullptr);
2389   Comments.clear();
2390 }
2391 
2392 void UnwrappedLineParser::pushToken(FormatToken *Tok) {
2393   Line->Tokens.push_back(UnwrappedLineNode(Tok));
2394   if (MustBreakBeforeNextToken) {
2395     Line->Tokens.back().Tok->MustBreakBefore = true;
2396     MustBreakBeforeNextToken = false;
2397   }
2398 }
2399 
2400 } // end namespace format
2401 } // end namespace clang
2402