]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/Format/UnwrappedLineParser.cpp
Merge llvm, clang, lld, lldb, compiler-rt and libc++ r306956, and update
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / lib / Format / UnwrappedLineParser.cpp
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       else if (Style.Language == FormatStyle::LK_Proto &&
1182                FormatTok->Tok.is(tok::less))
1183         parseBracedList(/*ContinueOnSemicolons=*/false,
1184                         /*ClosingBraceKind=*/tok::greater);
1185       break;
1186     case tok::l_square:
1187       parseSquare();
1188       break;
1189     case tok::kw_new:
1190       parseNew();
1191       break;
1192     default:
1193       nextToken();
1194       break;
1195     }
1196   } while (!eof());
1197 }
1198
1199 bool UnwrappedLineParser::tryToParseLambda() {
1200   if (!Style.isCpp()) {
1201     nextToken();
1202     return false;
1203   }
1204   const FormatToken* Previous = getPreviousToken();
1205   if (Previous &&
1206       (Previous->isOneOf(tok::identifier, tok::kw_operator, tok::kw_new,
1207                          tok::kw_delete) ||
1208        Previous->closesScope() || Previous->isSimpleTypeSpecifier())) {
1209     nextToken();
1210     return false;
1211   }
1212   assert(FormatTok->is(tok::l_square));
1213   FormatToken &LSquare = *FormatTok;
1214   if (!tryToParseLambdaIntroducer())
1215     return false;
1216
1217   while (FormatTok->isNot(tok::l_brace)) {
1218     if (FormatTok->isSimpleTypeSpecifier()) {
1219       nextToken();
1220       continue;
1221     }
1222     switch (FormatTok->Tok.getKind()) {
1223     case tok::l_brace:
1224       break;
1225     case tok::l_paren:
1226       parseParens();
1227       break;
1228     case tok::amp:
1229     case tok::star:
1230     case tok::kw_const:
1231     case tok::comma:
1232     case tok::less:
1233     case tok::greater:
1234     case tok::identifier:
1235     case tok::numeric_constant:
1236     case tok::coloncolon:
1237     case tok::kw_mutable:
1238       nextToken();
1239       break;
1240     case tok::arrow:
1241       FormatTok->Type = TT_LambdaArrow;
1242       nextToken();
1243       break;
1244     default:
1245       return true;
1246     }
1247   }
1248   LSquare.Type = TT_LambdaLSquare;
1249   parseChildBlock();
1250   return true;
1251 }
1252
1253 bool UnwrappedLineParser::tryToParseLambdaIntroducer() {
1254   nextToken();
1255   if (FormatTok->is(tok::equal)) {
1256     nextToken();
1257     if (FormatTok->is(tok::r_square)) {
1258       nextToken();
1259       return true;
1260     }
1261     if (FormatTok->isNot(tok::comma))
1262       return false;
1263     nextToken();
1264   } else if (FormatTok->is(tok::amp)) {
1265     nextToken();
1266     if (FormatTok->is(tok::r_square)) {
1267       nextToken();
1268       return true;
1269     }
1270     if (!FormatTok->isOneOf(tok::comma, tok::identifier)) {
1271       return false;
1272     }
1273     if (FormatTok->is(tok::comma))
1274       nextToken();
1275   } else if (FormatTok->is(tok::r_square)) {
1276     nextToken();
1277     return true;
1278   }
1279   do {
1280     if (FormatTok->is(tok::amp))
1281       nextToken();
1282     if (!FormatTok->isOneOf(tok::identifier, tok::kw_this))
1283       return false;
1284     nextToken();
1285     if (FormatTok->is(tok::ellipsis))
1286       nextToken();
1287     if (FormatTok->is(tok::comma)) {
1288       nextToken();
1289     } else if (FormatTok->is(tok::r_square)) {
1290       nextToken();
1291       return true;
1292     } else {
1293       return false;
1294     }
1295   } while (!eof());
1296   return false;
1297 }
1298
1299 void UnwrappedLineParser::tryToParseJSFunction() {
1300   assert(FormatTok->is(Keywords.kw_function) ||
1301          FormatTok->startsSequence(Keywords.kw_async, Keywords.kw_function));
1302   if (FormatTok->is(Keywords.kw_async))
1303     nextToken();
1304   // Consume "function".
1305   nextToken();
1306
1307   // Consume * (generator function). Treat it like C++'s overloaded operators.
1308   if (FormatTok->is(tok::star)) {
1309     FormatTok->Type = TT_OverloadedOperator;
1310     nextToken();
1311   }
1312
1313   // Consume function name.
1314   if (FormatTok->is(tok::identifier))
1315     nextToken();
1316
1317   if (FormatTok->isNot(tok::l_paren))
1318     return;
1319
1320   // Parse formal parameter list.
1321   parseParens();
1322
1323   if (FormatTok->is(tok::colon)) {
1324     // Parse a type definition.
1325     nextToken();
1326
1327     // Eat the type declaration. For braced inline object types, balance braces,
1328     // otherwise just parse until finding an l_brace for the function body.
1329     if (FormatTok->is(tok::l_brace))
1330       tryToParseBracedList();
1331     else
1332       while (!FormatTok->isOneOf(tok::l_brace, tok::semi) && !eof())
1333         nextToken();
1334   }
1335
1336   if (FormatTok->is(tok::semi))
1337     return;
1338
1339   parseChildBlock();
1340 }
1341
1342 bool UnwrappedLineParser::tryToParseBracedList() {
1343   if (FormatTok->BlockKind == BK_Unknown)
1344     calculateBraceTypes();
1345   assert(FormatTok->BlockKind != BK_Unknown);
1346   if (FormatTok->BlockKind == BK_Block)
1347     return false;
1348   parseBracedList();
1349   return true;
1350 }
1351
1352 bool UnwrappedLineParser::parseBracedList(bool ContinueOnSemicolons,
1353                                           tok::TokenKind ClosingBraceKind) {
1354   bool HasError = false;
1355   nextToken();
1356
1357   // FIXME: Once we have an expression parser in the UnwrappedLineParser,
1358   // replace this by using parseAssigmentExpression() inside.
1359   do {
1360     if (Style.Language == FormatStyle::LK_JavaScript) {
1361       if (FormatTok->is(Keywords.kw_function) ||
1362           FormatTok->startsSequence(Keywords.kw_async, Keywords.kw_function)) {
1363         tryToParseJSFunction();
1364         continue;
1365       }
1366       if (FormatTok->is(TT_JsFatArrow)) {
1367         nextToken();
1368         // Fat arrows can be followed by simple expressions or by child blocks
1369         // in curly braces.
1370         if (FormatTok->is(tok::l_brace)) {
1371           parseChildBlock();
1372           continue;
1373         }
1374       }
1375       if (FormatTok->is(tok::l_brace)) {
1376         // Could be a method inside of a braced list `{a() { return 1; }}`.
1377         if (tryToParseBracedList())
1378           continue;
1379         parseChildBlock();
1380       }
1381     }
1382     if (FormatTok->Tok.getKind() == ClosingBraceKind) {
1383       nextToken();
1384       return !HasError;
1385     }
1386     switch (FormatTok->Tok.getKind()) {
1387     case tok::caret:
1388       nextToken();
1389       if (FormatTok->is(tok::l_brace)) {
1390         parseChildBlock();
1391       }
1392       break;
1393     case tok::l_square:
1394       tryToParseLambda();
1395       break;
1396     case tok::l_paren:
1397       parseParens();
1398       // JavaScript can just have free standing methods and getters/setters in
1399       // object literals. Detect them by a "{" following ")".
1400       if (Style.Language == FormatStyle::LK_JavaScript) {
1401         if (FormatTok->is(tok::l_brace))
1402           parseChildBlock();
1403         break;
1404       }
1405       break;
1406     case tok::l_brace:
1407       // Assume there are no blocks inside a braced init list apart
1408       // from the ones we explicitly parse out (like lambdas).
1409       FormatTok->BlockKind = BK_BracedInit;
1410       parseBracedList();
1411       break;
1412     case tok::semi:
1413       // JavaScript (or more precisely TypeScript) can have semicolons in braced
1414       // lists (in so-called TypeMemberLists). Thus, the semicolon cannot be
1415       // used for error recovery if we have otherwise determined that this is
1416       // a braced list.
1417       if (Style.Language == FormatStyle::LK_JavaScript) {
1418         nextToken();
1419         break;
1420       }
1421       HasError = true;
1422       if (!ContinueOnSemicolons)
1423         return !HasError;
1424       nextToken();
1425       break;
1426     case tok::comma:
1427       nextToken();
1428       break;
1429     default:
1430       nextToken();
1431       break;
1432     }
1433   } while (!eof());
1434   return false;
1435 }
1436
1437 void UnwrappedLineParser::parseParens() {
1438   assert(FormatTok->Tok.is(tok::l_paren) && "'(' expected.");
1439   nextToken();
1440   do {
1441     switch (FormatTok->Tok.getKind()) {
1442     case tok::l_paren:
1443       parseParens();
1444       if (Style.Language == FormatStyle::LK_Java && FormatTok->is(tok::l_brace))
1445         parseChildBlock();
1446       break;
1447     case tok::r_paren:
1448       nextToken();
1449       return;
1450     case tok::r_brace:
1451       // A "}" inside parenthesis is an error if there wasn't a matching "{".
1452       return;
1453     case tok::l_square:
1454       tryToParseLambda();
1455       break;
1456     case tok::l_brace:
1457       if (!tryToParseBracedList())
1458         parseChildBlock();
1459       break;
1460     case tok::at:
1461       nextToken();
1462       if (FormatTok->Tok.is(tok::l_brace))
1463         parseBracedList();
1464       break;
1465     case tok::kw_class:
1466       if (Style.Language == FormatStyle::LK_JavaScript)
1467         parseRecord(/*ParseAsExpr=*/true);
1468       else
1469         nextToken();
1470       break;
1471     case tok::identifier:
1472       if (Style.Language == FormatStyle::LK_JavaScript &&
1473           (FormatTok->is(Keywords.kw_function) ||
1474            FormatTok->startsSequence(Keywords.kw_async, Keywords.kw_function)))
1475         tryToParseJSFunction();
1476       else
1477         nextToken();
1478       break;
1479     default:
1480       nextToken();
1481       break;
1482     }
1483   } while (!eof());
1484 }
1485
1486 void UnwrappedLineParser::parseSquare() {
1487   assert(FormatTok->Tok.is(tok::l_square) && "'[' expected.");
1488   if (tryToParseLambda())
1489     return;
1490   do {
1491     switch (FormatTok->Tok.getKind()) {
1492     case tok::l_paren:
1493       parseParens();
1494       break;
1495     case tok::r_square:
1496       nextToken();
1497       return;
1498     case tok::r_brace:
1499       // A "}" inside parenthesis is an error if there wasn't a matching "{".
1500       return;
1501     case tok::l_square:
1502       parseSquare();
1503       break;
1504     case tok::l_brace: {
1505       if (!tryToParseBracedList())
1506         parseChildBlock();
1507       break;
1508     }
1509     case tok::at:
1510       nextToken();
1511       if (FormatTok->Tok.is(tok::l_brace))
1512         parseBracedList();
1513       break;
1514     default:
1515       nextToken();
1516       break;
1517     }
1518   } while (!eof());
1519 }
1520
1521 void UnwrappedLineParser::parseIfThenElse() {
1522   assert(FormatTok->Tok.is(tok::kw_if) && "'if' expected");
1523   nextToken();
1524   if (FormatTok->Tok.is(tok::kw_constexpr))
1525     nextToken();
1526   if (FormatTok->Tok.is(tok::l_paren))
1527     parseParens();
1528   bool NeedsUnwrappedLine = false;
1529   if (FormatTok->Tok.is(tok::l_brace)) {
1530     CompoundStatementIndenter Indenter(this, Style, Line->Level);
1531     parseBlock(/*MustBeDeclaration=*/false);
1532     if (Style.BraceWrapping.BeforeElse)
1533       addUnwrappedLine();
1534     else
1535       NeedsUnwrappedLine = true;
1536   } else {
1537     addUnwrappedLine();
1538     ++Line->Level;
1539     parseStructuralElement();
1540     --Line->Level;
1541   }
1542   if (FormatTok->Tok.is(tok::kw_else)) {
1543     nextToken();
1544     if (FormatTok->Tok.is(tok::l_brace)) {
1545       CompoundStatementIndenter Indenter(this, Style, Line->Level);
1546       parseBlock(/*MustBeDeclaration=*/false);
1547       addUnwrappedLine();
1548     } else if (FormatTok->Tok.is(tok::kw_if)) {
1549       parseIfThenElse();
1550     } else {
1551       addUnwrappedLine();
1552       ++Line->Level;
1553       parseStructuralElement();
1554       if (FormatTok->is(tok::eof))
1555         addUnwrappedLine();
1556       --Line->Level;
1557     }
1558   } else if (NeedsUnwrappedLine) {
1559     addUnwrappedLine();
1560   }
1561 }
1562
1563 void UnwrappedLineParser::parseTryCatch() {
1564   assert(FormatTok->isOneOf(tok::kw_try, tok::kw___try) && "'try' expected");
1565   nextToken();
1566   bool NeedsUnwrappedLine = false;
1567   if (FormatTok->is(tok::colon)) {
1568     // We are in a function try block, what comes is an initializer list.
1569     nextToken();
1570     while (FormatTok->is(tok::identifier)) {
1571       nextToken();
1572       if (FormatTok->is(tok::l_paren))
1573         parseParens();
1574       if (FormatTok->is(tok::comma))
1575         nextToken();
1576     }
1577   }
1578   // Parse try with resource.
1579   if (Style.Language == FormatStyle::LK_Java && FormatTok->is(tok::l_paren)) {
1580     parseParens();
1581   }
1582   if (FormatTok->is(tok::l_brace)) {
1583     CompoundStatementIndenter Indenter(this, Style, Line->Level);
1584     parseBlock(/*MustBeDeclaration=*/false);
1585     if (Style.BraceWrapping.BeforeCatch) {
1586       addUnwrappedLine();
1587     } else {
1588       NeedsUnwrappedLine = true;
1589     }
1590   } else if (!FormatTok->is(tok::kw_catch)) {
1591     // The C++ standard requires a compound-statement after a try.
1592     // If there's none, we try to assume there's a structuralElement
1593     // and try to continue.
1594     addUnwrappedLine();
1595     ++Line->Level;
1596     parseStructuralElement();
1597     --Line->Level;
1598   }
1599   while (1) {
1600     if (FormatTok->is(tok::at))
1601       nextToken();
1602     if (!(FormatTok->isOneOf(tok::kw_catch, Keywords.kw___except,
1603                              tok::kw___finally) ||
1604           ((Style.Language == FormatStyle::LK_Java ||
1605             Style.Language == FormatStyle::LK_JavaScript) &&
1606            FormatTok->is(Keywords.kw_finally)) ||
1607           (FormatTok->Tok.isObjCAtKeyword(tok::objc_catch) ||
1608            FormatTok->Tok.isObjCAtKeyword(tok::objc_finally))))
1609       break;
1610     nextToken();
1611     while (FormatTok->isNot(tok::l_brace)) {
1612       if (FormatTok->is(tok::l_paren)) {
1613         parseParens();
1614         continue;
1615       }
1616       if (FormatTok->isOneOf(tok::semi, tok::r_brace, tok::eof))
1617         return;
1618       nextToken();
1619     }
1620     NeedsUnwrappedLine = false;
1621     CompoundStatementIndenter Indenter(this, Style, Line->Level);
1622     parseBlock(/*MustBeDeclaration=*/false);
1623     if (Style.BraceWrapping.BeforeCatch)
1624       addUnwrappedLine();
1625     else
1626       NeedsUnwrappedLine = true;
1627   }
1628   if (NeedsUnwrappedLine)
1629     addUnwrappedLine();
1630 }
1631
1632 void UnwrappedLineParser::parseNamespace() {
1633   assert(FormatTok->Tok.is(tok::kw_namespace) && "'namespace' expected");
1634
1635   const FormatToken &InitialToken = *FormatTok;
1636   nextToken();
1637   while (FormatTok->isOneOf(tok::identifier, tok::coloncolon))
1638     nextToken();
1639   if (FormatTok->Tok.is(tok::l_brace)) {
1640     if (ShouldBreakBeforeBrace(Style, InitialToken))
1641       addUnwrappedLine();
1642
1643     bool AddLevel = Style.NamespaceIndentation == FormatStyle::NI_All ||
1644                     (Style.NamespaceIndentation == FormatStyle::NI_Inner &&
1645                      DeclarationScopeStack.size() > 1);
1646     parseBlock(/*MustBeDeclaration=*/true, AddLevel);
1647     // Munch the semicolon after a namespace. This is more common than one would
1648     // think. Puttin the semicolon into its own line is very ugly.
1649     if (FormatTok->Tok.is(tok::semi))
1650       nextToken();
1651     addUnwrappedLine();
1652   }
1653   // FIXME: Add error handling.
1654 }
1655
1656 void UnwrappedLineParser::parseNew() {
1657   assert(FormatTok->is(tok::kw_new) && "'new' expected");
1658   nextToken();
1659   if (Style.Language != FormatStyle::LK_Java)
1660     return;
1661
1662   // In Java, we can parse everything up to the parens, which aren't optional.
1663   do {
1664     // There should not be a ;, { or } before the new's open paren.
1665     if (FormatTok->isOneOf(tok::semi, tok::l_brace, tok::r_brace))
1666       return;
1667
1668     // Consume the parens.
1669     if (FormatTok->is(tok::l_paren)) {
1670       parseParens();
1671
1672       // If there is a class body of an anonymous class, consume that as child.
1673       if (FormatTok->is(tok::l_brace))
1674         parseChildBlock();
1675       return;
1676     }
1677     nextToken();
1678   } while (!eof());
1679 }
1680
1681 void UnwrappedLineParser::parseForOrWhileLoop() {
1682   assert(FormatTok->isOneOf(tok::kw_for, tok::kw_while, TT_ForEachMacro) &&
1683          "'for', 'while' or foreach macro expected");
1684   nextToken();
1685   // JS' for await ( ...
1686   if (Style.Language == FormatStyle::LK_JavaScript &&
1687       FormatTok->is(Keywords.kw_await))
1688     nextToken();
1689   if (FormatTok->Tok.is(tok::l_paren))
1690     parseParens();
1691   if (FormatTok->Tok.is(tok::l_brace)) {
1692     CompoundStatementIndenter Indenter(this, Style, Line->Level);
1693     parseBlock(/*MustBeDeclaration=*/false);
1694     addUnwrappedLine();
1695   } else {
1696     addUnwrappedLine();
1697     ++Line->Level;
1698     parseStructuralElement();
1699     --Line->Level;
1700   }
1701 }
1702
1703 void UnwrappedLineParser::parseDoWhile() {
1704   assert(FormatTok->Tok.is(tok::kw_do) && "'do' expected");
1705   nextToken();
1706   if (FormatTok->Tok.is(tok::l_brace)) {
1707     CompoundStatementIndenter Indenter(this, Style, Line->Level);
1708     parseBlock(/*MustBeDeclaration=*/false);
1709     if (Style.BraceWrapping.IndentBraces)
1710       addUnwrappedLine();
1711   } else {
1712     addUnwrappedLine();
1713     ++Line->Level;
1714     parseStructuralElement();
1715     --Line->Level;
1716   }
1717
1718   // FIXME: Add error handling.
1719   if (!FormatTok->Tok.is(tok::kw_while)) {
1720     addUnwrappedLine();
1721     return;
1722   }
1723
1724   nextToken();
1725   parseStructuralElement();
1726 }
1727
1728 void UnwrappedLineParser::parseLabel() {
1729   nextToken();
1730   unsigned OldLineLevel = Line->Level;
1731   if (Line->Level > 1 || (!Line->InPPDirective && Line->Level > 0))
1732     --Line->Level;
1733   if (CommentsBeforeNextToken.empty() && FormatTok->Tok.is(tok::l_brace)) {
1734     CompoundStatementIndenter Indenter(this, Style, Line->Level);
1735     parseBlock(/*MustBeDeclaration=*/false);
1736     if (FormatTok->Tok.is(tok::kw_break)) {
1737       if (Style.BraceWrapping.AfterControlStatement)
1738         addUnwrappedLine();
1739       parseStructuralElement();
1740     }
1741     addUnwrappedLine();
1742   } else {
1743     if (FormatTok->is(tok::semi))
1744       nextToken();
1745     addUnwrappedLine();
1746   }
1747   Line->Level = OldLineLevel;
1748   if (FormatTok->isNot(tok::l_brace)) {
1749     parseStructuralElement();
1750     addUnwrappedLine();
1751   }
1752 }
1753
1754 void UnwrappedLineParser::parseCaseLabel() {
1755   assert(FormatTok->Tok.is(tok::kw_case) && "'case' expected");
1756   // FIXME: fix handling of complex expressions here.
1757   do {
1758     nextToken();
1759   } while (!eof() && !FormatTok->Tok.is(tok::colon));
1760   parseLabel();
1761 }
1762
1763 void UnwrappedLineParser::parseSwitch() {
1764   assert(FormatTok->Tok.is(tok::kw_switch) && "'switch' expected");
1765   nextToken();
1766   if (FormatTok->Tok.is(tok::l_paren))
1767     parseParens();
1768   if (FormatTok->Tok.is(tok::l_brace)) {
1769     CompoundStatementIndenter Indenter(this, Style, Line->Level);
1770     parseBlock(/*MustBeDeclaration=*/false);
1771     addUnwrappedLine();
1772   } else {
1773     addUnwrappedLine();
1774     ++Line->Level;
1775     parseStructuralElement();
1776     --Line->Level;
1777   }
1778 }
1779
1780 void UnwrappedLineParser::parseAccessSpecifier() {
1781   nextToken();
1782   // Understand Qt's slots.
1783   if (FormatTok->isOneOf(Keywords.kw_slots, Keywords.kw_qslots))
1784     nextToken();
1785   // Otherwise, we don't know what it is, and we'd better keep the next token.
1786   if (FormatTok->Tok.is(tok::colon))
1787     nextToken();
1788   addUnwrappedLine();
1789 }
1790
1791 bool UnwrappedLineParser::parseEnum() {
1792   // Won't be 'enum' for NS_ENUMs.
1793   if (FormatTok->Tok.is(tok::kw_enum))
1794     nextToken();
1795
1796   // In TypeScript, "enum" can also be used as property name, e.g. in interface
1797   // declarations. An "enum" keyword followed by a colon would be a syntax
1798   // error and thus assume it is just an identifier.
1799   if (Style.Language == FormatStyle::LK_JavaScript &&
1800       FormatTok->isOneOf(tok::colon, tok::question))
1801     return false;
1802
1803   // Eat up enum class ...
1804   if (FormatTok->Tok.is(tok::kw_class) || FormatTok->Tok.is(tok::kw_struct))
1805     nextToken();
1806
1807   while (FormatTok->Tok.getIdentifierInfo() ||
1808          FormatTok->isOneOf(tok::colon, tok::coloncolon, tok::less,
1809                             tok::greater, tok::comma, tok::question)) {
1810     nextToken();
1811     // We can have macros or attributes in between 'enum' and the enum name.
1812     if (FormatTok->is(tok::l_paren))
1813       parseParens();
1814     if (FormatTok->is(tok::identifier)) {
1815       nextToken();
1816       // If there are two identifiers in a row, this is likely an elaborate
1817       // return type. In Java, this can be "implements", etc.
1818       if (Style.isCpp() && FormatTok->is(tok::identifier))
1819         return false;
1820     }
1821   }
1822
1823   // Just a declaration or something is wrong.
1824   if (FormatTok->isNot(tok::l_brace))
1825     return true;
1826   FormatTok->BlockKind = BK_Block;
1827
1828   if (Style.Language == FormatStyle::LK_Java) {
1829     // Java enums are different.
1830     parseJavaEnumBody();
1831     return true;
1832   }
1833   if (Style.Language == FormatStyle::LK_Proto) {
1834     parseBlock(/*MustBeDeclaration=*/true);
1835     return true;
1836   }
1837
1838   // Parse enum body.
1839   bool HasError = !parseBracedList(/*ContinueOnSemicolons=*/true);
1840   if (HasError) {
1841     if (FormatTok->is(tok::semi))
1842       nextToken();
1843     addUnwrappedLine();
1844   }
1845   return true;
1846
1847   // There is no addUnwrappedLine() here so that we fall through to parsing a
1848   // structural element afterwards. Thus, in "enum A {} n, m;",
1849   // "} n, m;" will end up in one unwrapped line.
1850 }
1851
1852 void UnwrappedLineParser::parseJavaEnumBody() {
1853   // Determine whether the enum is simple, i.e. does not have a semicolon or
1854   // constants with class bodies. Simple enums can be formatted like braced
1855   // lists, contracted to a single line, etc.
1856   unsigned StoredPosition = Tokens->getPosition();
1857   bool IsSimple = true;
1858   FormatToken *Tok = Tokens->getNextToken();
1859   while (Tok) {
1860     if (Tok->is(tok::r_brace))
1861       break;
1862     if (Tok->isOneOf(tok::l_brace, tok::semi)) {
1863       IsSimple = false;
1864       break;
1865     }
1866     // FIXME: This will also mark enums with braces in the arguments to enum
1867     // constants as "not simple". This is probably fine in practice, though.
1868     Tok = Tokens->getNextToken();
1869   }
1870   FormatTok = Tokens->setPosition(StoredPosition);
1871
1872   if (IsSimple) {
1873     parseBracedList();
1874     addUnwrappedLine();
1875     return;
1876   }
1877
1878   // Parse the body of a more complex enum.
1879   // First add a line for everything up to the "{".
1880   nextToken();
1881   addUnwrappedLine();
1882   ++Line->Level;
1883
1884   // Parse the enum constants.
1885   while (FormatTok) {
1886     if (FormatTok->is(tok::l_brace)) {
1887       // Parse the constant's class body.
1888       parseBlock(/*MustBeDeclaration=*/true, /*AddLevel=*/true,
1889                  /*MunchSemi=*/false);
1890     } else if (FormatTok->is(tok::l_paren)) {
1891       parseParens();
1892     } else if (FormatTok->is(tok::comma)) {
1893       nextToken();
1894       addUnwrappedLine();
1895     } else if (FormatTok->is(tok::semi)) {
1896       nextToken();
1897       addUnwrappedLine();
1898       break;
1899     } else if (FormatTok->is(tok::r_brace)) {
1900       addUnwrappedLine();
1901       break;
1902     } else {
1903       nextToken();
1904     }
1905   }
1906
1907   // Parse the class body after the enum's ";" if any.
1908   parseLevel(/*HasOpeningBrace=*/true);
1909   nextToken();
1910   --Line->Level;
1911   addUnwrappedLine();
1912 }
1913
1914 void UnwrappedLineParser::parseRecord(bool ParseAsExpr) {
1915   const FormatToken &InitialToken = *FormatTok;
1916   nextToken();
1917
1918   // The actual identifier can be a nested name specifier, and in macros
1919   // it is often token-pasted.
1920   while (FormatTok->isOneOf(tok::identifier, tok::coloncolon, tok::hashhash,
1921                             tok::kw___attribute, tok::kw___declspec,
1922                             tok::kw_alignas) ||
1923          ((Style.Language == FormatStyle::LK_Java ||
1924            Style.Language == FormatStyle::LK_JavaScript) &&
1925           FormatTok->isOneOf(tok::period, tok::comma))) {
1926     bool IsNonMacroIdentifier =
1927         FormatTok->is(tok::identifier) &&
1928         FormatTok->TokenText != FormatTok->TokenText.upper();
1929     nextToken();
1930     // We can have macros or attributes in between 'class' and the class name.
1931     if (!IsNonMacroIdentifier && FormatTok->Tok.is(tok::l_paren))
1932       parseParens();
1933   }
1934
1935   // Note that parsing away template declarations here leads to incorrectly
1936   // accepting function declarations as record declarations.
1937   // In general, we cannot solve this problem. Consider:
1938   // class A<int> B() {}
1939   // which can be a function definition or a class definition when B() is a
1940   // macro. If we find enough real-world cases where this is a problem, we
1941   // can parse for the 'template' keyword in the beginning of the statement,
1942   // and thus rule out the record production in case there is no template
1943   // (this would still leave us with an ambiguity between template function
1944   // and class declarations).
1945   if (FormatTok->isOneOf(tok::colon, tok::less)) {
1946     while (!eof()) {
1947       if (FormatTok->is(tok::l_brace)) {
1948         calculateBraceTypes(/*ExpectClassBody=*/true);
1949         if (!tryToParseBracedList())
1950           break;
1951       }
1952       if (FormatTok->Tok.is(tok::semi))
1953         return;
1954       nextToken();
1955     }
1956   }
1957   if (FormatTok->Tok.is(tok::l_brace)) {
1958     if (ParseAsExpr) {
1959       parseChildBlock();
1960     } else {
1961       if (ShouldBreakBeforeBrace(Style, InitialToken))
1962         addUnwrappedLine();
1963
1964       parseBlock(/*MustBeDeclaration=*/true, /*AddLevel=*/true,
1965                  /*MunchSemi=*/false);
1966     }
1967   }
1968   // There is no addUnwrappedLine() here so that we fall through to parsing a
1969   // structural element afterwards. Thus, in "class A {} n, m;",
1970   // "} n, m;" will end up in one unwrapped line.
1971 }
1972
1973 void UnwrappedLineParser::parseObjCProtocolList() {
1974   assert(FormatTok->Tok.is(tok::less) && "'<' expected.");
1975   do
1976     nextToken();
1977   while (!eof() && FormatTok->Tok.isNot(tok::greater));
1978   nextToken(); // Skip '>'.
1979 }
1980
1981 void UnwrappedLineParser::parseObjCUntilAtEnd() {
1982   do {
1983     if (FormatTok->Tok.isObjCAtKeyword(tok::objc_end)) {
1984       nextToken();
1985       addUnwrappedLine();
1986       break;
1987     }
1988     if (FormatTok->is(tok::l_brace)) {
1989       parseBlock(/*MustBeDeclaration=*/false);
1990       // In ObjC interfaces, nothing should be following the "}".
1991       addUnwrappedLine();
1992     } else if (FormatTok->is(tok::r_brace)) {
1993       // Ignore stray "}". parseStructuralElement doesn't consume them.
1994       nextToken();
1995       addUnwrappedLine();
1996     } else {
1997       parseStructuralElement();
1998     }
1999   } while (!eof());
2000 }
2001
2002 void UnwrappedLineParser::parseObjCInterfaceOrImplementation() {
2003   nextToken();
2004   nextToken(); // interface name
2005
2006   // @interface can be followed by either a base class, or a category.
2007   if (FormatTok->Tok.is(tok::colon)) {
2008     nextToken();
2009     nextToken(); // base class name
2010   } else if (FormatTok->Tok.is(tok::l_paren))
2011     // Skip category, if present.
2012     parseParens();
2013
2014   if (FormatTok->Tok.is(tok::less))
2015     parseObjCProtocolList();
2016
2017   if (FormatTok->Tok.is(tok::l_brace)) {
2018     if (Style.BraceWrapping.AfterObjCDeclaration)
2019       addUnwrappedLine();
2020     parseBlock(/*MustBeDeclaration=*/true);
2021   }
2022
2023   // With instance variables, this puts '}' on its own line.  Without instance
2024   // variables, this ends the @interface line.
2025   addUnwrappedLine();
2026
2027   parseObjCUntilAtEnd();
2028 }
2029
2030 void UnwrappedLineParser::parseObjCProtocol() {
2031   nextToken();
2032   nextToken(); // protocol name
2033
2034   if (FormatTok->Tok.is(tok::less))
2035     parseObjCProtocolList();
2036
2037   // Check for protocol declaration.
2038   if (FormatTok->Tok.is(tok::semi)) {
2039     nextToken();
2040     return addUnwrappedLine();
2041   }
2042
2043   addUnwrappedLine();
2044   parseObjCUntilAtEnd();
2045 }
2046
2047 void UnwrappedLineParser::parseJavaScriptEs6ImportExport() {
2048   bool IsImport = FormatTok->is(Keywords.kw_import);
2049   assert(IsImport || FormatTok->is(tok::kw_export));
2050   nextToken();
2051
2052   // Consume the "default" in "export default class/function".
2053   if (FormatTok->is(tok::kw_default))
2054     nextToken();
2055
2056   // Consume "async function", "function" and "default function", so that these
2057   // get parsed as free-standing JS functions, i.e. do not require a trailing
2058   // semicolon.
2059   if (FormatTok->is(Keywords.kw_async))
2060     nextToken();
2061   if (FormatTok->is(Keywords.kw_function)) {
2062     nextToken();
2063     return;
2064   }
2065
2066   // For imports, `export *`, `export {...}`, consume the rest of the line up
2067   // to the terminating `;`. For everything else, just return and continue
2068   // parsing the structural element, i.e. the declaration or expression for
2069   // `export default`.
2070   if (!IsImport && !FormatTok->isOneOf(tok::l_brace, tok::star) &&
2071       !FormatTok->isStringLiteral())
2072     return;
2073
2074   while (!eof()) {
2075     if (FormatTok->is(tok::semi))
2076       return;
2077     if (Line->Tokens.size() == 0) {
2078       // Common issue: Automatic Semicolon Insertion wrapped the line, so the
2079       // import statement should terminate.
2080       return;
2081     }
2082     if (FormatTok->is(tok::l_brace)) {
2083       FormatTok->BlockKind = BK_Block;
2084       parseBracedList();
2085     } else {
2086       nextToken();
2087     }
2088   }
2089 }
2090
2091 LLVM_ATTRIBUTE_UNUSED static void printDebugInfo(const UnwrappedLine &Line,
2092                                                  StringRef Prefix = "") {
2093   llvm::dbgs() << Prefix << "Line(" << Line.Level << ")"
2094                << (Line.InPPDirective ? " MACRO" : "") << ": ";
2095   for (std::list<UnwrappedLineNode>::const_iterator I = Line.Tokens.begin(),
2096                                                     E = Line.Tokens.end();
2097        I != E; ++I) {
2098     llvm::dbgs() << I->Tok->Tok.getName() << "["
2099                  << "T=" << I->Tok->Type
2100                  << ", OC=" << I->Tok->OriginalColumn << "] ";
2101   }
2102   for (std::list<UnwrappedLineNode>::const_iterator I = Line.Tokens.begin(),
2103                                                     E = Line.Tokens.end();
2104        I != E; ++I) {
2105     const UnwrappedLineNode &Node = *I;
2106     for (SmallVectorImpl<UnwrappedLine>::const_iterator
2107              I = Node.Children.begin(),
2108              E = Node.Children.end();
2109          I != E; ++I) {
2110       printDebugInfo(*I, "\nChild: ");
2111     }
2112   }
2113   llvm::dbgs() << "\n";
2114 }
2115
2116 void UnwrappedLineParser::addUnwrappedLine() {
2117   if (Line->Tokens.empty())
2118     return;
2119   DEBUG({
2120     if (CurrentLines == &Lines)
2121       printDebugInfo(*Line);
2122   });
2123   CurrentLines->push_back(std::move(*Line));
2124   Line->Tokens.clear();
2125   Line->MatchingOpeningBlockLineIndex = UnwrappedLine::kInvalidIndex;
2126   if (CurrentLines == &Lines && !PreprocessorDirectives.empty()) {
2127     CurrentLines->append(
2128         std::make_move_iterator(PreprocessorDirectives.begin()),
2129         std::make_move_iterator(PreprocessorDirectives.end()));
2130     PreprocessorDirectives.clear();
2131   }
2132 }
2133
2134 bool UnwrappedLineParser::eof() const { return FormatTok->Tok.is(tok::eof); }
2135
2136 bool UnwrappedLineParser::isOnNewLine(const FormatToken &FormatTok) {
2137   return (Line->InPPDirective || FormatTok.HasUnescapedNewline) &&
2138          FormatTok.NewlinesBefore > 0;
2139 }
2140
2141 // Checks if \p FormatTok is a line comment that continues the line comment
2142 // section on \p Line.
2143 static bool continuesLineCommentSection(const FormatToken &FormatTok,
2144                                         const UnwrappedLine &Line,
2145                                         llvm::Regex &CommentPragmasRegex) {
2146   if (Line.Tokens.empty())
2147     return false;
2148
2149   StringRef IndentContent = FormatTok.TokenText;
2150   if (FormatTok.TokenText.startswith("//") ||
2151       FormatTok.TokenText.startswith("/*"))
2152     IndentContent = FormatTok.TokenText.substr(2);
2153   if (CommentPragmasRegex.match(IndentContent))
2154     return false;
2155
2156   // If Line starts with a line comment, then FormatTok continues the comment
2157   // section if its original column is greater or equal to the original start
2158   // column of the line.
2159   //
2160   // Define the min column token of a line as follows: if a line ends in '{' or
2161   // contains a '{' followed by a line comment, then the min column token is
2162   // that '{'. Otherwise, the min column token of the line is the first token of
2163   // the line.
2164   //
2165   // If Line starts with a token other than a line comment, then FormatTok
2166   // continues the comment section if its original column is greater than the
2167   // original start column of the min column token of the line.
2168   //
2169   // For example, the second line comment continues the first in these cases:
2170   //
2171   // // first line
2172   // // second line
2173   //
2174   // and:
2175   //
2176   // // first line
2177   //  // second line
2178   //
2179   // and:
2180   //
2181   // int i; // first line
2182   //  // second line
2183   //
2184   // and:
2185   //
2186   // do { // first line
2187   //      // second line
2188   //   int i;
2189   // } while (true);
2190   //
2191   // and:
2192   //
2193   // enum {
2194   //   a, // first line
2195   //    // second line
2196   //   b
2197   // };
2198   //
2199   // The second line comment doesn't continue the first in these cases:
2200   //
2201   //   // first line
2202   //  // second line
2203   //
2204   // and:
2205   //
2206   // int i; // first line
2207   // // second line
2208   //
2209   // and:
2210   //
2211   // do { // first line
2212   //   // second line
2213   //   int i;
2214   // } while (true);
2215   //
2216   // and:
2217   //
2218   // enum {
2219   //   a, // first line
2220   //   // second line
2221   // };
2222   const FormatToken *MinColumnToken = Line.Tokens.front().Tok;
2223
2224   // Scan for '{//'. If found, use the column of '{' as a min column for line
2225   // comment section continuation.
2226   const FormatToken *PreviousToken = nullptr;
2227   for (const UnwrappedLineNode &Node : Line.Tokens) {
2228     if (PreviousToken && PreviousToken->is(tok::l_brace) &&
2229         isLineComment(*Node.Tok)) {
2230       MinColumnToken = PreviousToken;
2231       break;
2232     }
2233     PreviousToken = Node.Tok;
2234
2235     // Grab the last newline preceding a token in this unwrapped line.
2236     if (Node.Tok->NewlinesBefore > 0) {
2237       MinColumnToken = Node.Tok;
2238     }
2239   }
2240   if (PreviousToken && PreviousToken->is(tok::l_brace)) {
2241     MinColumnToken = PreviousToken;
2242   }
2243
2244   return continuesLineComment(FormatTok, /*Previous=*/Line.Tokens.back().Tok,
2245                               MinColumnToken);
2246 }
2247
2248 void UnwrappedLineParser::flushComments(bool NewlineBeforeNext) {
2249   bool JustComments = Line->Tokens.empty();
2250   for (SmallVectorImpl<FormatToken *>::const_iterator
2251            I = CommentsBeforeNextToken.begin(),
2252            E = CommentsBeforeNextToken.end();
2253        I != E; ++I) {
2254     // Line comments that belong to the same line comment section are put on the
2255     // same line since later we might want to reflow content between them.
2256     // Additional fine-grained breaking of line comment sections is controlled
2257     // by the class BreakableLineCommentSection in case it is desirable to keep
2258     // several line comment sections in the same unwrapped line.
2259     //
2260     // FIXME: Consider putting separate line comment sections as children to the
2261     // unwrapped line instead.
2262     (*I)->ContinuesLineCommentSection =
2263         continuesLineCommentSection(**I, *Line, CommentPragmasRegex);
2264     if (isOnNewLine(**I) && JustComments && !(*I)->ContinuesLineCommentSection)
2265       addUnwrappedLine();
2266     pushToken(*I);
2267   }
2268   if (NewlineBeforeNext && JustComments)
2269     addUnwrappedLine();
2270   CommentsBeforeNextToken.clear();
2271 }
2272
2273 void UnwrappedLineParser::nextToken() {
2274   if (eof())
2275     return;
2276   flushComments(isOnNewLine(*FormatTok));
2277   pushToken(FormatTok);
2278   if (Style.Language != FormatStyle::LK_JavaScript)
2279     readToken();
2280   else
2281     readTokenWithJavaScriptASI();
2282 }
2283
2284 const FormatToken *UnwrappedLineParser::getPreviousToken() {
2285   // FIXME: This is a dirty way to access the previous token. Find a better
2286   // solution.
2287   if (!Line || Line->Tokens.empty())
2288     return nullptr;
2289   return Line->Tokens.back().Tok;
2290 }
2291
2292 void UnwrappedLineParser::distributeComments(
2293     const SmallVectorImpl<FormatToken *> &Comments,
2294     const FormatToken *NextTok) {
2295   // Whether or not a line comment token continues a line is controlled by
2296   // the method continuesLineCommentSection, with the following caveat:
2297   //
2298   // Define a trail of Comments to be a nonempty proper postfix of Comments such
2299   // that each comment line from the trail is aligned with the next token, if
2300   // the next token exists. If a trail exists, the beginning of the maximal
2301   // trail is marked as a start of a new comment section.
2302   //
2303   // For example in this code:
2304   //
2305   // int a; // line about a
2306   //   // line 1 about b
2307   //   // line 2 about b
2308   //   int b;
2309   //
2310   // the two lines about b form a maximal trail, so there are two sections, the
2311   // first one consisting of the single comment "// line about a" and the
2312   // second one consisting of the next two comments.
2313   if (Comments.empty())
2314     return;
2315   bool ShouldPushCommentsInCurrentLine = true;
2316   bool HasTrailAlignedWithNextToken = false;
2317   unsigned StartOfTrailAlignedWithNextToken = 0;
2318   if (NextTok) {
2319     // We are skipping the first element intentionally.
2320     for (unsigned i = Comments.size() - 1; i > 0; --i) {
2321       if (Comments[i]->OriginalColumn == NextTok->OriginalColumn) {
2322         HasTrailAlignedWithNextToken = true;
2323         StartOfTrailAlignedWithNextToken = i;
2324       }
2325     }
2326   }
2327   for (unsigned i = 0, e = Comments.size(); i < e; ++i) {
2328     FormatToken *FormatTok = Comments[i];
2329     if (HasTrailAlignedWithNextToken &&
2330         i == StartOfTrailAlignedWithNextToken) {
2331       FormatTok->ContinuesLineCommentSection = false;
2332     } else {
2333       FormatTok->ContinuesLineCommentSection =
2334           continuesLineCommentSection(*FormatTok, *Line, CommentPragmasRegex);
2335     }
2336     if (!FormatTok->ContinuesLineCommentSection &&
2337         (isOnNewLine(*FormatTok) || FormatTok->IsFirst)) {
2338       ShouldPushCommentsInCurrentLine = false;
2339     }
2340     if (ShouldPushCommentsInCurrentLine) {
2341       pushToken(FormatTok);
2342     } else {
2343       CommentsBeforeNextToken.push_back(FormatTok);
2344     }
2345   }
2346 }
2347
2348 void UnwrappedLineParser::readToken() {
2349   SmallVector<FormatToken *, 1> Comments;
2350   do {
2351     FormatTok = Tokens->getNextToken();
2352     assert(FormatTok);
2353     while (!Line->InPPDirective && FormatTok->Tok.is(tok::hash) &&
2354            (FormatTok->HasUnescapedNewline || FormatTok->IsFirst)) {
2355       distributeComments(Comments, FormatTok);
2356       Comments.clear();
2357       // If there is an unfinished unwrapped line, we flush the preprocessor
2358       // directives only after that unwrapped line was finished later.
2359       bool SwitchToPreprocessorLines = !Line->Tokens.empty();
2360       ScopedLineState BlockState(*this, SwitchToPreprocessorLines);
2361       // Comments stored before the preprocessor directive need to be output
2362       // before the preprocessor directive, at the same level as the
2363       // preprocessor directive, as we consider them to apply to the directive.
2364       flushComments(isOnNewLine(*FormatTok));
2365       parsePPDirective();
2366     }
2367     while (FormatTok->Type == TT_ConflictStart ||
2368            FormatTok->Type == TT_ConflictEnd ||
2369            FormatTok->Type == TT_ConflictAlternative) {
2370       if (FormatTok->Type == TT_ConflictStart) {
2371         conditionalCompilationStart(/*Unreachable=*/false);
2372       } else if (FormatTok->Type == TT_ConflictAlternative) {
2373         conditionalCompilationAlternative();
2374       } else if (FormatTok->Type == TT_ConflictEnd) {
2375         conditionalCompilationEnd();
2376       }
2377       FormatTok = Tokens->getNextToken();
2378       FormatTok->MustBreakBefore = true;
2379     }
2380
2381     if (!PPStack.empty() && (PPStack.back() == PP_Unreachable) &&
2382         !Line->InPPDirective) {
2383       continue;
2384     }
2385
2386     if (!FormatTok->Tok.is(tok::comment)) {
2387       distributeComments(Comments, FormatTok);
2388       Comments.clear();
2389       return;
2390     }
2391
2392     Comments.push_back(FormatTok);
2393   } while (!eof());
2394
2395   distributeComments(Comments, nullptr);
2396   Comments.clear();
2397 }
2398
2399 void UnwrappedLineParser::pushToken(FormatToken *Tok) {
2400   Line->Tokens.push_back(UnwrappedLineNode(Tok));
2401   if (MustBreakBeforeNextToken) {
2402     Line->Tokens.back().Tok->MustBreakBefore = true;
2403     MustBreakBeforeNextToken = false;
2404   }
2405 }
2406
2407 } // end namespace format
2408 } // end namespace clang