1 //===--- UnwrappedLineParser.cpp - Format C++ code ------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 /// \brief This file contains the implementation of the UnwrappedLineParser,
12 /// which turns a stream of tokens into UnwrappedLines.
14 //===----------------------------------------------------------------------===//
16 #include "UnwrappedLineParser.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/Support/Debug.h"
19 #include "llvm/Support/raw_ostream.h"
21 #define DEBUG_TYPE "format-parser"
26 class FormatTokenSource {
28 virtual ~FormatTokenSource() {}
29 virtual FormatToken *getNextToken() = 0;
31 virtual unsigned getPosition() = 0;
32 virtual FormatToken *setPosition(unsigned Position) = 0;
37 class ScopedDeclarationState {
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);
45 ~ScopedDeclarationState() {
48 Line.MustBeDeclaration = Stack.back();
50 Line.MustBeDeclaration = true;
55 std::vector<bool> &Stack;
58 static bool isLineComment(const FormatToken &FormatTok) {
59 return FormatTok.is(tok::comment) &&
60 FormatTok.TokenText.startswith("//");
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)
71 unsigned MinContinueColumn =
72 MinColumnToken->OriginalColumn + (isLineComment(*MinColumnToken) ? 0 : 1);
73 return isLineComment(FormatTok) && FormatTok.NewlinesBefore == 1 &&
74 isLineComment(*Previous) &&
75 FormatTok.OriginalColumn >= MinContinueColumn;
78 class ScopedMacroState : public FormatTokenSource {
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) {
87 Line.InPPDirective = true;
90 ~ScopedMacroState() override {
91 TokenSource = PreviousTokenSource;
93 Line.InPPDirective = false;
94 Line.Level = PreviousLineLevel;
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.
101 PreviousToken = Token;
102 Token = PreviousTokenSource->getNextToken();
108 unsigned getPosition() override { return PreviousTokenSource->getPosition(); }
110 FormatToken *setPosition(unsigned Position) override {
111 PreviousToken = nullptr;
112 Token = PreviousTokenSource->setPosition(Position);
118 return Token && Token->HasUnescapedNewline &&
119 !continuesLineComment(*Token, PreviousToken,
120 /*MinColumnToken=*/PreviousToken);
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;
135 FormatTokenSource *&TokenSource;
136 FormatToken *&ResetToken;
137 unsigned PreviousLineLevel;
138 FormatTokenSource *PreviousTokenSource;
141 FormatToken *PreviousToken;
144 } // end anonymous namespace
146 class ScopedLineState {
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;
162 if (!Parser.Line->Tokens.empty()) {
163 Parser.addUnwrappedLine();
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;
173 UnwrappedLineParser &Parser;
175 std::unique_ptr<UnwrappedLine> PreBlockLine;
176 SmallVectorImpl<UnwrappedLine> *OriginalLines;
179 class CompoundStatementIndenter {
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)
189 ~CompoundStatementIndenter() { LineLevel = OldLineLevel; }
193 unsigned OldLineLevel;
198 class IndexedTokenSource : public FormatTokenSource {
200 IndexedTokenSource(ArrayRef<FormatToken *> Tokens)
201 : Tokens(Tokens), Position(-1) {}
203 FormatToken *getNextToken() override {
205 return Tokens[Position];
208 unsigned getPosition() override {
209 assert(Position >= 0);
213 FormatToken *setPosition(unsigned P) override {
215 return Tokens[Position];
218 void reset() { Position = -1; }
221 ArrayRef<FormatToken *> Tokens;
225 } // end anonymous namespace
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) {}
236 void UnwrappedLineParser::reset() {
238 Line.reset(new UnwrappedLine);
239 CommentsBeforeNextToken.clear();
241 MustBreakBeforeNextToken = false;
242 PreprocessorDirectives.clear();
243 CurrentLines = &Lines;
244 DeclarationScopeStack.clear();
248 void UnwrappedLineParser::parse() {
249 IndexedTokenSource TokenSource(AllTokens);
251 DEBUG(llvm::dbgs() << "----\n");
253 Tokens = &TokenSource;
258 // Create line with eof token.
259 pushToken(FormatTok);
262 for (SmallVectorImpl<UnwrappedLine>::iterator I = Lines.begin(),
265 Callback.consumeUnwrappedLine(*I);
267 Callback.finishRun();
269 while (!PPLevelBranchIndex.empty() &&
270 PPLevelBranchIndex.back() + 1 >= PPLevelBranchCount.back()) {
271 PPLevelBranchIndex.resize(PPLevelBranchIndex.size() - 1);
272 PPLevelBranchCount.resize(PPLevelBranchCount.size() - 1);
274 if (!PPLevelBranchIndex.empty()) {
275 ++PPLevelBranchIndex.back();
276 assert(PPLevelBranchIndex.size() == PPLevelBranchCount.size());
277 assert(PPLevelBranchIndex.back() <= PPLevelBranchCount.back());
279 } while (!PPLevelBranchIndex.empty());
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,
289 parseLevel(/*HasOpeningBrace=*/false);
290 // Make sure to format the remaining tokens.
295 void UnwrappedLineParser::parseLevel(bool HasOpeningBrace) {
296 bool SwitchLabelEncountered = false;
298 tok::TokenKind kind = FormatTok->Tok.getKind();
299 if (FormatTok->Type == TT_MacroBlockBegin) {
301 } else if (FormatTok->Type == TT_MacroBlockEnd) {
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())
315 parseBlock(/*MustBeDeclaration=*/false);
324 case tok::kw_default:
326 if (!SwitchLabelEncountered &&
327 (Style.IndentCaseLabels || (Line->InPPDirective && Line->Level == 1)))
329 SwitchLabelEncountered = true;
330 parseStructuralElement();
333 parseStructuralElement();
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
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));
353 // Get next non-comment token.
354 FormatToken *NextTok;
355 unsigned ReadTokens = 0;
357 NextTok = Tokens->getNextToken();
359 } while (NextTok->is(tok::comment));
361 switch (Tok->Tok.getKind()) {
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
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;
376 Tok->BlockKind = BK_Unknown;
378 LBraceStack.push_back(Tok);
381 if (LBraceStack.empty())
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);
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;
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.
402 (Style.Language == FormatStyle::LK_JavaScript &&
403 NextTok->isOneOf(Keywords.kw_of, Keywords.kw_in,
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);
415 if (ProbablyBracedList) {
416 Tok->BlockKind = BK_BracedInit;
417 LBraceStack.back()->BlockKind = BK_BracedInit;
419 Tok->BlockKind = BK_Block;
420 LBraceStack.back()->BlockKind = BK_Block;
423 LBraceStack.pop_back();
433 if (!LBraceStack.empty() && LBraceStack.back()->BlockKind == BK_Unknown)
434 LBraceStack.back()->BlockKind = BK_Block;
441 } while (Tok->Tok.isNot(tok::eof) && !LBraceStack.empty());
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;
449 FormatTok = Tokens->setPosition(StoredPosition);
452 void UnwrappedLineParser::parseBlock(bool MustBeDeclaration, bool AddLevel,
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;
459 unsigned InitialLevel = Line->Level;
462 if (MacroBlock && FormatTok->is(tok::l_paren))
466 size_t OpeningLineIndex = CurrentLines->empty()
467 ? (UnwrappedLine::kInvalidIndex)
468 : (CurrentLines->size() - 1);
470 ScopedDeclarationState DeclarationState(*Line, DeclarationScopeStack,
474 parseLevel(/*HasOpeningBrace=*/true);
479 if (MacroBlock ? !FormatTok->is(TT_MacroBlockEnd)
480 : !FormatTok->is(tok::r_brace)) {
481 Line->Level = InitialLevel;
482 FormatTok->BlockKind = BK_Block;
486 nextToken(); // Munch the closing brace.
488 if (MacroBlock && FormatTok->is(tok::l_paren))
491 if (MunchSemi && FormatTok->Tok.is(tok::semi))
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;
502 static bool isGoogScope(const UnwrappedLine &Line) {
503 // FIXME: Closure-library specific stuff should not be hard-coded but be
505 if (Line.Tokens.size() < 4)
507 auto I = Line.Tokens.begin();
508 if (I->Tok->TokenText != "goog")
511 if (I->Tok->isNot(tok::period))
514 if (I->Tok->TokenText != "scope")
517 return I->Tok->is(tok::l_paren);
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)
528 auto I = Line.Tokens.begin();
529 if (I->Tok->isNot(tok::l_paren))
532 if (I->Tok->isNot(Keywords.kw_function))
535 return I->Tok->is(tok::l_paren);
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;
551 void UnwrappedLineParser::parseChildBlock() {
552 FormatTok->BlockKind = BK_Block;
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;
569 void UnwrappedLineParser::parsePPDirective() {
570 assert(FormatTok->Tok.is(tok::hash) && "'#' expected");
571 ScopedMacroState MacroState(*Line, Tokens, FormatTok);
574 if (!FormatTok->Tok.getIdentifierInfo()) {
579 switch (FormatTok->Tok.getIdentifierInfo()->getPPKeywordID()) {
584 parsePPIf(/*IfDef=*/false);
588 parsePPIf(/*IfDef=*/true);
605 void UnwrappedLineParser::conditionalCompilationCondition(bool Unreachable) {
606 if (Unreachable || (!PPStack.empty() && PPStack.back() == PP_Unreachable))
607 PPStack.push_back(PP_Unreachable);
609 PPStack.push_back(PP_Conditional);
612 void UnwrappedLineParser::conditionalCompilationStart(bool Unreachable) {
614 assert(PPBranchLevel >= 0 && PPBranchLevel <= (int)PPLevelBranchIndex.size());
615 if (PPBranchLevel == (int)PPLevelBranchIndex.size()) {
616 PPLevelBranchIndex.push_back(0);
617 PPLevelBranchCount.push_back(0);
619 PPChainBranchIndex.push(0);
620 bool Skip = PPLevelBranchIndex[PPBranchLevel] > 0;
621 conditionalCompilationCondition(Unreachable || Skip);
624 void UnwrappedLineParser::conditionalCompilationAlternative() {
625 if (!PPStack.empty())
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());
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;
642 // Guard against #endif's without #if.
643 if (PPBranchLevel > 0)
645 if (!PPChainBranchIndex.empty())
646 PPChainBranchIndex.pop();
647 if (!PPStack.empty())
651 void UnwrappedLineParser::parsePPIf(bool IfDef) {
652 bool IfNDef = FormatTok->is(tok::pp_ifndef);
654 bool Unreachable = false;
655 if (!IfDef && (FormatTok->is(tok::kw_false) || FormatTok->TokenText == "0"))
657 if (IfDef && !IfNDef && FormatTok->TokenText == "SWIG")
659 conditionalCompilationStart(Unreachable);
663 void UnwrappedLineParser::parsePPElse() {
664 conditionalCompilationAlternative();
668 void UnwrappedLineParser::parsePPElIf() { parsePPElse(); }
670 void UnwrappedLineParser::parsePPEndIf() {
671 conditionalCompilationEnd();
675 void UnwrappedLineParser::parsePPDefine() {
678 if (FormatTok->Tok.getKind() != tok::identifier) {
683 if (FormatTok->Tok.getKind() == tok::l_paren &&
684 FormatTok->WhitespaceRange.getBegin() ==
685 FormatTok->WhitespaceRange.getEnd()) {
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
699 void UnwrappedLineParser::parsePPUnknown() {
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);
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 ||
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));
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);
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,
764 tok::kw_if, tok::kw_else,
766 tok::kw_for, tok::kw_while, tok::kw_do, tok::kw_continue, tok::kw_break,
768 tok::kw_switch, tok::kw_case,
770 tok::kw_throw, tok::kw_try, tok::kw_catch, Keywords.kw_finally,
772 tok::kw_const, tok::kw_class, Keywords.kw_var, Keywords.kw_let,
773 Keywords.kw_async, Keywords.kw_function,
775 Keywords.kw_import, tok::kw_export);
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.
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;
788 FormatToken *Next = FormatTok;
791 CommentsBeforeNextToken.empty()
792 ? Next->NewlinesBefore == 0
793 : CommentsBeforeNextToken.front()->NewlinesBefore == 0;
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))
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,
816 return addUnwrappedLine();
817 if (PreviousMustBeValue && isJSDeclOrStmt(Keywords, Next))
818 return addUnwrappedLine();
821 void UnwrappedLineParser::parseStructuralElement() {
822 assert(!FormatTok->is(tok::l_brace));
823 if (Style.Language == FormatStyle::LK_TableGen &&
824 FormatTok->is(tok::pp_include)) {
826 if (FormatTok->is(tok::string_literal))
831 switch (FormatTok->Tok.getKind()) {
834 if (FormatTok->Tok.is(tok::l_brace)) {
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();
850 return; // Handled by the caller.
851 case tok::objc_optional:
852 case tok::objc_required:
856 case tok::objc_autoreleasepool:
858 if (FormatTok->Tok.is(tok::l_brace)) {
859 if (Style.BraceWrapping.AfterObjCDeclaration)
861 parseBlock(/*MustBeDeclaration=*/false);
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.
876 if (FormatTok->is(tok::l_brace)) {
877 FormatTok->Type = TT_InlineASMBrace;
879 while (FormatTok && FormatTok->isNot(tok::eof)) {
880 if (FormatTok->is(tok::r_brace)) {
881 FormatTok->Type = TT_InlineASMBrace;
886 FormatTok->Finalized = true;
891 case tok::kw_namespace:
896 if (FormatTok->Tok.is(tok::kw_namespace)) {
902 case tok::kw_protected:
903 case tok::kw_private:
904 if (Style.Language == FormatStyle::LK_Java ||
905 Style.Language == FormatStyle::LK_JavaScript)
908 parseAccessSpecifier();
915 parseForOrWhileLoop();
923 case tok::kw_default:
936 if (FormatTok->Tok.is(tok::string_literal)) {
938 if (FormatTok->Tok.is(tok::l_brace)) {
939 parseBlock(/*MustBeDeclaration=*/true, /*AddLevel=*/false);
946 if (Style.Language == FormatStyle::LK_JavaScript) {
947 parseJavaScriptEs6ImportExport();
951 case tok::identifier:
952 if (FormatTok->is(TT_ForEachMacro)) {
953 parseForOrWhileLoop();
956 if (FormatTok->is(TT_MacroBlockBegin)) {
957 parseBlock(/*MustBeDeclaration=*/false, /*AddLevel=*/true,
958 /*MunchSemi=*/false);
961 if (FormatTok->is(Keywords.kw_import)) {
962 if (Style.Language == FormatStyle::LK_JavaScript) {
963 parseJavaScriptEs6ImportExport();
966 if (Style.Language == FormatStyle::LK_Proto) {
968 if (FormatTok->is(tok::kw_public))
970 if (!FormatTok->is(tok::string_literal))
973 if (FormatTok->is(tok::semi))
980 FormatTok->isOneOf(Keywords.kw_signals, Keywords.kw_qsignals,
981 Keywords.kw_slots, Keywords.kw_qslots)) {
983 if (FormatTok->is(tok::colon)) {
989 // In all other cases, parse the declaration.
995 const FormatToken *Previous = getPreviousToken();
996 switch (FormatTok->Tok.getKind()) {
999 if (FormatTok->Tok.is(tok::l_brace))
1003 // Ignore if this is part of "template <enum ...".
1004 if (Previous && Previous->is(tok::less)) {
1009 // parseEnum falls through and does not yet add an unwrapped line as an
1010 // enum definition can start a structural element.
1013 // This only applies for C++.
1014 if (!Style.isCpp()) {
1019 case tok::kw_typedef:
1021 if (FormatTok->isOneOf(Keywords.kw_NS_ENUM, Keywords.kw_NS_OPTIONS,
1022 Keywords.kw_CF_ENUM, Keywords.kw_CF_OPTIONS))
1025 case tok::kw_struct:
1028 // parseRecord falls through and does not yet add an unwrapped line as a
1029 // record declaration or definition can start a structural element.
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))
1042 // In Java, classes have an implicit static member "class".
1043 if (Style.Language == FormatStyle::LK_Java && FormatTok &&
1044 FormatTok->is(tok::kw_class))
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
1062 case tok::kw_operator:
1064 if (FormatTok->isBinaryOperator())
1069 if (FormatTok->Tok.isAnyIdentifier() ||
1070 FormatTok->isSimpleTypeSpecifier())
1072 if (FormatTok->is(tok::l_paren))
1074 if (FormatTok->is(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)
1085 FormatTok->Type = TT_FunctionLBrace;
1086 parseBlock(/*MustBeDeclaration=*/false);
1090 // Otherwise this was a braced init list, and the structural
1091 // element continues.
1094 // We arrive here when parsing function-try blocks.
1097 case tok::identifier: {
1098 if (FormatTok->is(TT_MacroBlockEnd)) {
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();
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)) {
1136 // See if the following token should start a new unwrapped line.
1137 StringRef Text = FormatTok->TokenText;
1139 if (Line->Tokens.size() == 1 &&
1140 // JS doesn't have macros, and within classes colons indicate fields,
1142 Style.Language != FormatStyle::LK_JavaScript) {
1143 if (FormatTok->Tok.is(tok::colon) && !Line->MustBeDeclaration) {
1144 Line->Tokens.begin()->Tok->MustBreakBefore = true;
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);
1154 bool FollowedByNewline =
1155 CommentsBeforeNextToken.empty()
1156 ? FormatTok->NewlinesBefore > 0
1157 : CommentsBeforeNextToken.front()->NewlinesBefore > 0;
1159 if (FollowedByNewline && (Text.size() >= 5 || FunctionLike) &&
1160 tokenCanStartNewLine(FormatTok->Tok) && Text == Text.upper()) {
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)) {
1173 if (FormatTok->is(tok::l_brace))
1179 if (FormatTok->Tok.is(tok::l_brace))
1181 else if (Style.Language == FormatStyle::LK_Proto &&
1182 FormatTok->Tok.is(tok::less))
1183 parseBracedList(/*ContinueOnSemicolons=*/false,
1184 /*ClosingBraceKind=*/tok::greater);
1199 bool UnwrappedLineParser::tryToParseLambda() {
1200 if (!Style.isCpp()) {
1204 const FormatToken* Previous = getPreviousToken();
1206 (Previous->isOneOf(tok::identifier, tok::kw_operator, tok::kw_new,
1208 Previous->closesScope() || Previous->isSimpleTypeSpecifier())) {
1212 assert(FormatTok->is(tok::l_square));
1213 FormatToken &LSquare = *FormatTok;
1214 if (!tryToParseLambdaIntroducer())
1217 while (FormatTok->isNot(tok::l_brace)) {
1218 if (FormatTok->isSimpleTypeSpecifier()) {
1222 switch (FormatTok->Tok.getKind()) {
1234 case tok::identifier:
1235 case tok::numeric_constant:
1236 case tok::coloncolon:
1237 case tok::kw_mutable:
1241 FormatTok->Type = TT_LambdaArrow;
1248 LSquare.Type = TT_LambdaLSquare;
1253 bool UnwrappedLineParser::tryToParseLambdaIntroducer() {
1255 if (FormatTok->is(tok::equal)) {
1257 if (FormatTok->is(tok::r_square)) {
1261 if (FormatTok->isNot(tok::comma))
1264 } else if (FormatTok->is(tok::amp)) {
1266 if (FormatTok->is(tok::r_square)) {
1270 if (!FormatTok->isOneOf(tok::comma, tok::identifier)) {
1273 if (FormatTok->is(tok::comma))
1275 } else if (FormatTok->is(tok::r_square)) {
1280 if (FormatTok->is(tok::amp))
1282 if (!FormatTok->isOneOf(tok::identifier, tok::kw_this))
1285 if (FormatTok->is(tok::ellipsis))
1287 if (FormatTok->is(tok::comma)) {
1289 } else if (FormatTok->is(tok::r_square)) {
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))
1304 // Consume "function".
1307 // Consume * (generator function). Treat it like C++'s overloaded operators.
1308 if (FormatTok->is(tok::star)) {
1309 FormatTok->Type = TT_OverloadedOperator;
1313 // Consume function name.
1314 if (FormatTok->is(tok::identifier))
1317 if (FormatTok->isNot(tok::l_paren))
1320 // Parse formal parameter list.
1323 if (FormatTok->is(tok::colon)) {
1324 // Parse a type definition.
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();
1332 while (!FormatTok->isOneOf(tok::l_brace, tok::semi) && !eof())
1336 if (FormatTok->is(tok::semi))
1342 bool UnwrappedLineParser::tryToParseBracedList() {
1343 if (FormatTok->BlockKind == BK_Unknown)
1344 calculateBraceTypes();
1345 assert(FormatTok->BlockKind != BK_Unknown);
1346 if (FormatTok->BlockKind == BK_Block)
1352 bool UnwrappedLineParser::parseBracedList(bool ContinueOnSemicolons,
1353 tok::TokenKind ClosingBraceKind) {
1354 bool HasError = false;
1357 // FIXME: Once we have an expression parser in the UnwrappedLineParser,
1358 // replace this by using parseAssigmentExpression() inside.
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();
1366 if (FormatTok->is(TT_JsFatArrow)) {
1368 // Fat arrows can be followed by simple expressions or by child blocks
1370 if (FormatTok->is(tok::l_brace)) {
1375 if (FormatTok->is(tok::l_brace)) {
1376 // Could be a method inside of a braced list `{a() { return 1; }}`.
1377 if (tryToParseBracedList())
1382 if (FormatTok->Tok.getKind() == ClosingBraceKind) {
1386 switch (FormatTok->Tok.getKind()) {
1389 if (FormatTok->is(tok::l_brace)) {
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))
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;
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
1417 if (Style.Language == FormatStyle::LK_JavaScript) {
1422 if (!ContinueOnSemicolons)
1437 void UnwrappedLineParser::parseParens() {
1438 assert(FormatTok->Tok.is(tok::l_paren) && "'(' expected.");
1441 switch (FormatTok->Tok.getKind()) {
1444 if (Style.Language == FormatStyle::LK_Java && FormatTok->is(tok::l_brace))
1451 // A "}" inside parenthesis is an error if there wasn't a matching "{".
1457 if (!tryToParseBracedList())
1462 if (FormatTok->Tok.is(tok::l_brace))
1466 if (Style.Language == FormatStyle::LK_JavaScript)
1467 parseRecord(/*ParseAsExpr=*/true);
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();
1486 void UnwrappedLineParser::parseSquare() {
1487 assert(FormatTok->Tok.is(tok::l_square) && "'[' expected.");
1488 if (tryToParseLambda())
1491 switch (FormatTok->Tok.getKind()) {
1499 // A "}" inside parenthesis is an error if there wasn't a matching "{".
1504 case tok::l_brace: {
1505 if (!tryToParseBracedList())
1511 if (FormatTok->Tok.is(tok::l_brace))
1521 void UnwrappedLineParser::parseIfThenElse() {
1522 assert(FormatTok->Tok.is(tok::kw_if) && "'if' expected");
1524 if (FormatTok->Tok.is(tok::kw_constexpr))
1526 if (FormatTok->Tok.is(tok::l_paren))
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)
1535 NeedsUnwrappedLine = true;
1539 parseStructuralElement();
1542 if (FormatTok->Tok.is(tok::kw_else)) {
1544 if (FormatTok->Tok.is(tok::l_brace)) {
1545 CompoundStatementIndenter Indenter(this, Style, Line->Level);
1546 parseBlock(/*MustBeDeclaration=*/false);
1548 } else if (FormatTok->Tok.is(tok::kw_if)) {
1553 parseStructuralElement();
1554 if (FormatTok->is(tok::eof))
1558 } else if (NeedsUnwrappedLine) {
1563 void UnwrappedLineParser::parseTryCatch() {
1564 assert(FormatTok->isOneOf(tok::kw_try, tok::kw___try) && "'try' expected");
1566 bool NeedsUnwrappedLine = false;
1567 if (FormatTok->is(tok::colon)) {
1568 // We are in a function try block, what comes is an initializer list.
1570 while (FormatTok->is(tok::identifier)) {
1572 if (FormatTok->is(tok::l_paren))
1574 if (FormatTok->is(tok::comma))
1578 // Parse try with resource.
1579 if (Style.Language == FormatStyle::LK_Java && FormatTok->is(tok::l_paren)) {
1582 if (FormatTok->is(tok::l_brace)) {
1583 CompoundStatementIndenter Indenter(this, Style, Line->Level);
1584 parseBlock(/*MustBeDeclaration=*/false);
1585 if (Style.BraceWrapping.BeforeCatch) {
1588 NeedsUnwrappedLine = true;
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.
1596 parseStructuralElement();
1600 if (FormatTok->is(tok::at))
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))))
1611 while (FormatTok->isNot(tok::l_brace)) {
1612 if (FormatTok->is(tok::l_paren)) {
1616 if (FormatTok->isOneOf(tok::semi, tok::r_brace, tok::eof))
1620 NeedsUnwrappedLine = false;
1621 CompoundStatementIndenter Indenter(this, Style, Line->Level);
1622 parseBlock(/*MustBeDeclaration=*/false);
1623 if (Style.BraceWrapping.BeforeCatch)
1626 NeedsUnwrappedLine = true;
1628 if (NeedsUnwrappedLine)
1632 void UnwrappedLineParser::parseNamespace() {
1633 assert(FormatTok->Tok.is(tok::kw_namespace) && "'namespace' expected");
1635 const FormatToken &InitialToken = *FormatTok;
1637 while (FormatTok->isOneOf(tok::identifier, tok::coloncolon))
1639 if (FormatTok->Tok.is(tok::l_brace)) {
1640 if (ShouldBreakBeforeBrace(Style, InitialToken))
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))
1653 // FIXME: Add error handling.
1656 void UnwrappedLineParser::parseNew() {
1657 assert(FormatTok->is(tok::kw_new) && "'new' expected");
1659 if (Style.Language != FormatStyle::LK_Java)
1662 // In Java, we can parse everything up to the parens, which aren't optional.
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))
1668 // Consume the parens.
1669 if (FormatTok->is(tok::l_paren)) {
1672 // If there is a class body of an anonymous class, consume that as child.
1673 if (FormatTok->is(tok::l_brace))
1681 void UnwrappedLineParser::parseForOrWhileLoop() {
1682 assert(FormatTok->isOneOf(tok::kw_for, tok::kw_while, TT_ForEachMacro) &&
1683 "'for', 'while' or foreach macro expected");
1685 // JS' for await ( ...
1686 if (Style.Language == FormatStyle::LK_JavaScript &&
1687 FormatTok->is(Keywords.kw_await))
1689 if (FormatTok->Tok.is(tok::l_paren))
1691 if (FormatTok->Tok.is(tok::l_brace)) {
1692 CompoundStatementIndenter Indenter(this, Style, Line->Level);
1693 parseBlock(/*MustBeDeclaration=*/false);
1698 parseStructuralElement();
1703 void UnwrappedLineParser::parseDoWhile() {
1704 assert(FormatTok->Tok.is(tok::kw_do) && "'do' expected");
1706 if (FormatTok->Tok.is(tok::l_brace)) {
1707 CompoundStatementIndenter Indenter(this, Style, Line->Level);
1708 parseBlock(/*MustBeDeclaration=*/false);
1709 if (Style.BraceWrapping.IndentBraces)
1714 parseStructuralElement();
1718 // FIXME: Add error handling.
1719 if (!FormatTok->Tok.is(tok::kw_while)) {
1725 parseStructuralElement();
1728 void UnwrappedLineParser::parseLabel() {
1730 unsigned OldLineLevel = Line->Level;
1731 if (Line->Level > 1 || (!Line->InPPDirective && Line->Level > 0))
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)
1739 parseStructuralElement();
1743 if (FormatTok->is(tok::semi))
1747 Line->Level = OldLineLevel;
1748 if (FormatTok->isNot(tok::l_brace)) {
1749 parseStructuralElement();
1754 void UnwrappedLineParser::parseCaseLabel() {
1755 assert(FormatTok->Tok.is(tok::kw_case) && "'case' expected");
1756 // FIXME: fix handling of complex expressions here.
1759 } while (!eof() && !FormatTok->Tok.is(tok::colon));
1763 void UnwrappedLineParser::parseSwitch() {
1764 assert(FormatTok->Tok.is(tok::kw_switch) && "'switch' expected");
1766 if (FormatTok->Tok.is(tok::l_paren))
1768 if (FormatTok->Tok.is(tok::l_brace)) {
1769 CompoundStatementIndenter Indenter(this, Style, Line->Level);
1770 parseBlock(/*MustBeDeclaration=*/false);
1775 parseStructuralElement();
1780 void UnwrappedLineParser::parseAccessSpecifier() {
1782 // Understand Qt's slots.
1783 if (FormatTok->isOneOf(Keywords.kw_slots, Keywords.kw_qslots))
1785 // Otherwise, we don't know what it is, and we'd better keep the next token.
1786 if (FormatTok->Tok.is(tok::colon))
1791 bool UnwrappedLineParser::parseEnum() {
1792 // Won't be 'enum' for NS_ENUMs.
1793 if (FormatTok->Tok.is(tok::kw_enum))
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))
1803 // Eat up enum class ...
1804 if (FormatTok->Tok.is(tok::kw_class) || FormatTok->Tok.is(tok::kw_struct))
1807 while (FormatTok->Tok.getIdentifierInfo() ||
1808 FormatTok->isOneOf(tok::colon, tok::coloncolon, tok::less,
1809 tok::greater, tok::comma, tok::question)) {
1811 // We can have macros or attributes in between 'enum' and the enum name.
1812 if (FormatTok->is(tok::l_paren))
1814 if (FormatTok->is(tok::identifier)) {
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))
1823 // Just a declaration or something is wrong.
1824 if (FormatTok->isNot(tok::l_brace))
1826 FormatTok->BlockKind = BK_Block;
1828 if (Style.Language == FormatStyle::LK_Java) {
1829 // Java enums are different.
1830 parseJavaEnumBody();
1833 if (Style.Language == FormatStyle::LK_Proto) {
1834 parseBlock(/*MustBeDeclaration=*/true);
1839 bool HasError = !parseBracedList(/*ContinueOnSemicolons=*/true);
1841 if (FormatTok->is(tok::semi))
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.
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();
1860 if (Tok->is(tok::r_brace))
1862 if (Tok->isOneOf(tok::l_brace, tok::semi)) {
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();
1870 FormatTok = Tokens->setPosition(StoredPosition);
1878 // Parse the body of a more complex enum.
1879 // First add a line for everything up to the "{".
1884 // Parse the enum constants.
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)) {
1892 } else if (FormatTok->is(tok::comma)) {
1895 } else if (FormatTok->is(tok::semi)) {
1899 } else if (FormatTok->is(tok::r_brace)) {
1907 // Parse the class body after the enum's ";" if any.
1908 parseLevel(/*HasOpeningBrace=*/true);
1914 void UnwrappedLineParser::parseRecord(bool ParseAsExpr) {
1915 const FormatToken &InitialToken = *FormatTok;
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,
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();
1930 // We can have macros or attributes in between 'class' and the class name.
1931 if (!IsNonMacroIdentifier && FormatTok->Tok.is(tok::l_paren))
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)) {
1947 if (FormatTok->is(tok::l_brace)) {
1948 calculateBraceTypes(/*ExpectClassBody=*/true);
1949 if (!tryToParseBracedList())
1952 if (FormatTok->Tok.is(tok::semi))
1957 if (FormatTok->Tok.is(tok::l_brace)) {
1961 if (ShouldBreakBeforeBrace(Style, InitialToken))
1964 parseBlock(/*MustBeDeclaration=*/true, /*AddLevel=*/true,
1965 /*MunchSemi=*/false);
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.
1973 void UnwrappedLineParser::parseObjCProtocolList() {
1974 assert(FormatTok->Tok.is(tok::less) && "'<' expected.");
1977 while (!eof() && FormatTok->Tok.isNot(tok::greater));
1978 nextToken(); // Skip '>'.
1981 void UnwrappedLineParser::parseObjCUntilAtEnd() {
1983 if (FormatTok->Tok.isObjCAtKeyword(tok::objc_end)) {
1988 if (FormatTok->is(tok::l_brace)) {
1989 parseBlock(/*MustBeDeclaration=*/false);
1990 // In ObjC interfaces, nothing should be following the "}".
1992 } else if (FormatTok->is(tok::r_brace)) {
1993 // Ignore stray "}". parseStructuralElement doesn't consume them.
1997 parseStructuralElement();
2002 void UnwrappedLineParser::parseObjCInterfaceOrImplementation() {
2004 nextToken(); // interface name
2006 // @interface can be followed by either a base class, or a category.
2007 if (FormatTok->Tok.is(tok::colon)) {
2009 nextToken(); // base class name
2010 } else if (FormatTok->Tok.is(tok::l_paren))
2011 // Skip category, if present.
2014 if (FormatTok->Tok.is(tok::less))
2015 parseObjCProtocolList();
2017 if (FormatTok->Tok.is(tok::l_brace)) {
2018 if (Style.BraceWrapping.AfterObjCDeclaration)
2020 parseBlock(/*MustBeDeclaration=*/true);
2023 // With instance variables, this puts '}' on its own line. Without instance
2024 // variables, this ends the @interface line.
2027 parseObjCUntilAtEnd();
2030 void UnwrappedLineParser::parseObjCProtocol() {
2032 nextToken(); // protocol name
2034 if (FormatTok->Tok.is(tok::less))
2035 parseObjCProtocolList();
2037 // Check for protocol declaration.
2038 if (FormatTok->Tok.is(tok::semi)) {
2040 return addUnwrappedLine();
2044 parseObjCUntilAtEnd();
2047 void UnwrappedLineParser::parseJavaScriptEs6ImportExport() {
2048 bool IsImport = FormatTok->is(Keywords.kw_import);
2049 assert(IsImport || FormatTok->is(tok::kw_export));
2052 // Consume the "default" in "export default class/function".
2053 if (FormatTok->is(tok::kw_default))
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
2059 if (FormatTok->is(Keywords.kw_async))
2061 if (FormatTok->is(Keywords.kw_function)) {
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())
2075 if (FormatTok->is(tok::semi))
2077 if (Line->Tokens.size() == 0) {
2078 // Common issue: Automatic Semicolon Insertion wrapped the line, so the
2079 // import statement should terminate.
2082 if (FormatTok->is(tok::l_brace)) {
2083 FormatTok->BlockKind = BK_Block;
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();
2098 llvm::dbgs() << I->Tok->Tok.getName() << "["
2099 << "T=" << I->Tok->Type
2100 << ", OC=" << I->Tok->OriginalColumn << "] ";
2102 for (std::list<UnwrappedLineNode>::const_iterator I = Line.Tokens.begin(),
2103 E = Line.Tokens.end();
2105 const UnwrappedLineNode &Node = *I;
2106 for (SmallVectorImpl<UnwrappedLine>::const_iterator
2107 I = Node.Children.begin(),
2108 E = Node.Children.end();
2110 printDebugInfo(*I, "\nChild: ");
2113 llvm::dbgs() << "\n";
2116 void UnwrappedLineParser::addUnwrappedLine() {
2117 if (Line->Tokens.empty())
2120 if (CurrentLines == &Lines)
2121 printDebugInfo(*Line);
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();
2134 bool UnwrappedLineParser::eof() const { return FormatTok->Tok.is(tok::eof); }
2136 bool UnwrappedLineParser::isOnNewLine(const FormatToken &FormatTok) {
2137 return (Line->InPPDirective || FormatTok.HasUnescapedNewline) &&
2138 FormatTok.NewlinesBefore > 0;
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())
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))
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.
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
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.
2169 // For example, the second line comment continues the first in these cases:
2181 // int i; // first line
2186 // do { // first line
2199 // The second line comment doesn't continue the first in these cases:
2206 // int i; // first line
2211 // do { // first line
2222 const FormatToken *MinColumnToken = Line.Tokens.front().Tok;
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;
2233 PreviousToken = Node.Tok;
2235 // Grab the last newline preceding a token in this unwrapped line.
2236 if (Node.Tok->NewlinesBefore > 0) {
2237 MinColumnToken = Node.Tok;
2240 if (PreviousToken && PreviousToken->is(tok::l_brace)) {
2241 MinColumnToken = PreviousToken;
2244 return continuesLineComment(FormatTok, /*Previous=*/Line.Tokens.back().Tok,
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();
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.
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)
2268 if (NewlineBeforeNext && JustComments)
2270 CommentsBeforeNextToken.clear();
2273 void UnwrappedLineParser::nextToken() {
2276 flushComments(isOnNewLine(*FormatTok));
2277 pushToken(FormatTok);
2278 if (Style.Language != FormatStyle::LK_JavaScript)
2281 readTokenWithJavaScriptASI();
2284 const FormatToken *UnwrappedLineParser::getPreviousToken() {
2285 // FIXME: This is a dirty way to access the previous token. Find a better
2287 if (!Line || Line->Tokens.empty())
2289 return Line->Tokens.back().Tok;
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:
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.
2303 // For example in this code:
2305 // int a; // line about a
2306 // // line 1 about b
2307 // // line 2 about b
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())
2315 bool ShouldPushCommentsInCurrentLine = true;
2316 bool HasTrailAlignedWithNextToken = false;
2317 unsigned StartOfTrailAlignedWithNextToken = 0;
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;
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;
2333 FormatTok->ContinuesLineCommentSection =
2334 continuesLineCommentSection(*FormatTok, *Line, CommentPragmasRegex);
2336 if (!FormatTok->ContinuesLineCommentSection &&
2337 (isOnNewLine(*FormatTok) || FormatTok->IsFirst)) {
2338 ShouldPushCommentsInCurrentLine = false;
2340 if (ShouldPushCommentsInCurrentLine) {
2341 pushToken(FormatTok);
2343 CommentsBeforeNextToken.push_back(FormatTok);
2348 void UnwrappedLineParser::readToken() {
2349 SmallVector<FormatToken *, 1> Comments;
2351 FormatTok = Tokens->getNextToken();
2353 while (!Line->InPPDirective && FormatTok->Tok.is(tok::hash) &&
2354 (FormatTok->HasUnescapedNewline || FormatTok->IsFirst)) {
2355 distributeComments(Comments, FormatTok);
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));
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();
2377 FormatTok = Tokens->getNextToken();
2378 FormatTok->MustBreakBefore = true;
2381 if (!PPStack.empty() && (PPStack.back() == PP_Unreachable) &&
2382 !Line->InPPDirective) {
2386 if (!FormatTok->Tok.is(tok::comment)) {
2387 distributeComments(Comments, FormatTok);
2392 Comments.push_back(FormatTok);
2395 distributeComments(Comments, nullptr);
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;
2407 } // end namespace format
2408 } // end namespace clang