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