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 PrevTok->is(tok::colon))
365 // A colon indicates this code is in a type, or a braced list following
366 // a label in an object literal ({a: {b: 1}}).
367 // The code below could be confused by semicolons between the individual
368 // members in a type member list, which would normally trigger BK_Block.
369 // In both cases, this must be parsed as an inline braced init.
370 Tok->BlockKind = BK_BracedInit;
372 Tok->BlockKind = BK_Unknown;
373 LBraceStack.push_back(Tok);
376 if (LBraceStack.empty())
378 if (LBraceStack.back()->BlockKind == BK_Unknown) {
379 bool ProbablyBracedList = false;
380 if (Style.Language == FormatStyle::LK_Proto) {
381 ProbablyBracedList = NextTok->isOneOf(tok::comma, tok::r_square);
383 // Using OriginalColumn to distinguish between ObjC methods and
384 // binary operators is a bit hacky.
385 bool NextIsObjCMethod = NextTok->isOneOf(tok::plus, tok::minus) &&
386 NextTok->OriginalColumn == 0;
388 // If there is a comma, semicolon or right paren after the closing
389 // brace, we assume this is a braced initializer list. Note that
390 // regardless how we mark inner braces here, we will overwrite the
391 // BlockKind later if we parse a braced list (where all blocks
392 // inside are by default braced lists), or when we explicitly detect
393 // blocks (for example while parsing lambdas).
395 (Style.Language == FormatStyle::LK_JavaScript &&
396 NextTok->isOneOf(Keywords.kw_of, Keywords.kw_in,
398 (Style.isCpp() && NextTok->is(tok::l_paren)) ||
399 NextTok->isOneOf(tok::comma, tok::period, tok::colon,
400 tok::r_paren, tok::r_square, tok::l_brace,
401 tok::l_square, tok::ellipsis) ||
402 (NextTok->is(tok::identifier) &&
403 !PrevTok->isOneOf(tok::semi, tok::r_brace, tok::l_brace)) ||
404 (NextTok->is(tok::semi) &&
405 (!ExpectClassBody || LBraceStack.size() != 1)) ||
406 (NextTok->isBinaryOperator() && !NextIsObjCMethod);
408 if (ProbablyBracedList) {
409 Tok->BlockKind = BK_BracedInit;
410 LBraceStack.back()->BlockKind = BK_BracedInit;
412 Tok->BlockKind = BK_Block;
413 LBraceStack.back()->BlockKind = BK_Block;
416 LBraceStack.pop_back();
426 if (!LBraceStack.empty() && LBraceStack.back()->BlockKind == BK_Unknown)
427 LBraceStack.back()->BlockKind = BK_Block;
434 } while (Tok->Tok.isNot(tok::eof) && !LBraceStack.empty());
436 // Assume other blocks for all unclosed opening braces.
437 for (unsigned i = 0, e = LBraceStack.size(); i != e; ++i) {
438 if (LBraceStack[i]->BlockKind == BK_Unknown)
439 LBraceStack[i]->BlockKind = BK_Block;
442 FormatTok = Tokens->setPosition(StoredPosition);
445 void UnwrappedLineParser::parseBlock(bool MustBeDeclaration, bool AddLevel,
447 assert(FormatTok->isOneOf(tok::l_brace, TT_MacroBlockBegin) &&
448 "'{' or macro block token expected");
449 const bool MacroBlock = FormatTok->is(TT_MacroBlockBegin);
450 FormatTok->BlockKind = BK_Block;
452 unsigned InitialLevel = Line->Level;
455 if (MacroBlock && FormatTok->is(tok::l_paren))
459 size_t OpeningLineIndex = CurrentLines->empty()
460 ? (UnwrappedLine::kInvalidIndex)
461 : (CurrentLines->size() - 1);
463 ScopedDeclarationState DeclarationState(*Line, DeclarationScopeStack,
467 parseLevel(/*HasOpeningBrace=*/true);
472 if (MacroBlock ? !FormatTok->is(TT_MacroBlockEnd)
473 : !FormatTok->is(tok::r_brace)) {
474 Line->Level = InitialLevel;
475 FormatTok->BlockKind = BK_Block;
479 nextToken(); // Munch the closing brace.
481 if (MacroBlock && FormatTok->is(tok::l_paren))
484 if (MunchSemi && FormatTok->Tok.is(tok::semi))
486 Line->Level = InitialLevel;
487 Line->MatchingOpeningBlockLineIndex = OpeningLineIndex;
490 static bool isGoogScope(const UnwrappedLine &Line) {
491 // FIXME: Closure-library specific stuff should not be hard-coded but be
493 if (Line.Tokens.size() < 4)
495 auto I = Line.Tokens.begin();
496 if (I->Tok->TokenText != "goog")
499 if (I->Tok->isNot(tok::period))
502 if (I->Tok->TokenText != "scope")
505 return I->Tok->is(tok::l_paren);
508 static bool isIIFE(const UnwrappedLine &Line,
509 const AdditionalKeywords &Keywords) {
510 // Look for the start of an immediately invoked anonymous function.
511 // https://en.wikipedia.org/wiki/Immediately-invoked_function_expression
512 // This is commonly done in JavaScript to create a new, anonymous scope.
513 // Example: (function() { ... })()
514 if (Line.Tokens.size() < 3)
516 auto I = Line.Tokens.begin();
517 if (I->Tok->isNot(tok::l_paren))
520 if (I->Tok->isNot(Keywords.kw_function))
523 return I->Tok->is(tok::l_paren);
526 static bool ShouldBreakBeforeBrace(const FormatStyle &Style,
527 const FormatToken &InitialToken) {
528 if (InitialToken.is(tok::kw_namespace))
529 return Style.BraceWrapping.AfterNamespace;
530 if (InitialToken.is(tok::kw_class))
531 return Style.BraceWrapping.AfterClass;
532 if (InitialToken.is(tok::kw_union))
533 return Style.BraceWrapping.AfterUnion;
534 if (InitialToken.is(tok::kw_struct))
535 return Style.BraceWrapping.AfterStruct;
539 void UnwrappedLineParser::parseChildBlock() {
540 FormatTok->BlockKind = BK_Block;
544 (Style.Language == FormatStyle::LK_JavaScript &&
545 (isGoogScope(*Line) || isIIFE(*Line, Keywords)));
546 ScopedLineState LineState(*this);
547 ScopedDeclarationState DeclarationState(*Line, DeclarationScopeStack,
548 /*MustBeDeclaration=*/false);
549 Line->Level += SkipIndent ? 0 : 1;
550 parseLevel(/*HasOpeningBrace=*/true);
551 flushComments(isOnNewLine(*FormatTok));
552 Line->Level -= SkipIndent ? 0 : 1;
557 void UnwrappedLineParser::parsePPDirective() {
558 assert(FormatTok->Tok.is(tok::hash) && "'#' expected");
559 ScopedMacroState MacroState(*Line, Tokens, FormatTok);
562 if (!FormatTok->Tok.getIdentifierInfo()) {
567 switch (FormatTok->Tok.getIdentifierInfo()->getPPKeywordID()) {
572 parsePPIf(/*IfDef=*/false);
576 parsePPIf(/*IfDef=*/true);
593 void UnwrappedLineParser::conditionalCompilationCondition(bool Unreachable) {
594 if (Unreachable || (!PPStack.empty() && PPStack.back() == PP_Unreachable))
595 PPStack.push_back(PP_Unreachable);
597 PPStack.push_back(PP_Conditional);
600 void UnwrappedLineParser::conditionalCompilationStart(bool Unreachable) {
602 assert(PPBranchLevel >= 0 && PPBranchLevel <= (int)PPLevelBranchIndex.size());
603 if (PPBranchLevel == (int)PPLevelBranchIndex.size()) {
604 PPLevelBranchIndex.push_back(0);
605 PPLevelBranchCount.push_back(0);
607 PPChainBranchIndex.push(0);
608 bool Skip = PPLevelBranchIndex[PPBranchLevel] > 0;
609 conditionalCompilationCondition(Unreachable || Skip);
612 void UnwrappedLineParser::conditionalCompilationAlternative() {
613 if (!PPStack.empty())
615 assert(PPBranchLevel < (int)PPLevelBranchIndex.size());
616 if (!PPChainBranchIndex.empty())
617 ++PPChainBranchIndex.top();
618 conditionalCompilationCondition(
619 PPBranchLevel >= 0 && !PPChainBranchIndex.empty() &&
620 PPLevelBranchIndex[PPBranchLevel] != PPChainBranchIndex.top());
623 void UnwrappedLineParser::conditionalCompilationEnd() {
624 assert(PPBranchLevel < (int)PPLevelBranchIndex.size());
625 if (PPBranchLevel >= 0 && !PPChainBranchIndex.empty()) {
626 if (PPChainBranchIndex.top() + 1 > PPLevelBranchCount[PPBranchLevel]) {
627 PPLevelBranchCount[PPBranchLevel] = PPChainBranchIndex.top() + 1;
630 // Guard against #endif's without #if.
631 if (PPBranchLevel > 0)
633 if (!PPChainBranchIndex.empty())
634 PPChainBranchIndex.pop();
635 if (!PPStack.empty())
639 void UnwrappedLineParser::parsePPIf(bool IfDef) {
640 bool IfNDef = FormatTok->is(tok::pp_ifndef);
642 bool Unreachable = false;
643 if (!IfDef && (FormatTok->is(tok::kw_false) || FormatTok->TokenText == "0"))
645 if (IfDef && !IfNDef && FormatTok->TokenText == "SWIG")
647 conditionalCompilationStart(Unreachable);
651 void UnwrappedLineParser::parsePPElse() {
652 conditionalCompilationAlternative();
656 void UnwrappedLineParser::parsePPElIf() { parsePPElse(); }
658 void UnwrappedLineParser::parsePPEndIf() {
659 conditionalCompilationEnd();
663 void UnwrappedLineParser::parsePPDefine() {
666 if (FormatTok->Tok.getKind() != tok::identifier) {
671 if (FormatTok->Tok.getKind() == tok::l_paren &&
672 FormatTok->WhitespaceRange.getBegin() ==
673 FormatTok->WhitespaceRange.getEnd()) {
679 // Errors during a preprocessor directive can only affect the layout of the
680 // preprocessor directive, and thus we ignore them. An alternative approach
681 // would be to use the same approach we use on the file level (no
682 // re-indentation if there was a structural error) within the macro
687 void UnwrappedLineParser::parsePPUnknown() {
694 // Here we blacklist certain tokens that are not usually the first token in an
695 // unwrapped line. This is used in attempt to distinguish macro calls without
696 // trailing semicolons from other constructs split to several lines.
697 static bool tokenCanStartNewLine(const clang::Token &Tok) {
698 // Semicolon can be a null-statement, l_square can be a start of a macro or
699 // a C++11 attribute, but this doesn't seem to be common.
700 return Tok.isNot(tok::semi) && Tok.isNot(tok::l_brace) &&
701 Tok.isNot(tok::l_square) &&
702 // Tokens that can only be used as binary operators and a part of
703 // overloaded operator names.
704 Tok.isNot(tok::period) && Tok.isNot(tok::periodstar) &&
705 Tok.isNot(tok::arrow) && Tok.isNot(tok::arrowstar) &&
706 Tok.isNot(tok::less) && Tok.isNot(tok::greater) &&
707 Tok.isNot(tok::slash) && Tok.isNot(tok::percent) &&
708 Tok.isNot(tok::lessless) && Tok.isNot(tok::greatergreater) &&
709 Tok.isNot(tok::equal) && Tok.isNot(tok::plusequal) &&
710 Tok.isNot(tok::minusequal) && Tok.isNot(tok::starequal) &&
711 Tok.isNot(tok::slashequal) && Tok.isNot(tok::percentequal) &&
712 Tok.isNot(tok::ampequal) && Tok.isNot(tok::pipeequal) &&
713 Tok.isNot(tok::caretequal) && Tok.isNot(tok::greatergreaterequal) &&
714 Tok.isNot(tok::lesslessequal) &&
715 // Colon is used in labels, base class lists, initializer lists,
716 // range-based for loops, ternary operator, but should never be the
717 // first token in an unwrapped line.
718 Tok.isNot(tok::colon) &&
719 // 'noexcept' is a trailing annotation.
720 Tok.isNot(tok::kw_noexcept);
723 static bool mustBeJSIdent(const AdditionalKeywords &Keywords,
724 const FormatToken *FormatTok) {
725 // FIXME: This returns true for C/C++ keywords like 'struct'.
726 return FormatTok->is(tok::identifier) &&
727 (FormatTok->Tok.getIdentifierInfo() == nullptr ||
729 Keywords.kw_in, Keywords.kw_of, Keywords.kw_as, Keywords.kw_async,
730 Keywords.kw_await, Keywords.kw_yield, Keywords.kw_finally,
731 Keywords.kw_function, Keywords.kw_import, Keywords.kw_is,
732 Keywords.kw_let, Keywords.kw_var, tok::kw_const,
733 Keywords.kw_abstract, Keywords.kw_extends, Keywords.kw_implements,
734 Keywords.kw_instanceof, Keywords.kw_interface,
735 Keywords.kw_throws));
738 static bool mustBeJSIdentOrValue(const AdditionalKeywords &Keywords,
739 const FormatToken *FormatTok) {
740 return FormatTok->Tok.isLiteral() ||
741 FormatTok->isOneOf(tok::kw_true, tok::kw_false) ||
742 mustBeJSIdent(Keywords, FormatTok);
745 // isJSDeclOrStmt returns true if |FormatTok| starts a declaration or statement
746 // when encountered after a value (see mustBeJSIdentOrValue).
747 static bool isJSDeclOrStmt(const AdditionalKeywords &Keywords,
748 const FormatToken *FormatTok) {
749 return FormatTok->isOneOf(
750 tok::kw_return, Keywords.kw_yield,
752 tok::kw_if, tok::kw_else,
754 tok::kw_for, tok::kw_while, tok::kw_do, tok::kw_continue, tok::kw_break,
756 tok::kw_switch, tok::kw_case,
758 tok::kw_throw, tok::kw_try, tok::kw_catch, Keywords.kw_finally,
760 tok::kw_const, tok::kw_class, Keywords.kw_var, Keywords.kw_let,
761 Keywords.kw_async, Keywords.kw_function,
763 Keywords.kw_import, tok::kw_export);
766 // readTokenWithJavaScriptASI reads the next token and terminates the current
767 // line if JavaScript Automatic Semicolon Insertion must
768 // happen between the current token and the next token.
770 // This method is conservative - it cannot cover all edge cases of JavaScript,
771 // but only aims to correctly handle certain well known cases. It *must not*
772 // return true in speculative cases.
773 void UnwrappedLineParser::readTokenWithJavaScriptASI() {
774 FormatToken *Previous = FormatTok;
776 FormatToken *Next = FormatTok;
779 CommentsBeforeNextToken.empty()
780 ? Next->NewlinesBefore == 0
781 : CommentsBeforeNextToken.front()->NewlinesBefore == 0;
785 bool PreviousMustBeValue = mustBeJSIdentOrValue(Keywords, Previous);
786 bool PreviousStartsTemplateExpr =
787 Previous->is(TT_TemplateString) && Previous->TokenText.endswith("${");
788 if (PreviousMustBeValue && Line && Line->Tokens.size() > 1) {
789 // If the token before the previous one is an '@', the previous token is an
790 // annotation and can precede another identifier/value.
791 const FormatToken *PrePrevious = std::prev(Line->Tokens.end(), 2)->Tok;
792 if (PrePrevious->is(tok::at))
795 if (Next->is(tok::exclaim) && PreviousMustBeValue)
796 return addUnwrappedLine();
797 bool NextMustBeValue = mustBeJSIdentOrValue(Keywords, Next);
798 bool NextEndsTemplateExpr =
799 Next->is(TT_TemplateString) && Next->TokenText.startswith("}");
800 if (NextMustBeValue && !NextEndsTemplateExpr && !PreviousStartsTemplateExpr &&
801 (PreviousMustBeValue ||
802 Previous->isOneOf(tok::r_square, tok::r_paren, tok::plusplus,
804 return addUnwrappedLine();
805 if (PreviousMustBeValue && isJSDeclOrStmt(Keywords, Next))
806 return addUnwrappedLine();
809 void UnwrappedLineParser::parseStructuralElement() {
810 assert(!FormatTok->is(tok::l_brace));
811 if (Style.Language == FormatStyle::LK_TableGen &&
812 FormatTok->is(tok::pp_include)) {
814 if (FormatTok->is(tok::string_literal))
819 switch (FormatTok->Tok.getKind()) {
822 if (FormatTok->Tok.is(tok::l_brace)) {
826 switch (FormatTok->Tok.getObjCKeywordID()) {
827 case tok::objc_public:
828 case tok::objc_protected:
829 case tok::objc_package:
830 case tok::objc_private:
831 return parseAccessSpecifier();
832 case tok::objc_interface:
833 case tok::objc_implementation:
834 return parseObjCInterfaceOrImplementation();
835 case tok::objc_protocol:
836 return parseObjCProtocol();
838 return; // Handled by the caller.
839 case tok::objc_optional:
840 case tok::objc_required:
844 case tok::objc_autoreleasepool:
846 if (FormatTok->Tok.is(tok::l_brace)) {
847 if (Style.BraceWrapping.AfterObjCDeclaration)
849 parseBlock(/*MustBeDeclaration=*/false);
854 // This branch isn't strictly necessary (the kw_try case below would
855 // do this too after the tok::at is parsed above). But be explicit.
864 if (FormatTok->is(tok::l_brace)) {
865 FormatTok->Type = TT_InlineASMBrace;
867 while (FormatTok && FormatTok->isNot(tok::eof)) {
868 if (FormatTok->is(tok::r_brace)) {
869 FormatTok->Type = TT_InlineASMBrace;
874 FormatTok->Finalized = true;
879 case tok::kw_namespace:
884 if (FormatTok->Tok.is(tok::kw_namespace)) {
890 case tok::kw_protected:
891 case tok::kw_private:
892 if (Style.Language == FormatStyle::LK_Java ||
893 Style.Language == FormatStyle::LK_JavaScript)
896 parseAccessSpecifier();
903 parseForOrWhileLoop();
911 case tok::kw_default:
924 if (FormatTok->Tok.is(tok::string_literal)) {
926 if (FormatTok->Tok.is(tok::l_brace)) {
927 parseBlock(/*MustBeDeclaration=*/true, /*AddLevel=*/false);
934 if (Style.Language == FormatStyle::LK_JavaScript) {
935 parseJavaScriptEs6ImportExport();
939 case tok::identifier:
940 if (FormatTok->is(TT_ForEachMacro)) {
941 parseForOrWhileLoop();
944 if (FormatTok->is(TT_MacroBlockBegin)) {
945 parseBlock(/*MustBeDeclaration=*/false, /*AddLevel=*/true,
946 /*MunchSemi=*/false);
949 if (FormatTok->is(Keywords.kw_import)) {
950 if (Style.Language == FormatStyle::LK_JavaScript) {
951 parseJavaScriptEs6ImportExport();
954 if (Style.Language == FormatStyle::LK_Proto) {
956 if (FormatTok->is(tok::kw_public))
958 if (!FormatTok->is(tok::string_literal))
961 if (FormatTok->is(tok::semi))
968 FormatTok->isOneOf(Keywords.kw_signals, Keywords.kw_qsignals,
969 Keywords.kw_slots, Keywords.kw_qslots)) {
971 if (FormatTok->is(tok::colon)) {
977 // In all other cases, parse the declaration.
983 const FormatToken *Previous = getPreviousToken();
984 switch (FormatTok->Tok.getKind()) {
987 if (FormatTok->Tok.is(tok::l_brace))
991 // Ignore if this is part of "template <enum ...".
992 if (Previous && Previous->is(tok::less)) {
997 // parseEnum falls through and does not yet add an unwrapped line as an
998 // enum definition can start a structural element.
1001 // This only applies for C++.
1002 if (!Style.isCpp()) {
1007 case tok::kw_typedef:
1009 if (FormatTok->isOneOf(Keywords.kw_NS_ENUM, Keywords.kw_NS_OPTIONS,
1010 Keywords.kw_CF_ENUM, Keywords.kw_CF_OPTIONS))
1013 case tok::kw_struct:
1016 // parseRecord falls through and does not yet add an unwrapped line as a
1017 // record declaration or definition can start a structural element.
1019 // This does not apply for Java and JavaScript.
1020 if (Style.Language == FormatStyle::LK_Java ||
1021 Style.Language == FormatStyle::LK_JavaScript) {
1022 if (FormatTok->is(tok::semi))
1030 // In Java, classes have an implicit static member "class".
1031 if (Style.Language == FormatStyle::LK_Java && FormatTok &&
1032 FormatTok->is(tok::kw_class))
1034 if (Style.Language == FormatStyle::LK_JavaScript && FormatTok &&
1035 FormatTok->Tok.getIdentifierInfo())
1036 // JavaScript only has pseudo keywords, all keywords are allowed to
1037 // appear in "IdentifierName" positions. See http://es5.github.io/#x7.6
1050 case tok::kw_operator:
1052 if (FormatTok->isBinaryOperator())
1057 if (FormatTok->Tok.isAnyIdentifier() ||
1058 FormatTok->isSimpleTypeSpecifier())
1060 if (FormatTok->is(tok::l_paren))
1062 if (FormatTok->is(tok::l_brace))
1066 if (!tryToParseBracedList()) {
1067 // A block outside of parentheses must be the last part of a
1068 // structural element.
1069 // FIXME: Figure out cases where this is not true, and add projections
1070 // for them (the one we know is missing are lambdas).
1071 if (Style.BraceWrapping.AfterFunction)
1073 FormatTok->Type = TT_FunctionLBrace;
1074 parseBlock(/*MustBeDeclaration=*/false);
1078 // Otherwise this was a braced init list, and the structural
1079 // element continues.
1082 // We arrive here when parsing function-try blocks.
1085 case tok::identifier: {
1086 if (FormatTok->is(TT_MacroBlockEnd)) {
1091 // Function declarations (as opposed to function expressions) are parsed
1092 // on their own unwrapped line by continuing this loop. Function
1093 // expressions (functions that are not on their own line) must not create
1094 // a new unwrapped line, so they are special cased below.
1095 size_t TokenCount = Line->Tokens.size();
1096 if (Style.Language == FormatStyle::LK_JavaScript &&
1097 FormatTok->is(Keywords.kw_function) &&
1098 (TokenCount > 1 || (TokenCount == 1 && !Line->Tokens.front().Tok->is(
1099 Keywords.kw_async)))) {
1100 tryToParseJSFunction();
1103 if ((Style.Language == FormatStyle::LK_JavaScript ||
1104 Style.Language == FormatStyle::LK_Java) &&
1105 FormatTok->is(Keywords.kw_interface)) {
1106 if (Style.Language == FormatStyle::LK_JavaScript) {
1107 // In JavaScript/TypeScript, "interface" can be used as a standalone
1108 // identifier, e.g. in `var interface = 1;`. If "interface" is
1109 // followed by another identifier, it is very like to be an actual
1110 // interface declaration.
1111 unsigned StoredPosition = Tokens->getPosition();
1112 FormatToken *Next = Tokens->getNextToken();
1113 FormatTok = Tokens->setPosition(StoredPosition);
1114 if (Next && !mustBeJSIdent(Keywords, Next)) {
1124 // See if the following token should start a new unwrapped line.
1125 StringRef Text = FormatTok->TokenText;
1127 if (Line->Tokens.size() == 1 &&
1128 // JS doesn't have macros, and within classes colons indicate fields,
1130 Style.Language != FormatStyle::LK_JavaScript) {
1131 if (FormatTok->Tok.is(tok::colon) && !Line->MustBeDeclaration) {
1132 Line->Tokens.begin()->Tok->MustBreakBefore = true;
1136 // Recognize function-like macro usages without trailing semicolon as
1137 // well as free-standing macros like Q_OBJECT.
1138 bool FunctionLike = FormatTok->is(tok::l_paren);
1142 bool FollowedByNewline =
1143 CommentsBeforeNextToken.empty()
1144 ? FormatTok->NewlinesBefore > 0
1145 : CommentsBeforeNextToken.front()->NewlinesBefore > 0;
1147 if (FollowedByNewline && (Text.size() >= 5 || FunctionLike) &&
1148 tokenCanStartNewLine(FormatTok->Tok) && Text == Text.upper()) {
1156 // Fat arrows (=>) have tok::TokenKind tok::equal but TokenType
1157 // TT_JsFatArrow. The always start an expression or a child block if
1158 // followed by a curly.
1159 if (FormatTok->is(TT_JsFatArrow)) {
1161 if (FormatTok->is(tok::l_brace))
1167 if (FormatTok->Tok.is(tok::l_brace)) {
1184 bool UnwrappedLineParser::tryToParseLambda() {
1185 if (!Style.isCpp()) {
1189 const FormatToken* Previous = getPreviousToken();
1191 (Previous->isOneOf(tok::identifier, tok::kw_operator, tok::kw_new,
1193 Previous->closesScope() || Previous->isSimpleTypeSpecifier())) {
1197 assert(FormatTok->is(tok::l_square));
1198 FormatToken &LSquare = *FormatTok;
1199 if (!tryToParseLambdaIntroducer())
1202 while (FormatTok->isNot(tok::l_brace)) {
1203 if (FormatTok->isSimpleTypeSpecifier()) {
1207 switch (FormatTok->Tok.getKind()) {
1219 case tok::identifier:
1220 case tok::numeric_constant:
1221 case tok::coloncolon:
1222 case tok::kw_mutable:
1226 FormatTok->Type = TT_LambdaArrow;
1233 LSquare.Type = TT_LambdaLSquare;
1238 bool UnwrappedLineParser::tryToParseLambdaIntroducer() {
1240 if (FormatTok->is(tok::equal)) {
1242 if (FormatTok->is(tok::r_square)) {
1246 if (FormatTok->isNot(tok::comma))
1249 } else if (FormatTok->is(tok::amp)) {
1251 if (FormatTok->is(tok::r_square)) {
1255 if (!FormatTok->isOneOf(tok::comma, tok::identifier)) {
1258 if (FormatTok->is(tok::comma))
1260 } else if (FormatTok->is(tok::r_square)) {
1265 if (FormatTok->is(tok::amp))
1267 if (!FormatTok->isOneOf(tok::identifier, tok::kw_this))
1270 if (FormatTok->is(tok::ellipsis))
1272 if (FormatTok->is(tok::comma)) {
1274 } else if (FormatTok->is(tok::r_square)) {
1284 void UnwrappedLineParser::tryToParseJSFunction() {
1285 assert(FormatTok->is(Keywords.kw_function) ||
1286 FormatTok->startsSequence(Keywords.kw_async, Keywords.kw_function));
1287 if (FormatTok->is(Keywords.kw_async))
1289 // Consume "function".
1292 // Consume * (generator function). Treat it like C++'s overloaded operators.
1293 if (FormatTok->is(tok::star)) {
1294 FormatTok->Type = TT_OverloadedOperator;
1298 // Consume function name.
1299 if (FormatTok->is(tok::identifier))
1302 if (FormatTok->isNot(tok::l_paren))
1305 // Parse formal parameter list.
1308 if (FormatTok->is(tok::colon)) {
1309 // Parse a type definition.
1312 // Eat the type declaration. For braced inline object types, balance braces,
1313 // otherwise just parse until finding an l_brace for the function body.
1314 if (FormatTok->is(tok::l_brace))
1315 tryToParseBracedList();
1317 while (!FormatTok->isOneOf(tok::l_brace, tok::semi) && !eof())
1321 if (FormatTok->is(tok::semi))
1327 bool UnwrappedLineParser::tryToParseBracedList() {
1328 if (FormatTok->BlockKind == BK_Unknown)
1329 calculateBraceTypes();
1330 assert(FormatTok->BlockKind != BK_Unknown);
1331 if (FormatTok->BlockKind == BK_Block)
1337 bool UnwrappedLineParser::parseBracedList(bool ContinueOnSemicolons) {
1338 bool HasError = false;
1341 // FIXME: Once we have an expression parser in the UnwrappedLineParser,
1342 // replace this by using parseAssigmentExpression() inside.
1344 if (Style.Language == FormatStyle::LK_JavaScript) {
1345 if (FormatTok->is(Keywords.kw_function) ||
1346 FormatTok->startsSequence(Keywords.kw_async, Keywords.kw_function)) {
1347 tryToParseJSFunction();
1350 if (FormatTok->is(TT_JsFatArrow)) {
1352 // Fat arrows can be followed by simple expressions or by child blocks
1354 if (FormatTok->is(tok::l_brace)) {
1359 if (FormatTok->is(tok::l_brace)) {
1360 // Could be a method inside of a braced list `{a() { return 1; }}`.
1361 if (tryToParseBracedList())
1366 switch (FormatTok->Tok.getKind()) {
1369 if (FormatTok->is(tok::l_brace)) {
1378 // JavaScript can just have free standing methods and getters/setters in
1379 // object literals. Detect them by a "{" following ")".
1380 if (Style.Language == FormatStyle::LK_JavaScript) {
1381 if (FormatTok->is(tok::l_brace))
1387 // Assume there are no blocks inside a braced init list apart
1388 // from the ones we explicitly parse out (like lambdas).
1389 FormatTok->BlockKind = BK_BracedInit;
1396 // JavaScript (or more precisely TypeScript) can have semicolons in braced
1397 // lists (in so-called TypeMemberLists). Thus, the semicolon cannot be
1398 // used for error recovery if we have otherwise determined that this is
1400 if (Style.Language == FormatStyle::LK_JavaScript) {
1405 if (!ContinueOnSemicolons)
1420 void UnwrappedLineParser::parseParens() {
1421 assert(FormatTok->Tok.is(tok::l_paren) && "'(' expected.");
1424 switch (FormatTok->Tok.getKind()) {
1427 if (Style.Language == FormatStyle::LK_Java && FormatTok->is(tok::l_brace))
1434 // A "}" inside parenthesis is an error if there wasn't a matching "{".
1440 if (!tryToParseBracedList())
1445 if (FormatTok->Tok.is(tok::l_brace))
1449 if (Style.Language == FormatStyle::LK_JavaScript)
1450 parseRecord(/*ParseAsExpr=*/true);
1454 case tok::identifier:
1455 if (Style.Language == FormatStyle::LK_JavaScript &&
1456 (FormatTok->is(Keywords.kw_function) ||
1457 FormatTok->startsSequence(Keywords.kw_async, Keywords.kw_function)))
1458 tryToParseJSFunction();
1469 void UnwrappedLineParser::parseSquare() {
1470 assert(FormatTok->Tok.is(tok::l_square) && "'[' expected.");
1471 if (tryToParseLambda())
1474 switch (FormatTok->Tok.getKind()) {
1482 // A "}" inside parenthesis is an error if there wasn't a matching "{".
1487 case tok::l_brace: {
1488 if (!tryToParseBracedList())
1494 if (FormatTok->Tok.is(tok::l_brace))
1504 void UnwrappedLineParser::parseIfThenElse() {
1505 assert(FormatTok->Tok.is(tok::kw_if) && "'if' expected");
1507 if (FormatTok->Tok.is(tok::l_paren))
1509 bool NeedsUnwrappedLine = false;
1510 if (FormatTok->Tok.is(tok::l_brace)) {
1511 CompoundStatementIndenter Indenter(this, Style, Line->Level);
1512 parseBlock(/*MustBeDeclaration=*/false);
1513 if (Style.BraceWrapping.BeforeElse)
1516 NeedsUnwrappedLine = true;
1520 parseStructuralElement();
1523 if (FormatTok->Tok.is(tok::kw_else)) {
1525 if (FormatTok->Tok.is(tok::l_brace)) {
1526 CompoundStatementIndenter Indenter(this, Style, Line->Level);
1527 parseBlock(/*MustBeDeclaration=*/false);
1529 } else if (FormatTok->Tok.is(tok::kw_if)) {
1534 parseStructuralElement();
1535 if (FormatTok->is(tok::eof))
1539 } else if (NeedsUnwrappedLine) {
1544 void UnwrappedLineParser::parseTryCatch() {
1545 assert(FormatTok->isOneOf(tok::kw_try, tok::kw___try) && "'try' expected");
1547 bool NeedsUnwrappedLine = false;
1548 if (FormatTok->is(tok::colon)) {
1549 // We are in a function try block, what comes is an initializer list.
1551 while (FormatTok->is(tok::identifier)) {
1553 if (FormatTok->is(tok::l_paren))
1555 if (FormatTok->is(tok::comma))
1559 // Parse try with resource.
1560 if (Style.Language == FormatStyle::LK_Java && FormatTok->is(tok::l_paren)) {
1563 if (FormatTok->is(tok::l_brace)) {
1564 CompoundStatementIndenter Indenter(this, Style, Line->Level);
1565 parseBlock(/*MustBeDeclaration=*/false);
1566 if (Style.BraceWrapping.BeforeCatch) {
1569 NeedsUnwrappedLine = true;
1571 } else if (!FormatTok->is(tok::kw_catch)) {
1572 // The C++ standard requires a compound-statement after a try.
1573 // If there's none, we try to assume there's a structuralElement
1574 // and try to continue.
1577 parseStructuralElement();
1581 if (FormatTok->is(tok::at))
1583 if (!(FormatTok->isOneOf(tok::kw_catch, Keywords.kw___except,
1584 tok::kw___finally) ||
1585 ((Style.Language == FormatStyle::LK_Java ||
1586 Style.Language == FormatStyle::LK_JavaScript) &&
1587 FormatTok->is(Keywords.kw_finally)) ||
1588 (FormatTok->Tok.isObjCAtKeyword(tok::objc_catch) ||
1589 FormatTok->Tok.isObjCAtKeyword(tok::objc_finally))))
1592 while (FormatTok->isNot(tok::l_brace)) {
1593 if (FormatTok->is(tok::l_paren)) {
1597 if (FormatTok->isOneOf(tok::semi, tok::r_brace, tok::eof))
1601 NeedsUnwrappedLine = false;
1602 CompoundStatementIndenter Indenter(this, Style, Line->Level);
1603 parseBlock(/*MustBeDeclaration=*/false);
1604 if (Style.BraceWrapping.BeforeCatch)
1607 NeedsUnwrappedLine = true;
1609 if (NeedsUnwrappedLine)
1613 void UnwrappedLineParser::parseNamespace() {
1614 assert(FormatTok->Tok.is(tok::kw_namespace) && "'namespace' expected");
1616 const FormatToken &InitialToken = *FormatTok;
1618 while (FormatTok->isOneOf(tok::identifier, tok::coloncolon))
1620 if (FormatTok->Tok.is(tok::l_brace)) {
1621 if (ShouldBreakBeforeBrace(Style, InitialToken))
1624 bool AddLevel = Style.NamespaceIndentation == FormatStyle::NI_All ||
1625 (Style.NamespaceIndentation == FormatStyle::NI_Inner &&
1626 DeclarationScopeStack.size() > 1);
1627 parseBlock(/*MustBeDeclaration=*/true, AddLevel);
1628 // Munch the semicolon after a namespace. This is more common than one would
1629 // think. Puttin the semicolon into its own line is very ugly.
1630 if (FormatTok->Tok.is(tok::semi))
1634 // FIXME: Add error handling.
1637 void UnwrappedLineParser::parseNew() {
1638 assert(FormatTok->is(tok::kw_new) && "'new' expected");
1640 if (Style.Language != FormatStyle::LK_Java)
1643 // In Java, we can parse everything up to the parens, which aren't optional.
1645 // There should not be a ;, { or } before the new's open paren.
1646 if (FormatTok->isOneOf(tok::semi, tok::l_brace, tok::r_brace))
1649 // Consume the parens.
1650 if (FormatTok->is(tok::l_paren)) {
1653 // If there is a class body of an anonymous class, consume that as child.
1654 if (FormatTok->is(tok::l_brace))
1662 void UnwrappedLineParser::parseForOrWhileLoop() {
1663 assert(FormatTok->isOneOf(tok::kw_for, tok::kw_while, TT_ForEachMacro) &&
1664 "'for', 'while' or foreach macro expected");
1666 // JS' for await ( ...
1667 if (Style.Language == FormatStyle::LK_JavaScript &&
1668 FormatTok->is(Keywords.kw_await))
1670 if (FormatTok->Tok.is(tok::l_paren))
1672 if (FormatTok->Tok.is(tok::l_brace)) {
1673 CompoundStatementIndenter Indenter(this, Style, Line->Level);
1674 parseBlock(/*MustBeDeclaration=*/false);
1679 parseStructuralElement();
1684 void UnwrappedLineParser::parseDoWhile() {
1685 assert(FormatTok->Tok.is(tok::kw_do) && "'do' expected");
1687 if (FormatTok->Tok.is(tok::l_brace)) {
1688 CompoundStatementIndenter Indenter(this, Style, Line->Level);
1689 parseBlock(/*MustBeDeclaration=*/false);
1690 if (Style.BraceWrapping.IndentBraces)
1695 parseStructuralElement();
1699 // FIXME: Add error handling.
1700 if (!FormatTok->Tok.is(tok::kw_while)) {
1706 parseStructuralElement();
1709 void UnwrappedLineParser::parseLabel() {
1711 unsigned OldLineLevel = Line->Level;
1712 if (Line->Level > 1 || (!Line->InPPDirective && Line->Level > 0))
1714 if (CommentsBeforeNextToken.empty() && FormatTok->Tok.is(tok::l_brace)) {
1715 CompoundStatementIndenter Indenter(this, Style, Line->Level);
1716 parseBlock(/*MustBeDeclaration=*/false);
1717 if (FormatTok->Tok.is(tok::kw_break)) {
1718 if (Style.BraceWrapping.AfterControlStatement)
1720 parseStructuralElement();
1724 if (FormatTok->is(tok::semi))
1728 Line->Level = OldLineLevel;
1729 if (FormatTok->isNot(tok::l_brace)) {
1730 parseStructuralElement();
1735 void UnwrappedLineParser::parseCaseLabel() {
1736 assert(FormatTok->Tok.is(tok::kw_case) && "'case' expected");
1737 // FIXME: fix handling of complex expressions here.
1740 } while (!eof() && !FormatTok->Tok.is(tok::colon));
1744 void UnwrappedLineParser::parseSwitch() {
1745 assert(FormatTok->Tok.is(tok::kw_switch) && "'switch' expected");
1747 if (FormatTok->Tok.is(tok::l_paren))
1749 if (FormatTok->Tok.is(tok::l_brace)) {
1750 CompoundStatementIndenter Indenter(this, Style, Line->Level);
1751 parseBlock(/*MustBeDeclaration=*/false);
1756 parseStructuralElement();
1761 void UnwrappedLineParser::parseAccessSpecifier() {
1763 // Understand Qt's slots.
1764 if (FormatTok->isOneOf(Keywords.kw_slots, Keywords.kw_qslots))
1766 // Otherwise, we don't know what it is, and we'd better keep the next token.
1767 if (FormatTok->Tok.is(tok::colon))
1772 bool UnwrappedLineParser::parseEnum() {
1773 // Won't be 'enum' for NS_ENUMs.
1774 if (FormatTok->Tok.is(tok::kw_enum))
1777 // In TypeScript, "enum" can also be used as property name, e.g. in interface
1778 // declarations. An "enum" keyword followed by a colon would be a syntax
1779 // error and thus assume it is just an identifier.
1780 if (Style.Language == FormatStyle::LK_JavaScript &&
1781 FormatTok->isOneOf(tok::colon, tok::question))
1784 // Eat up enum class ...
1785 if (FormatTok->Tok.is(tok::kw_class) || FormatTok->Tok.is(tok::kw_struct))
1788 while (FormatTok->Tok.getIdentifierInfo() ||
1789 FormatTok->isOneOf(tok::colon, tok::coloncolon, tok::less,
1790 tok::greater, tok::comma, tok::question)) {
1792 // We can have macros or attributes in between 'enum' and the enum name.
1793 if (FormatTok->is(tok::l_paren))
1795 if (FormatTok->is(tok::identifier)) {
1797 // If there are two identifiers in a row, this is likely an elaborate
1798 // return type. In Java, this can be "implements", etc.
1799 if (Style.isCpp() && FormatTok->is(tok::identifier))
1804 // Just a declaration or something is wrong.
1805 if (FormatTok->isNot(tok::l_brace))
1807 FormatTok->BlockKind = BK_Block;
1809 if (Style.Language == FormatStyle::LK_Java) {
1810 // Java enums are different.
1811 parseJavaEnumBody();
1814 if (Style.Language == FormatStyle::LK_Proto) {
1815 parseBlock(/*MustBeDeclaration=*/true);
1820 bool HasError = !parseBracedList(/*ContinueOnSemicolons=*/true);
1822 if (FormatTok->is(tok::semi))
1828 // There is no addUnwrappedLine() here so that we fall through to parsing a
1829 // structural element afterwards. Thus, in "enum A {} n, m;",
1830 // "} n, m;" will end up in one unwrapped line.
1833 void UnwrappedLineParser::parseJavaEnumBody() {
1834 // Determine whether the enum is simple, i.e. does not have a semicolon or
1835 // constants with class bodies. Simple enums can be formatted like braced
1836 // lists, contracted to a single line, etc.
1837 unsigned StoredPosition = Tokens->getPosition();
1838 bool IsSimple = true;
1839 FormatToken *Tok = Tokens->getNextToken();
1841 if (Tok->is(tok::r_brace))
1843 if (Tok->isOneOf(tok::l_brace, tok::semi)) {
1847 // FIXME: This will also mark enums with braces in the arguments to enum
1848 // constants as "not simple". This is probably fine in practice, though.
1849 Tok = Tokens->getNextToken();
1851 FormatTok = Tokens->setPosition(StoredPosition);
1859 // Parse the body of a more complex enum.
1860 // First add a line for everything up to the "{".
1865 // Parse the enum constants.
1867 if (FormatTok->is(tok::l_brace)) {
1868 // Parse the constant's class body.
1869 parseBlock(/*MustBeDeclaration=*/true, /*AddLevel=*/true,
1870 /*MunchSemi=*/false);
1871 } else if (FormatTok->is(tok::l_paren)) {
1873 } else if (FormatTok->is(tok::comma)) {
1876 } else if (FormatTok->is(tok::semi)) {
1880 } else if (FormatTok->is(tok::r_brace)) {
1888 // Parse the class body after the enum's ";" if any.
1889 parseLevel(/*HasOpeningBrace=*/true);
1895 void UnwrappedLineParser::parseRecord(bool ParseAsExpr) {
1896 const FormatToken &InitialToken = *FormatTok;
1899 // The actual identifier can be a nested name specifier, and in macros
1900 // it is often token-pasted.
1901 while (FormatTok->isOneOf(tok::identifier, tok::coloncolon, tok::hashhash,
1902 tok::kw___attribute, tok::kw___declspec,
1904 ((Style.Language == FormatStyle::LK_Java ||
1905 Style.Language == FormatStyle::LK_JavaScript) &&
1906 FormatTok->isOneOf(tok::period, tok::comma))) {
1907 bool IsNonMacroIdentifier =
1908 FormatTok->is(tok::identifier) &&
1909 FormatTok->TokenText != FormatTok->TokenText.upper();
1911 // We can have macros or attributes in between 'class' and the class name.
1912 if (!IsNonMacroIdentifier && FormatTok->Tok.is(tok::l_paren))
1916 // Note that parsing away template declarations here leads to incorrectly
1917 // accepting function declarations as record declarations.
1918 // In general, we cannot solve this problem. Consider:
1919 // class A<int> B() {}
1920 // which can be a function definition or a class definition when B() is a
1921 // macro. If we find enough real-world cases where this is a problem, we
1922 // can parse for the 'template' keyword in the beginning of the statement,
1923 // and thus rule out the record production in case there is no template
1924 // (this would still leave us with an ambiguity between template function
1925 // and class declarations).
1926 if (FormatTok->isOneOf(tok::colon, tok::less)) {
1928 if (FormatTok->is(tok::l_brace)) {
1929 calculateBraceTypes(/*ExpectClassBody=*/true);
1930 if (!tryToParseBracedList())
1933 if (FormatTok->Tok.is(tok::semi))
1938 if (FormatTok->Tok.is(tok::l_brace)) {
1942 if (ShouldBreakBeforeBrace(Style, InitialToken))
1945 parseBlock(/*MustBeDeclaration=*/true, /*AddLevel=*/true,
1946 /*MunchSemi=*/false);
1949 // There is no addUnwrappedLine() here so that we fall through to parsing a
1950 // structural element afterwards. Thus, in "class A {} n, m;",
1951 // "} n, m;" will end up in one unwrapped line.
1954 void UnwrappedLineParser::parseObjCProtocolList() {
1955 assert(FormatTok->Tok.is(tok::less) && "'<' expected.");
1958 while (!eof() && FormatTok->Tok.isNot(tok::greater));
1959 nextToken(); // Skip '>'.
1962 void UnwrappedLineParser::parseObjCUntilAtEnd() {
1964 if (FormatTok->Tok.isObjCAtKeyword(tok::objc_end)) {
1969 if (FormatTok->is(tok::l_brace)) {
1970 parseBlock(/*MustBeDeclaration=*/false);
1971 // In ObjC interfaces, nothing should be following the "}".
1973 } else if (FormatTok->is(tok::r_brace)) {
1974 // Ignore stray "}". parseStructuralElement doesn't consume them.
1978 parseStructuralElement();
1983 void UnwrappedLineParser::parseObjCInterfaceOrImplementation() {
1985 nextToken(); // interface name
1987 // @interface can be followed by either a base class, or a category.
1988 if (FormatTok->Tok.is(tok::colon)) {
1990 nextToken(); // base class name
1991 } else if (FormatTok->Tok.is(tok::l_paren))
1992 // Skip category, if present.
1995 if (FormatTok->Tok.is(tok::less))
1996 parseObjCProtocolList();
1998 if (FormatTok->Tok.is(tok::l_brace)) {
1999 if (Style.BraceWrapping.AfterObjCDeclaration)
2001 parseBlock(/*MustBeDeclaration=*/true);
2004 // With instance variables, this puts '}' on its own line. Without instance
2005 // variables, this ends the @interface line.
2008 parseObjCUntilAtEnd();
2011 void UnwrappedLineParser::parseObjCProtocol() {
2013 nextToken(); // protocol name
2015 if (FormatTok->Tok.is(tok::less))
2016 parseObjCProtocolList();
2018 // Check for protocol declaration.
2019 if (FormatTok->Tok.is(tok::semi)) {
2021 return addUnwrappedLine();
2025 parseObjCUntilAtEnd();
2028 void UnwrappedLineParser::parseJavaScriptEs6ImportExport() {
2029 bool IsImport = FormatTok->is(Keywords.kw_import);
2030 assert(IsImport || FormatTok->is(tok::kw_export));
2033 // Consume the "default" in "export default class/function".
2034 if (FormatTok->is(tok::kw_default))
2037 // Consume "async function", "function" and "default function", so that these
2038 // get parsed as free-standing JS functions, i.e. do not require a trailing
2040 if (FormatTok->is(Keywords.kw_async))
2042 if (FormatTok->is(Keywords.kw_function)) {
2047 // For imports, `export *`, `export {...}`, consume the rest of the line up
2048 // to the terminating `;`. For everything else, just return and continue
2049 // parsing the structural element, i.e. the declaration or expression for
2050 // `export default`.
2051 if (!IsImport && !FormatTok->isOneOf(tok::l_brace, tok::star) &&
2052 !FormatTok->isStringLiteral())
2056 if (FormatTok->is(tok::semi))
2058 if (Line->Tokens.size() == 0) {
2059 // Common issue: Automatic Semicolon Insertion wrapped the line, so the
2060 // import statement should terminate.
2063 if (FormatTok->is(tok::l_brace)) {
2064 FormatTok->BlockKind = BK_Block;
2072 LLVM_ATTRIBUTE_UNUSED static void printDebugInfo(const UnwrappedLine &Line,
2073 StringRef Prefix = "") {
2074 llvm::dbgs() << Prefix << "Line(" << Line.Level << ")"
2075 << (Line.InPPDirective ? " MACRO" : "") << ": ";
2076 for (std::list<UnwrappedLineNode>::const_iterator I = Line.Tokens.begin(),
2077 E = Line.Tokens.end();
2079 llvm::dbgs() << I->Tok->Tok.getName() << "["
2080 << "T=" << I->Tok->Type
2081 << ", OC=" << I->Tok->OriginalColumn << "] ";
2083 for (std::list<UnwrappedLineNode>::const_iterator I = Line.Tokens.begin(),
2084 E = Line.Tokens.end();
2086 const UnwrappedLineNode &Node = *I;
2087 for (SmallVectorImpl<UnwrappedLine>::const_iterator
2088 I = Node.Children.begin(),
2089 E = Node.Children.end();
2091 printDebugInfo(*I, "\nChild: ");
2094 llvm::dbgs() << "\n";
2097 void UnwrappedLineParser::addUnwrappedLine() {
2098 if (Line->Tokens.empty())
2101 if (CurrentLines == &Lines)
2102 printDebugInfo(*Line);
2104 CurrentLines->push_back(std::move(*Line));
2105 Line->Tokens.clear();
2106 Line->MatchingOpeningBlockLineIndex = UnwrappedLine::kInvalidIndex;
2107 if (CurrentLines == &Lines && !PreprocessorDirectives.empty()) {
2108 CurrentLines->append(
2109 std::make_move_iterator(PreprocessorDirectives.begin()),
2110 std::make_move_iterator(PreprocessorDirectives.end()));
2111 PreprocessorDirectives.clear();
2115 bool UnwrappedLineParser::eof() const { return FormatTok->Tok.is(tok::eof); }
2117 bool UnwrappedLineParser::isOnNewLine(const FormatToken &FormatTok) {
2118 return (Line->InPPDirective || FormatTok.HasUnescapedNewline) &&
2119 FormatTok.NewlinesBefore > 0;
2122 // Checks if \p FormatTok is a line comment that continues the line comment
2123 // section on \p Line.
2124 static bool continuesLineCommentSection(const FormatToken &FormatTok,
2125 const UnwrappedLine &Line,
2126 llvm::Regex &CommentPragmasRegex) {
2127 if (Line.Tokens.empty())
2130 StringRef IndentContent = FormatTok.TokenText;
2131 if (FormatTok.TokenText.startswith("//") ||
2132 FormatTok.TokenText.startswith("/*"))
2133 IndentContent = FormatTok.TokenText.substr(2);
2134 if (CommentPragmasRegex.match(IndentContent))
2137 // If Line starts with a line comment, then FormatTok continues the comment
2138 // section if its original column is greater or equal to the original start
2139 // column of the line.
2141 // Define the min column token of a line as follows: if a line ends in '{' or
2142 // contains a '{' followed by a line comment, then the min column token is
2143 // that '{'. Otherwise, the min column token of the line is the first token of
2146 // If Line starts with a token other than a line comment, then FormatTok
2147 // continues the comment section if its original column is greater than the
2148 // original start column of the min column token of the line.
2150 // For example, the second line comment continues the first in these cases:
2162 // int i; // first line
2167 // do { // first line
2180 // The second line comment doesn't continue the first in these cases:
2187 // int i; // first line
2192 // do { // first line
2203 const FormatToken *MinColumnToken = Line.Tokens.front().Tok;
2205 // Scan for '{//'. If found, use the column of '{' as a min column for line
2206 // comment section continuation.
2207 const FormatToken *PreviousToken = nullptr;
2208 for (const UnwrappedLineNode &Node : Line.Tokens) {
2209 if (PreviousToken && PreviousToken->is(tok::l_brace) &&
2210 isLineComment(*Node.Tok)) {
2211 MinColumnToken = PreviousToken;
2214 PreviousToken = Node.Tok;
2216 // Grab the last newline preceding a token in this unwrapped line.
2217 if (Node.Tok->NewlinesBefore > 0) {
2218 MinColumnToken = Node.Tok;
2221 if (PreviousToken && PreviousToken->is(tok::l_brace)) {
2222 MinColumnToken = PreviousToken;
2225 return continuesLineComment(FormatTok, /*Previous=*/Line.Tokens.back().Tok,
2229 void UnwrappedLineParser::flushComments(bool NewlineBeforeNext) {
2230 bool JustComments = Line->Tokens.empty();
2231 for (SmallVectorImpl<FormatToken *>::const_iterator
2232 I = CommentsBeforeNextToken.begin(),
2233 E = CommentsBeforeNextToken.end();
2235 // Line comments that belong to the same line comment section are put on the
2236 // same line since later we might want to reflow content between them.
2237 // Additional fine-grained breaking of line comment sections is controlled
2238 // by the class BreakableLineCommentSection in case it is desirable to keep
2239 // several line comment sections in the same unwrapped line.
2241 // FIXME: Consider putting separate line comment sections as children to the
2242 // unwrapped line instead.
2243 (*I)->ContinuesLineCommentSection =
2244 continuesLineCommentSection(**I, *Line, CommentPragmasRegex);
2245 if (isOnNewLine(**I) && JustComments && !(*I)->ContinuesLineCommentSection)
2249 if (NewlineBeforeNext && JustComments)
2251 CommentsBeforeNextToken.clear();
2254 void UnwrappedLineParser::nextToken() {
2257 flushComments(isOnNewLine(*FormatTok));
2258 pushToken(FormatTok);
2259 if (Style.Language != FormatStyle::LK_JavaScript)
2262 readTokenWithJavaScriptASI();
2265 const FormatToken *UnwrappedLineParser::getPreviousToken() {
2266 // FIXME: This is a dirty way to access the previous token. Find a better
2268 if (!Line || Line->Tokens.empty())
2270 return Line->Tokens.back().Tok;
2273 void UnwrappedLineParser::distributeComments(
2274 const SmallVectorImpl<FormatToken *> &Comments,
2275 const FormatToken *NextTok) {
2276 // Whether or not a line comment token continues a line is controlled by
2277 // the method continuesLineCommentSection, with the following caveat:
2279 // Define a trail of Comments to be a nonempty proper postfix of Comments such
2280 // that each comment line from the trail is aligned with the next token, if
2281 // the next token exists. If a trail exists, the beginning of the maximal
2282 // trail is marked as a start of a new comment section.
2284 // For example in this code:
2286 // int a; // line about a
2287 // // line 1 about b
2288 // // line 2 about b
2291 // the two lines about b form a maximal trail, so there are two sections, the
2292 // first one consisting of the single comment "// line about a" and the
2293 // second one consisting of the next two comments.
2294 if (Comments.empty())
2296 bool ShouldPushCommentsInCurrentLine = true;
2297 bool HasTrailAlignedWithNextToken = false;
2298 unsigned StartOfTrailAlignedWithNextToken = 0;
2300 // We are skipping the first element intentionally.
2301 for (unsigned i = Comments.size() - 1; i > 0; --i) {
2302 if (Comments[i]->OriginalColumn == NextTok->OriginalColumn) {
2303 HasTrailAlignedWithNextToken = true;
2304 StartOfTrailAlignedWithNextToken = i;
2308 for (unsigned i = 0, e = Comments.size(); i < e; ++i) {
2309 FormatToken *FormatTok = Comments[i];
2310 if (HasTrailAlignedWithNextToken &&
2311 i == StartOfTrailAlignedWithNextToken) {
2312 FormatTok->ContinuesLineCommentSection = false;
2314 FormatTok->ContinuesLineCommentSection =
2315 continuesLineCommentSection(*FormatTok, *Line, CommentPragmasRegex);
2317 if (!FormatTok->ContinuesLineCommentSection &&
2318 (isOnNewLine(*FormatTok) || FormatTok->IsFirst)) {
2319 ShouldPushCommentsInCurrentLine = false;
2321 if (ShouldPushCommentsInCurrentLine) {
2322 pushToken(FormatTok);
2324 CommentsBeforeNextToken.push_back(FormatTok);
2329 void UnwrappedLineParser::readToken() {
2330 SmallVector<FormatToken *, 1> Comments;
2332 FormatTok = Tokens->getNextToken();
2334 while (!Line->InPPDirective && FormatTok->Tok.is(tok::hash) &&
2335 (FormatTok->HasUnescapedNewline || FormatTok->IsFirst)) {
2336 distributeComments(Comments, FormatTok);
2338 // If there is an unfinished unwrapped line, we flush the preprocessor
2339 // directives only after that unwrapped line was finished later.
2340 bool SwitchToPreprocessorLines = !Line->Tokens.empty();
2341 ScopedLineState BlockState(*this, SwitchToPreprocessorLines);
2342 // Comments stored before the preprocessor directive need to be output
2343 // before the preprocessor directive, at the same level as the
2344 // preprocessor directive, as we consider them to apply to the directive.
2345 flushComments(isOnNewLine(*FormatTok));
2348 while (FormatTok->Type == TT_ConflictStart ||
2349 FormatTok->Type == TT_ConflictEnd ||
2350 FormatTok->Type == TT_ConflictAlternative) {
2351 if (FormatTok->Type == TT_ConflictStart) {
2352 conditionalCompilationStart(/*Unreachable=*/false);
2353 } else if (FormatTok->Type == TT_ConflictAlternative) {
2354 conditionalCompilationAlternative();
2355 } else if (FormatTok->Type == TT_ConflictEnd) {
2356 conditionalCompilationEnd();
2358 FormatTok = Tokens->getNextToken();
2359 FormatTok->MustBreakBefore = true;
2362 if (!PPStack.empty() && (PPStack.back() == PP_Unreachable) &&
2363 !Line->InPPDirective) {
2367 if (!FormatTok->Tok.is(tok::comment)) {
2368 distributeComments(Comments, FormatTok);
2373 Comments.push_back(FormatTok);
2376 distributeComments(Comments, nullptr);
2380 void UnwrappedLineParser::pushToken(FormatToken *Tok) {
2381 Line->Tokens.push_back(UnwrappedLineNode(Tok));
2382 if (MustBreakBeforeNextToken) {
2383 Line->Tokens.back().Tok->MustBreakBefore = true;
2384 MustBreakBeforeNextToken = false;
2388 } // end namespace format
2389 } // end namespace clang