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 class ScopedMacroState : public FormatTokenSource {
60 ScopedMacroState(UnwrappedLine &Line, FormatTokenSource *&TokenSource,
61 FormatToken *&ResetToken)
62 : Line(Line), TokenSource(TokenSource), ResetToken(ResetToken),
63 PreviousLineLevel(Line.Level), PreviousTokenSource(TokenSource),
67 Line.InPPDirective = true;
70 ~ScopedMacroState() override {
71 TokenSource = PreviousTokenSource;
73 Line.InPPDirective = false;
74 Line.Level = PreviousLineLevel;
77 FormatToken *getNextToken() override {
78 // The \c UnwrappedLineParser guards against this by never calling
79 // \c getNextToken() after it has encountered the first eof token.
81 Token = PreviousTokenSource->getNextToken();
87 unsigned getPosition() override { return PreviousTokenSource->getPosition(); }
89 FormatToken *setPosition(unsigned Position) override {
90 Token = PreviousTokenSource->setPosition(Position);
95 bool eof() { return Token && Token->HasUnescapedNewline; }
97 FormatToken *getFakeEOF() {
98 static bool EOFInitialized = false;
99 static FormatToken FormatTok;
100 if (!EOFInitialized) {
101 FormatTok.Tok.startToken();
102 FormatTok.Tok.setKind(tok::eof);
103 EOFInitialized = true;
109 FormatTokenSource *&TokenSource;
110 FormatToken *&ResetToken;
111 unsigned PreviousLineLevel;
112 FormatTokenSource *PreviousTokenSource;
117 } // end anonymous namespace
119 class ScopedLineState {
121 ScopedLineState(UnwrappedLineParser &Parser,
122 bool SwitchToPreprocessorLines = false)
123 : Parser(Parser), OriginalLines(Parser.CurrentLines) {
124 if (SwitchToPreprocessorLines)
125 Parser.CurrentLines = &Parser.PreprocessorDirectives;
126 else if (!Parser.Line->Tokens.empty())
127 Parser.CurrentLines = &Parser.Line->Tokens.back().Children;
128 PreBlockLine = std::move(Parser.Line);
129 Parser.Line = llvm::make_unique<UnwrappedLine>();
130 Parser.Line->Level = PreBlockLine->Level;
131 Parser.Line->InPPDirective = PreBlockLine->InPPDirective;
135 if (!Parser.Line->Tokens.empty()) {
136 Parser.addUnwrappedLine();
138 assert(Parser.Line->Tokens.empty());
139 Parser.Line = std::move(PreBlockLine);
140 if (Parser.CurrentLines == &Parser.PreprocessorDirectives)
141 Parser.MustBreakBeforeNextToken = true;
142 Parser.CurrentLines = OriginalLines;
146 UnwrappedLineParser &Parser;
148 std::unique_ptr<UnwrappedLine> PreBlockLine;
149 SmallVectorImpl<UnwrappedLine> *OriginalLines;
152 class CompoundStatementIndenter {
154 CompoundStatementIndenter(UnwrappedLineParser *Parser,
155 const FormatStyle &Style, unsigned &LineLevel)
156 : LineLevel(LineLevel), OldLineLevel(LineLevel) {
157 if (Style.BraceWrapping.AfterControlStatement)
158 Parser->addUnwrappedLine();
159 if (Style.BraceWrapping.IndentBraces)
162 ~CompoundStatementIndenter() { LineLevel = OldLineLevel; }
166 unsigned OldLineLevel;
171 class IndexedTokenSource : public FormatTokenSource {
173 IndexedTokenSource(ArrayRef<FormatToken *> Tokens)
174 : Tokens(Tokens), Position(-1) {}
176 FormatToken *getNextToken() override {
178 return Tokens[Position];
181 unsigned getPosition() override {
182 assert(Position >= 0);
186 FormatToken *setPosition(unsigned P) override {
188 return Tokens[Position];
191 void reset() { Position = -1; }
194 ArrayRef<FormatToken *> Tokens;
198 } // end anonymous namespace
200 UnwrappedLineParser::UnwrappedLineParser(const FormatStyle &Style,
201 const AdditionalKeywords &Keywords,
202 ArrayRef<FormatToken *> Tokens,
203 UnwrappedLineConsumer &Callback)
204 : Line(new UnwrappedLine), MustBreakBeforeNextToken(false),
205 CurrentLines(&Lines), Style(Style), Keywords(Keywords), Tokens(nullptr),
206 Callback(Callback), AllTokens(Tokens), PPBranchLevel(-1) {}
208 void UnwrappedLineParser::reset() {
210 Line.reset(new UnwrappedLine);
211 CommentsBeforeNextToken.clear();
213 MustBreakBeforeNextToken = false;
214 PreprocessorDirectives.clear();
215 CurrentLines = &Lines;
216 DeclarationScopeStack.clear();
220 void UnwrappedLineParser::parse() {
221 IndexedTokenSource TokenSource(AllTokens);
223 DEBUG(llvm::dbgs() << "----\n");
225 Tokens = &TokenSource;
230 // Create line with eof token.
231 pushToken(FormatTok);
234 for (SmallVectorImpl<UnwrappedLine>::iterator I = Lines.begin(),
237 Callback.consumeUnwrappedLine(*I);
239 Callback.finishRun();
241 while (!PPLevelBranchIndex.empty() &&
242 PPLevelBranchIndex.back() + 1 >= PPLevelBranchCount.back()) {
243 PPLevelBranchIndex.resize(PPLevelBranchIndex.size() - 1);
244 PPLevelBranchCount.resize(PPLevelBranchCount.size() - 1);
246 if (!PPLevelBranchIndex.empty()) {
247 ++PPLevelBranchIndex.back();
248 assert(PPLevelBranchIndex.size() == PPLevelBranchCount.size());
249 assert(PPLevelBranchIndex.back() <= PPLevelBranchCount.back());
251 } while (!PPLevelBranchIndex.empty());
254 void UnwrappedLineParser::parseFile() {
255 // The top-level context in a file always has declarations, except for pre-
256 // processor directives and JavaScript files.
257 bool MustBeDeclaration =
258 !Line->InPPDirective && Style.Language != FormatStyle::LK_JavaScript;
259 ScopedDeclarationState DeclarationState(*Line, DeclarationScopeStack,
261 parseLevel(/*HasOpeningBrace=*/false);
262 // Make sure to format the remaining tokens.
267 void UnwrappedLineParser::parseLevel(bool HasOpeningBrace) {
268 bool SwitchLabelEncountered = false;
270 tok::TokenKind kind = FormatTok->Tok.getKind();
271 if (FormatTok->Type == TT_MacroBlockBegin) {
273 } else if (FormatTok->Type == TT_MacroBlockEnd) {
283 // FIXME: Add parameter whether this can happen - if this happens, we must
284 // be in a non-declaration context.
285 if (!FormatTok->is(TT_MacroBlockBegin) && tryToParseBracedList())
287 parseBlock(/*MustBeDeclaration=*/false);
296 case tok::kw_default:
298 if (!SwitchLabelEncountered &&
299 (Style.IndentCaseLabels || (Line->InPPDirective && Line->Level == 1)))
301 SwitchLabelEncountered = true;
302 parseStructuralElement();
305 parseStructuralElement();
311 void UnwrappedLineParser::calculateBraceTypes(bool ExpectClassBody) {
312 // We'll parse forward through the tokens until we hit
313 // a closing brace or eof - note that getNextToken() will
314 // parse macros, so this will magically work inside macro
316 unsigned StoredPosition = Tokens->getPosition();
317 FormatToken *Tok = FormatTok;
318 const FormatToken *PrevTok = getPreviousToken();
319 // Keep a stack of positions of lbrace tokens. We will
320 // update information about whether an lbrace starts a
321 // braced init list or a different block during the loop.
322 SmallVector<FormatToken *, 8> LBraceStack;
323 assert(Tok->Tok.is(tok::l_brace));
325 // Get next non-comment token.
326 FormatToken *NextTok;
327 unsigned ReadTokens = 0;
329 NextTok = Tokens->getNextToken();
331 } while (NextTok->is(tok::comment));
333 switch (Tok->Tok.getKind()) {
335 if (Style.Language == FormatStyle::LK_JavaScript && PrevTok &&
336 PrevTok->is(tok::colon))
337 // In TypeScript's TypeMemberLists, there can be semicolons between the
338 // individual members.
339 Tok->BlockKind = BK_BracedInit;
341 Tok->BlockKind = BK_Unknown;
342 LBraceStack.push_back(Tok);
345 if (LBraceStack.empty())
347 if (LBraceStack.back()->BlockKind == BK_Unknown) {
348 bool ProbablyBracedList = false;
349 if (Style.Language == FormatStyle::LK_Proto) {
350 ProbablyBracedList = NextTok->isOneOf(tok::comma, tok::r_square);
352 // Using OriginalColumn to distinguish between ObjC methods and
353 // binary operators is a bit hacky.
354 bool NextIsObjCMethod = NextTok->isOneOf(tok::plus, tok::minus) &&
355 NextTok->OriginalColumn == 0;
357 // If there is a comma, semicolon or right paren after the closing
358 // brace, we assume this is a braced initializer list. Note that
359 // regardless how we mark inner braces here, we will overwrite the
360 // BlockKind later if we parse a braced list (where all blocks
361 // inside are by default braced lists), or when we explicitly detect
362 // blocks (for example while parsing lambdas).
364 // We exclude + and - as they can be ObjC visibility modifiers.
366 (Style.Language == FormatStyle::LK_JavaScript &&
367 NextTok->isOneOf(Keywords.kw_of, Keywords.kw_in)) ||
368 NextTok->isOneOf(tok::comma, tok::period, tok::colon,
369 tok::r_paren, tok::r_square, tok::l_brace,
370 tok::l_square, tok::l_paren, tok::ellipsis) ||
371 (NextTok->is(tok::semi) &&
372 (!ExpectClassBody || LBraceStack.size() != 1)) ||
373 (NextTok->isBinaryOperator() && !NextIsObjCMethod);
375 if (ProbablyBracedList) {
376 Tok->BlockKind = BK_BracedInit;
377 LBraceStack.back()->BlockKind = BK_BracedInit;
379 Tok->BlockKind = BK_Block;
380 LBraceStack.back()->BlockKind = BK_Block;
383 LBraceStack.pop_back();
393 if (!LBraceStack.empty() && LBraceStack.back()->BlockKind == BK_Unknown)
394 LBraceStack.back()->BlockKind = BK_Block;
401 } while (Tok->Tok.isNot(tok::eof) && !LBraceStack.empty());
403 // Assume other blocks for all unclosed opening braces.
404 for (unsigned i = 0, e = LBraceStack.size(); i != e; ++i) {
405 if (LBraceStack[i]->BlockKind == BK_Unknown)
406 LBraceStack[i]->BlockKind = BK_Block;
409 FormatTok = Tokens->setPosition(StoredPosition);
412 void UnwrappedLineParser::parseBlock(bool MustBeDeclaration, bool AddLevel,
414 assert(FormatTok->isOneOf(tok::l_brace, TT_MacroBlockBegin) &&
415 "'{' or macro block token expected");
416 const bool MacroBlock = FormatTok->is(TT_MacroBlockBegin);
417 FormatTok->BlockKind = BK_Block;
419 unsigned InitialLevel = Line->Level;
422 if (MacroBlock && FormatTok->is(tok::l_paren))
427 ScopedDeclarationState DeclarationState(*Line, DeclarationScopeStack,
431 parseLevel(/*HasOpeningBrace=*/true);
436 if (MacroBlock ? !FormatTok->is(TT_MacroBlockEnd)
437 : !FormatTok->is(tok::r_brace)) {
438 Line->Level = InitialLevel;
439 FormatTok->BlockKind = BK_Block;
443 nextToken(); // Munch the closing brace.
445 if (MacroBlock && FormatTok->is(tok::l_paren))
448 if (MunchSemi && FormatTok->Tok.is(tok::semi))
450 Line->Level = InitialLevel;
453 static bool isGoogScope(const UnwrappedLine &Line) {
454 // FIXME: Closure-library specific stuff should not be hard-coded but be
456 if (Line.Tokens.size() < 4)
458 auto I = Line.Tokens.begin();
459 if (I->Tok->TokenText != "goog")
462 if (I->Tok->isNot(tok::period))
465 if (I->Tok->TokenText != "scope")
468 return I->Tok->is(tok::l_paren);
471 static bool ShouldBreakBeforeBrace(const FormatStyle &Style,
472 const FormatToken &InitialToken) {
473 if (InitialToken.is(tok::kw_namespace))
474 return Style.BraceWrapping.AfterNamespace;
475 if (InitialToken.is(tok::kw_class))
476 return Style.BraceWrapping.AfterClass;
477 if (InitialToken.is(tok::kw_union))
478 return Style.BraceWrapping.AfterUnion;
479 if (InitialToken.is(tok::kw_struct))
480 return Style.BraceWrapping.AfterStruct;
484 void UnwrappedLineParser::parseChildBlock() {
485 FormatTok->BlockKind = BK_Block;
489 Style.Language == FormatStyle::LK_JavaScript && isGoogScope(*Line);
490 ScopedLineState LineState(*this);
491 ScopedDeclarationState DeclarationState(*Line, DeclarationScopeStack,
492 /*MustBeDeclaration=*/false);
493 Line->Level += GoogScope ? 0 : 1;
494 parseLevel(/*HasOpeningBrace=*/true);
495 flushComments(isOnNewLine(*FormatTok));
496 Line->Level -= GoogScope ? 0 : 1;
501 void UnwrappedLineParser::parsePPDirective() {
502 assert(FormatTok->Tok.is(tok::hash) && "'#' expected");
503 ScopedMacroState MacroState(*Line, Tokens, FormatTok);
506 if (!FormatTok->Tok.getIdentifierInfo()) {
511 switch (FormatTok->Tok.getIdentifierInfo()->getPPKeywordID()) {
516 parsePPIf(/*IfDef=*/false);
520 parsePPIf(/*IfDef=*/true);
537 void UnwrappedLineParser::conditionalCompilationCondition(bool Unreachable) {
538 if (Unreachable || (!PPStack.empty() && PPStack.back() == PP_Unreachable))
539 PPStack.push_back(PP_Unreachable);
541 PPStack.push_back(PP_Conditional);
544 void UnwrappedLineParser::conditionalCompilationStart(bool Unreachable) {
546 assert(PPBranchLevel >= 0 && PPBranchLevel <= (int)PPLevelBranchIndex.size());
547 if (PPBranchLevel == (int)PPLevelBranchIndex.size()) {
548 PPLevelBranchIndex.push_back(0);
549 PPLevelBranchCount.push_back(0);
551 PPChainBranchIndex.push(0);
552 bool Skip = PPLevelBranchIndex[PPBranchLevel] > 0;
553 conditionalCompilationCondition(Unreachable || Skip);
556 void UnwrappedLineParser::conditionalCompilationAlternative() {
557 if (!PPStack.empty())
559 assert(PPBranchLevel < (int)PPLevelBranchIndex.size());
560 if (!PPChainBranchIndex.empty())
561 ++PPChainBranchIndex.top();
562 conditionalCompilationCondition(
563 PPBranchLevel >= 0 && !PPChainBranchIndex.empty() &&
564 PPLevelBranchIndex[PPBranchLevel] != PPChainBranchIndex.top());
567 void UnwrappedLineParser::conditionalCompilationEnd() {
568 assert(PPBranchLevel < (int)PPLevelBranchIndex.size());
569 if (PPBranchLevel >= 0 && !PPChainBranchIndex.empty()) {
570 if (PPChainBranchIndex.top() + 1 > PPLevelBranchCount[PPBranchLevel]) {
571 PPLevelBranchCount[PPBranchLevel] = PPChainBranchIndex.top() + 1;
574 // Guard against #endif's without #if.
575 if (PPBranchLevel > 0)
577 if (!PPChainBranchIndex.empty())
578 PPChainBranchIndex.pop();
579 if (!PPStack.empty())
583 void UnwrappedLineParser::parsePPIf(bool IfDef) {
585 bool IsLiteralFalse = (FormatTok->Tok.isLiteral() &&
586 FormatTok->Tok.getLiteralData() != nullptr &&
587 StringRef(FormatTok->Tok.getLiteralData(),
588 FormatTok->Tok.getLength()) == "0") ||
589 FormatTok->Tok.is(tok::kw_false);
590 conditionalCompilationStart(!IfDef && IsLiteralFalse);
594 void UnwrappedLineParser::parsePPElse() {
595 conditionalCompilationAlternative();
599 void UnwrappedLineParser::parsePPElIf() { parsePPElse(); }
601 void UnwrappedLineParser::parsePPEndIf() {
602 conditionalCompilationEnd();
606 void UnwrappedLineParser::parsePPDefine() {
609 if (FormatTok->Tok.getKind() != tok::identifier) {
614 if (FormatTok->Tok.getKind() == tok::l_paren &&
615 FormatTok->WhitespaceRange.getBegin() ==
616 FormatTok->WhitespaceRange.getEnd()) {
622 // Errors during a preprocessor directive can only affect the layout of the
623 // preprocessor directive, and thus we ignore them. An alternative approach
624 // would be to use the same approach we use on the file level (no
625 // re-indentation if there was a structural error) within the macro
630 void UnwrappedLineParser::parsePPUnknown() {
637 // Here we blacklist certain tokens that are not usually the first token in an
638 // unwrapped line. This is used in attempt to distinguish macro calls without
639 // trailing semicolons from other constructs split to several lines.
640 static bool tokenCanStartNewLine(const clang::Token &Tok) {
641 // Semicolon can be a null-statement, l_square can be a start of a macro or
642 // a C++11 attribute, but this doesn't seem to be common.
643 return Tok.isNot(tok::semi) && Tok.isNot(tok::l_brace) &&
644 Tok.isNot(tok::l_square) &&
645 // Tokens that can only be used as binary operators and a part of
646 // overloaded operator names.
647 Tok.isNot(tok::period) && Tok.isNot(tok::periodstar) &&
648 Tok.isNot(tok::arrow) && Tok.isNot(tok::arrowstar) &&
649 Tok.isNot(tok::less) && Tok.isNot(tok::greater) &&
650 Tok.isNot(tok::slash) && Tok.isNot(tok::percent) &&
651 Tok.isNot(tok::lessless) && Tok.isNot(tok::greatergreater) &&
652 Tok.isNot(tok::equal) && Tok.isNot(tok::plusequal) &&
653 Tok.isNot(tok::minusequal) && Tok.isNot(tok::starequal) &&
654 Tok.isNot(tok::slashequal) && Tok.isNot(tok::percentequal) &&
655 Tok.isNot(tok::ampequal) && Tok.isNot(tok::pipeequal) &&
656 Tok.isNot(tok::caretequal) && Tok.isNot(tok::greatergreaterequal) &&
657 Tok.isNot(tok::lesslessequal) &&
658 // Colon is used in labels, base class lists, initializer lists,
659 // range-based for loops, ternary operator, but should never be the
660 // first token in an unwrapped line.
661 Tok.isNot(tok::colon) &&
662 // 'noexcept' is a trailing annotation.
663 Tok.isNot(tok::kw_noexcept);
666 static bool mustBeJSIdent(const AdditionalKeywords &Keywords,
667 const FormatToken *FormatTok) {
668 // FIXME: This returns true for C/C++ keywords like 'struct'.
669 return FormatTok->is(tok::identifier) &&
670 (FormatTok->Tok.getIdentifierInfo() == nullptr ||
671 !FormatTok->isOneOf(Keywords.kw_in, Keywords.kw_of, Keywords.kw_as,
672 Keywords.kw_async, Keywords.kw_await,
673 Keywords.kw_yield, Keywords.kw_finally,
674 Keywords.kw_function, Keywords.kw_import,
675 Keywords.kw_is, Keywords.kw_let, Keywords.kw_var,
676 Keywords.kw_abstract, Keywords.kw_extends,
677 Keywords.kw_implements, Keywords.kw_instanceof,
678 Keywords.kw_interface, Keywords.kw_throws));
681 static bool mustBeJSIdentOrValue(const AdditionalKeywords &Keywords,
682 const FormatToken *FormatTok) {
683 return FormatTok->Tok.isLiteral() || mustBeJSIdent(Keywords, FormatTok);
686 // isJSDeclOrStmt returns true if |FormatTok| starts a declaration or statement
687 // when encountered after a value (see mustBeJSIdentOrValue).
688 static bool isJSDeclOrStmt(const AdditionalKeywords &Keywords,
689 const FormatToken *FormatTok) {
690 return FormatTok->isOneOf(
691 tok::kw_return, Keywords.kw_yield,
693 tok::kw_if, tok::kw_else,
695 tok::kw_for, tok::kw_while, tok::kw_do, tok::kw_continue, tok::kw_break,
697 tok::kw_switch, tok::kw_case,
699 tok::kw_throw, tok::kw_try, tok::kw_catch, Keywords.kw_finally,
701 tok::kw_const, tok::kw_class, Keywords.kw_var, Keywords.kw_let,
702 Keywords.kw_async, Keywords.kw_function,
704 Keywords.kw_import, tok::kw_export);
707 // readTokenWithJavaScriptASI reads the next token and terminates the current
708 // line if JavaScript Automatic Semicolon Insertion must
709 // happen between the current token and the next token.
711 // This method is conservative - it cannot cover all edge cases of JavaScript,
712 // but only aims to correctly handle certain well known cases. It *must not*
713 // return true in speculative cases.
714 void UnwrappedLineParser::readTokenWithJavaScriptASI() {
715 FormatToken *Previous = FormatTok;
717 FormatToken *Next = FormatTok;
720 CommentsBeforeNextToken.empty()
721 ? Next->NewlinesBefore == 0
722 : CommentsBeforeNextToken.front()->NewlinesBefore == 0;
726 bool PreviousMustBeValue = mustBeJSIdentOrValue(Keywords, Previous);
727 if (PreviousMustBeValue && Line && Line->Tokens.size() > 1) {
728 // If the token before the previous one is an '@', the previous token is an
729 // annotation and can precede another identifier/value.
730 const FormatToken *PrePrevious = std::prev(Line->Tokens.end(), 2)->Tok;
731 if (PrePrevious->is(tok::at))
734 if (Next->is(tok::exclaim) && PreviousMustBeValue)
736 bool NextMustBeValue = mustBeJSIdentOrValue(Keywords, Next);
737 if (NextMustBeValue && (PreviousMustBeValue ||
738 Previous->isOneOf(tok::r_square, tok::r_paren,
739 tok::plusplus, tok::minusminus)))
741 if (PreviousMustBeValue && isJSDeclOrStmt(Keywords, Next))
745 void UnwrappedLineParser::parseStructuralElement() {
746 assert(!FormatTok->is(tok::l_brace));
747 if (Style.Language == FormatStyle::LK_TableGen &&
748 FormatTok->is(tok::pp_include)) {
750 if (FormatTok->is(tok::string_literal))
755 switch (FormatTok->Tok.getKind()) {
758 if (FormatTok->Tok.is(tok::l_brace)) {
762 switch (FormatTok->Tok.getObjCKeywordID()) {
763 case tok::objc_public:
764 case tok::objc_protected:
765 case tok::objc_package:
766 case tok::objc_private:
767 return parseAccessSpecifier();
768 case tok::objc_interface:
769 case tok::objc_implementation:
770 return parseObjCInterfaceOrImplementation();
771 case tok::objc_protocol:
772 return parseObjCProtocol();
774 return; // Handled by the caller.
775 case tok::objc_optional:
776 case tok::objc_required:
780 case tok::objc_autoreleasepool:
782 if (FormatTok->Tok.is(tok::l_brace)) {
783 if (Style.BraceWrapping.AfterObjCDeclaration)
785 parseBlock(/*MustBeDeclaration=*/false);
790 // This branch isn't strictly necessary (the kw_try case below would
791 // do this too after the tok::at is parsed above). But be explicit.
800 if (FormatTok->is(tok::l_brace)) {
801 FormatTok->Type = TT_InlineASMBrace;
803 while (FormatTok && FormatTok->isNot(tok::eof)) {
804 if (FormatTok->is(tok::r_brace)) {
805 FormatTok->Type = TT_InlineASMBrace;
810 FormatTok->Finalized = true;
815 case tok::kw_namespace:
820 if (FormatTok->Tok.is(tok::kw_namespace)) {
826 case tok::kw_protected:
827 case tok::kw_private:
828 if (Style.Language == FormatStyle::LK_Java ||
829 Style.Language == FormatStyle::LK_JavaScript)
832 parseAccessSpecifier();
839 parseForOrWhileLoop();
847 case tok::kw_default:
860 if (FormatTok->Tok.is(tok::string_literal)) {
862 if (FormatTok->Tok.is(tok::l_brace)) {
863 parseBlock(/*MustBeDeclaration=*/true, /*AddLevel=*/false);
870 if (Style.Language == FormatStyle::LK_JavaScript) {
871 parseJavaScriptEs6ImportExport();
875 case tok::identifier:
876 if (FormatTok->is(TT_ForEachMacro)) {
877 parseForOrWhileLoop();
880 if (FormatTok->is(TT_MacroBlockBegin)) {
881 parseBlock(/*MustBeDeclaration=*/false, /*AddLevel=*/true,
882 /*MunchSemi=*/false);
885 if (FormatTok->is(Keywords.kw_import)) {
886 if (Style.Language == FormatStyle::LK_JavaScript) {
887 parseJavaScriptEs6ImportExport();
890 if (Style.Language == FormatStyle::LK_Proto) {
892 if (FormatTok->is(tok::kw_public))
894 if (!FormatTok->is(tok::string_literal))
897 if (FormatTok->is(tok::semi))
903 if (FormatTok->isOneOf(Keywords.kw_signals, Keywords.kw_qsignals,
904 Keywords.kw_slots, Keywords.kw_qslots)) {
906 if (FormatTok->is(tok::colon)) {
912 // In all other cases, parse the declaration.
918 const FormatToken *Previous = getPreviousToken();
919 switch (FormatTok->Tok.getKind()) {
922 if (FormatTok->Tok.is(tok::l_brace))
926 // Ignore if this is part of "template <enum ...".
927 if (Previous && Previous->is(tok::less)) {
932 // parseEnum falls through and does not yet add an unwrapped line as an
933 // enum definition can start a structural element.
936 // This only applies for C++.
937 if (Style.Language != FormatStyle::LK_Cpp) {
942 case tok::kw_typedef:
944 if (FormatTok->isOneOf(Keywords.kw_NS_ENUM, Keywords.kw_NS_OPTIONS,
945 Keywords.kw_CF_ENUM, Keywords.kw_CF_OPTIONS))
951 // parseRecord falls through and does not yet add an unwrapped line as a
952 // record declaration or definition can start a structural element.
954 // This does not apply for Java and JavaScript.
955 if (Style.Language == FormatStyle::LK_Java ||
956 Style.Language == FormatStyle::LK_JavaScript) {
957 if (FormatTok->is(tok::semi))
965 // In Java, classes have an implicit static member "class".
966 if (Style.Language == FormatStyle::LK_Java && FormatTok &&
967 FormatTok->is(tok::kw_class))
969 if (Style.Language == FormatStyle::LK_JavaScript && FormatTok &&
970 FormatTok->Tok.getIdentifierInfo())
971 // JavaScript only has pseudo keywords, all keywords are allowed to
972 // appear in "IdentifierName" positions. See http://es5.github.io/#x7.6
985 case tok::kw_operator:
987 if (FormatTok->isBinaryOperator())
992 if (FormatTok->Tok.isAnyIdentifier() ||
993 FormatTok->isSimpleTypeSpecifier())
995 if (FormatTok->is(tok::l_paren))
997 if (FormatTok->is(tok::l_brace))
1001 if (!tryToParseBracedList()) {
1002 // A block outside of parentheses must be the last part of a
1003 // structural element.
1004 // FIXME: Figure out cases where this is not true, and add projections
1005 // for them (the one we know is missing are lambdas).
1006 if (Style.BraceWrapping.AfterFunction)
1008 FormatTok->Type = TT_FunctionLBrace;
1009 parseBlock(/*MustBeDeclaration=*/false);
1013 // Otherwise this was a braced init list, and the structural
1014 // element continues.
1017 // We arrive here when parsing function-try blocks.
1020 case tok::identifier: {
1021 if (FormatTok->is(TT_MacroBlockEnd)) {
1026 // Parse function literal unless 'function' is the first token in a line
1027 // in which case this should be treated as a free-standing function.
1028 if (Style.Language == FormatStyle::LK_JavaScript &&
1029 (FormatTok->is(Keywords.kw_function) ||
1030 FormatTok->startsSequence(Keywords.kw_async,
1031 Keywords.kw_function)) &&
1032 Line->Tokens.size() > 0) {
1033 tryToParseJSFunction();
1036 if ((Style.Language == FormatStyle::LK_JavaScript ||
1037 Style.Language == FormatStyle::LK_Java) &&
1038 FormatTok->is(Keywords.kw_interface)) {
1039 if (Style.Language == FormatStyle::LK_JavaScript) {
1040 // In JavaScript/TypeScript, "interface" can be used as a standalone
1041 // identifier, e.g. in `var interface = 1;`. If "interface" is
1042 // followed by another identifier, it is very like to be an actual
1043 // interface declaration.
1044 unsigned StoredPosition = Tokens->getPosition();
1045 FormatToken *Next = Tokens->getNextToken();
1046 FormatTok = Tokens->setPosition(StoredPosition);
1047 if (Next && !mustBeJSIdent(Keywords, Next)) {
1057 // See if the following token should start a new unwrapped line.
1058 StringRef Text = FormatTok->TokenText;
1060 if (Line->Tokens.size() == 1 &&
1061 // JS doesn't have macros, and within classes colons indicate fields,
1063 Style.Language != FormatStyle::LK_JavaScript) {
1064 if (FormatTok->Tok.is(tok::colon) && !Line->MustBeDeclaration) {
1065 Line->Tokens.begin()->Tok->MustBreakBefore = true;
1069 // Recognize function-like macro usages without trailing semicolon as
1070 // well as free-standing macros like Q_OBJECT.
1071 bool FunctionLike = FormatTok->is(tok::l_paren);
1075 bool FollowedByNewline =
1076 CommentsBeforeNextToken.empty()
1077 ? FormatTok->NewlinesBefore > 0
1078 : CommentsBeforeNextToken.front()->NewlinesBefore > 0;
1080 if (FollowedByNewline && (Text.size() >= 5 || FunctionLike) &&
1081 tokenCanStartNewLine(FormatTok->Tok) && Text == Text.upper()) {
1089 // Fat arrows (=>) have tok::TokenKind tok::equal but TokenType
1090 // TT_JsFatArrow. The always start an expression or a child block if
1091 // followed by a curly.
1092 if (FormatTok->is(TT_JsFatArrow)) {
1094 if (FormatTok->is(tok::l_brace))
1100 if (FormatTok->Tok.is(tok::l_brace)) {
1117 bool UnwrappedLineParser::tryToParseLambda() {
1118 if (Style.Language != FormatStyle::LK_Cpp) {
1122 const FormatToken* Previous = getPreviousToken();
1124 (Previous->isOneOf(tok::identifier, tok::kw_operator, tok::kw_new,
1126 Previous->closesScope() || Previous->isSimpleTypeSpecifier())) {
1130 assert(FormatTok->is(tok::l_square));
1131 FormatToken &LSquare = *FormatTok;
1132 if (!tryToParseLambdaIntroducer())
1135 while (FormatTok->isNot(tok::l_brace)) {
1136 if (FormatTok->isSimpleTypeSpecifier()) {
1140 switch (FormatTok->Tok.getKind()) {
1152 case tok::identifier:
1153 case tok::numeric_constant:
1154 case tok::coloncolon:
1155 case tok::kw_mutable:
1159 FormatTok->Type = TT_LambdaArrow;
1166 LSquare.Type = TT_LambdaLSquare;
1171 bool UnwrappedLineParser::tryToParseLambdaIntroducer() {
1173 if (FormatTok->is(tok::equal)) {
1175 if (FormatTok->is(tok::r_square)) {
1179 if (FormatTok->isNot(tok::comma))
1182 } else if (FormatTok->is(tok::amp)) {
1184 if (FormatTok->is(tok::r_square)) {
1188 if (!FormatTok->isOneOf(tok::comma, tok::identifier)) {
1191 if (FormatTok->is(tok::comma))
1193 } else if (FormatTok->is(tok::r_square)) {
1198 if (FormatTok->is(tok::amp))
1200 if (!FormatTok->isOneOf(tok::identifier, tok::kw_this))
1203 if (FormatTok->is(tok::ellipsis))
1205 if (FormatTok->is(tok::comma)) {
1207 } else if (FormatTok->is(tok::r_square)) {
1217 void UnwrappedLineParser::tryToParseJSFunction() {
1218 assert(FormatTok->is(Keywords.kw_function) ||
1219 FormatTok->startsSequence(Keywords.kw_async, Keywords.kw_function));
1220 if (FormatTok->is(Keywords.kw_async))
1222 // Consume "function".
1225 // Consume * (generator function).
1226 if (FormatTok->is(tok::star))
1229 // Consume function name.
1230 if (FormatTok->is(tok::identifier))
1233 if (FormatTok->isNot(tok::l_paren))
1236 // Parse formal parameter list.
1239 if (FormatTok->is(tok::colon)) {
1240 // Parse a type definition.
1243 // Eat the type declaration. For braced inline object types, balance braces,
1244 // otherwise just parse until finding an l_brace for the function body.
1245 if (FormatTok->is(tok::l_brace))
1246 tryToParseBracedList();
1248 while (FormatTok->isNot(tok::l_brace) && !eof())
1255 bool UnwrappedLineParser::tryToParseBracedList() {
1256 if (FormatTok->BlockKind == BK_Unknown)
1257 calculateBraceTypes();
1258 assert(FormatTok->BlockKind != BK_Unknown);
1259 if (FormatTok->BlockKind == BK_Block)
1265 bool UnwrappedLineParser::parseBracedList(bool ContinueOnSemicolons) {
1266 bool HasError = false;
1269 // FIXME: Once we have an expression parser in the UnwrappedLineParser,
1270 // replace this by using parseAssigmentExpression() inside.
1272 if (Style.Language == FormatStyle::LK_JavaScript) {
1273 if (FormatTok->is(Keywords.kw_function) ||
1274 FormatTok->startsSequence(Keywords.kw_async, Keywords.kw_function)) {
1275 tryToParseJSFunction();
1278 if (FormatTok->is(TT_JsFatArrow)) {
1280 // Fat arrows can be followed by simple expressions or by child blocks
1282 if (FormatTok->is(tok::l_brace)) {
1288 switch (FormatTok->Tok.getKind()) {
1291 if (FormatTok->is(tok::l_brace)) {
1299 // Assume there are no blocks inside a braced init list apart
1300 // from the ones we explicitly parse out (like lambdas).
1301 FormatTok->BlockKind = BK_BracedInit;
1306 // JavaScript can just have free standing methods and getters/setters in
1307 // object literals. Detect them by a "{" following ")".
1308 if (Style.Language == FormatStyle::LK_JavaScript) {
1309 if (FormatTok->is(tok::l_brace))
1318 // JavaScript (or more precisely TypeScript) can have semicolons in braced
1319 // lists (in so-called TypeMemberLists). Thus, the semicolon cannot be
1320 // used for error recovery if we have otherwise determined that this is
1322 if (Style.Language == FormatStyle::LK_JavaScript) {
1327 if (!ContinueOnSemicolons)
1342 void UnwrappedLineParser::parseParens() {
1343 assert(FormatTok->Tok.is(tok::l_paren) && "'(' expected.");
1346 switch (FormatTok->Tok.getKind()) {
1349 if (Style.Language == FormatStyle::LK_Java && FormatTok->is(tok::l_brace))
1356 // A "}" inside parenthesis is an error if there wasn't a matching "{".
1362 if (!tryToParseBracedList())
1367 if (FormatTok->Tok.is(tok::l_brace))
1370 case tok::identifier:
1371 if (Style.Language == FormatStyle::LK_JavaScript &&
1372 (FormatTok->is(Keywords.kw_function) ||
1373 FormatTok->startsSequence(Keywords.kw_async, Keywords.kw_function)))
1374 tryToParseJSFunction();
1385 void UnwrappedLineParser::parseSquare() {
1386 assert(FormatTok->Tok.is(tok::l_square) && "'[' expected.");
1387 if (tryToParseLambda())
1390 switch (FormatTok->Tok.getKind()) {
1398 // A "}" inside parenthesis is an error if there wasn't a matching "{".
1403 case tok::l_brace: {
1404 if (!tryToParseBracedList())
1410 if (FormatTok->Tok.is(tok::l_brace))
1420 void UnwrappedLineParser::parseIfThenElse() {
1421 assert(FormatTok->Tok.is(tok::kw_if) && "'if' expected");
1423 if (FormatTok->Tok.is(tok::l_paren))
1425 bool NeedsUnwrappedLine = false;
1426 if (FormatTok->Tok.is(tok::l_brace)) {
1427 CompoundStatementIndenter Indenter(this, Style, Line->Level);
1428 parseBlock(/*MustBeDeclaration=*/false);
1429 if (Style.BraceWrapping.BeforeElse)
1432 NeedsUnwrappedLine = true;
1436 parseStructuralElement();
1439 if (FormatTok->Tok.is(tok::kw_else)) {
1441 if (FormatTok->Tok.is(tok::l_brace)) {
1442 CompoundStatementIndenter Indenter(this, Style, Line->Level);
1443 parseBlock(/*MustBeDeclaration=*/false);
1445 } else if (FormatTok->Tok.is(tok::kw_if)) {
1450 parseStructuralElement();
1451 if (FormatTok->is(tok::eof))
1455 } else if (NeedsUnwrappedLine) {
1460 void UnwrappedLineParser::parseTryCatch() {
1461 assert(FormatTok->isOneOf(tok::kw_try, tok::kw___try) && "'try' expected");
1463 bool NeedsUnwrappedLine = false;
1464 if (FormatTok->is(tok::colon)) {
1465 // We are in a function try block, what comes is an initializer list.
1467 while (FormatTok->is(tok::identifier)) {
1469 if (FormatTok->is(tok::l_paren))
1471 if (FormatTok->is(tok::comma))
1475 // Parse try with resource.
1476 if (Style.Language == FormatStyle::LK_Java && FormatTok->is(tok::l_paren)) {
1479 if (FormatTok->is(tok::l_brace)) {
1480 CompoundStatementIndenter Indenter(this, Style, Line->Level);
1481 parseBlock(/*MustBeDeclaration=*/false);
1482 if (Style.BraceWrapping.BeforeCatch) {
1485 NeedsUnwrappedLine = true;
1487 } else if (!FormatTok->is(tok::kw_catch)) {
1488 // The C++ standard requires a compound-statement after a try.
1489 // If there's none, we try to assume there's a structuralElement
1490 // and try to continue.
1493 parseStructuralElement();
1497 if (FormatTok->is(tok::at))
1499 if (!(FormatTok->isOneOf(tok::kw_catch, Keywords.kw___except,
1500 tok::kw___finally) ||
1501 ((Style.Language == FormatStyle::LK_Java ||
1502 Style.Language == FormatStyle::LK_JavaScript) &&
1503 FormatTok->is(Keywords.kw_finally)) ||
1504 (FormatTok->Tok.isObjCAtKeyword(tok::objc_catch) ||
1505 FormatTok->Tok.isObjCAtKeyword(tok::objc_finally))))
1508 while (FormatTok->isNot(tok::l_brace)) {
1509 if (FormatTok->is(tok::l_paren)) {
1513 if (FormatTok->isOneOf(tok::semi, tok::r_brace, tok::eof))
1517 NeedsUnwrappedLine = false;
1518 CompoundStatementIndenter Indenter(this, Style, Line->Level);
1519 parseBlock(/*MustBeDeclaration=*/false);
1520 if (Style.BraceWrapping.BeforeCatch)
1523 NeedsUnwrappedLine = true;
1525 if (NeedsUnwrappedLine)
1529 void UnwrappedLineParser::parseNamespace() {
1530 assert(FormatTok->Tok.is(tok::kw_namespace) && "'namespace' expected");
1532 const FormatToken &InitialToken = *FormatTok;
1534 while (FormatTok->isOneOf(tok::identifier, tok::coloncolon))
1536 if (FormatTok->Tok.is(tok::l_brace)) {
1537 if (ShouldBreakBeforeBrace(Style, InitialToken))
1540 bool AddLevel = Style.NamespaceIndentation == FormatStyle::NI_All ||
1541 (Style.NamespaceIndentation == FormatStyle::NI_Inner &&
1542 DeclarationScopeStack.size() > 1);
1543 parseBlock(/*MustBeDeclaration=*/true, AddLevel);
1544 // Munch the semicolon after a namespace. This is more common than one would
1545 // think. Puttin the semicolon into its own line is very ugly.
1546 if (FormatTok->Tok.is(tok::semi))
1550 // FIXME: Add error handling.
1553 void UnwrappedLineParser::parseNew() {
1554 assert(FormatTok->is(tok::kw_new) && "'new' expected");
1556 if (Style.Language != FormatStyle::LK_Java)
1559 // In Java, we can parse everything up to the parens, which aren't optional.
1561 // There should not be a ;, { or } before the new's open paren.
1562 if (FormatTok->isOneOf(tok::semi, tok::l_brace, tok::r_brace))
1565 // Consume the parens.
1566 if (FormatTok->is(tok::l_paren)) {
1569 // If there is a class body of an anonymous class, consume that as child.
1570 if (FormatTok->is(tok::l_brace))
1578 void UnwrappedLineParser::parseForOrWhileLoop() {
1579 assert(FormatTok->isOneOf(tok::kw_for, tok::kw_while, TT_ForEachMacro) &&
1580 "'for', 'while' or foreach macro expected");
1582 if (FormatTok->Tok.is(tok::l_paren))
1584 if (FormatTok->Tok.is(tok::l_brace)) {
1585 CompoundStatementIndenter Indenter(this, Style, Line->Level);
1586 parseBlock(/*MustBeDeclaration=*/false);
1591 parseStructuralElement();
1596 void UnwrappedLineParser::parseDoWhile() {
1597 assert(FormatTok->Tok.is(tok::kw_do) && "'do' expected");
1599 if (FormatTok->Tok.is(tok::l_brace)) {
1600 CompoundStatementIndenter Indenter(this, Style, Line->Level);
1601 parseBlock(/*MustBeDeclaration=*/false);
1602 if (Style.BraceWrapping.IndentBraces)
1607 parseStructuralElement();
1611 // FIXME: Add error handling.
1612 if (!FormatTok->Tok.is(tok::kw_while)) {
1618 parseStructuralElement();
1621 void UnwrappedLineParser::parseLabel() {
1623 unsigned OldLineLevel = Line->Level;
1624 if (Line->Level > 1 || (!Line->InPPDirective && Line->Level > 0))
1626 if (CommentsBeforeNextToken.empty() && FormatTok->Tok.is(tok::l_brace)) {
1627 CompoundStatementIndenter Indenter(this, Style, Line->Level);
1628 parseBlock(/*MustBeDeclaration=*/false);
1629 if (FormatTok->Tok.is(tok::kw_break)) {
1630 if (Style.BraceWrapping.AfterControlStatement)
1632 parseStructuralElement();
1636 if (FormatTok->is(tok::semi))
1640 Line->Level = OldLineLevel;
1641 if (FormatTok->isNot(tok::l_brace)) {
1642 parseStructuralElement();
1647 void UnwrappedLineParser::parseCaseLabel() {
1648 assert(FormatTok->Tok.is(tok::kw_case) && "'case' expected");
1649 // FIXME: fix handling of complex expressions here.
1652 } while (!eof() && !FormatTok->Tok.is(tok::colon));
1656 void UnwrappedLineParser::parseSwitch() {
1657 assert(FormatTok->Tok.is(tok::kw_switch) && "'switch' expected");
1659 if (FormatTok->Tok.is(tok::l_paren))
1661 if (FormatTok->Tok.is(tok::l_brace)) {
1662 CompoundStatementIndenter Indenter(this, Style, Line->Level);
1663 parseBlock(/*MustBeDeclaration=*/false);
1668 parseStructuralElement();
1673 void UnwrappedLineParser::parseAccessSpecifier() {
1675 // Understand Qt's slots.
1676 if (FormatTok->isOneOf(Keywords.kw_slots, Keywords.kw_qslots))
1678 // Otherwise, we don't know what it is, and we'd better keep the next token.
1679 if (FormatTok->Tok.is(tok::colon))
1684 bool UnwrappedLineParser::parseEnum() {
1685 // Won't be 'enum' for NS_ENUMs.
1686 if (FormatTok->Tok.is(tok::kw_enum))
1689 // In TypeScript, "enum" can also be used as property name, e.g. in interface
1690 // declarations. An "enum" keyword followed by a colon would be a syntax
1691 // error and thus assume it is just an identifier.
1692 if (Style.Language == FormatStyle::LK_JavaScript &&
1693 FormatTok->isOneOf(tok::colon, tok::question))
1696 // Eat up enum class ...
1697 if (FormatTok->Tok.is(tok::kw_class) || FormatTok->Tok.is(tok::kw_struct))
1700 while (FormatTok->Tok.getIdentifierInfo() ||
1701 FormatTok->isOneOf(tok::colon, tok::coloncolon, tok::less,
1702 tok::greater, tok::comma, tok::question)) {
1704 // We can have macros or attributes in between 'enum' and the enum name.
1705 if (FormatTok->is(tok::l_paren))
1707 if (FormatTok->is(tok::identifier)) {
1709 // If there are two identifiers in a row, this is likely an elaborate
1710 // return type. In Java, this can be "implements", etc.
1711 if (Style.Language == FormatStyle::LK_Cpp &&
1712 FormatTok->is(tok::identifier))
1717 // Just a declaration or something is wrong.
1718 if (FormatTok->isNot(tok::l_brace))
1720 FormatTok->BlockKind = BK_Block;
1722 if (Style.Language == FormatStyle::LK_Java) {
1723 // Java enums are different.
1724 parseJavaEnumBody();
1727 if (Style.Language == FormatStyle::LK_Proto) {
1728 parseBlock(/*MustBeDeclaration=*/true);
1733 bool HasError = !parseBracedList(/*ContinueOnSemicolons=*/true);
1735 if (FormatTok->is(tok::semi))
1741 // There is no addUnwrappedLine() here so that we fall through to parsing a
1742 // structural element afterwards. Thus, in "enum A {} n, m;",
1743 // "} n, m;" will end up in one unwrapped line.
1746 void UnwrappedLineParser::parseJavaEnumBody() {
1747 // Determine whether the enum is simple, i.e. does not have a semicolon or
1748 // constants with class bodies. Simple enums can be formatted like braced
1749 // lists, contracted to a single line, etc.
1750 unsigned StoredPosition = Tokens->getPosition();
1751 bool IsSimple = true;
1752 FormatToken *Tok = Tokens->getNextToken();
1754 if (Tok->is(tok::r_brace))
1756 if (Tok->isOneOf(tok::l_brace, tok::semi)) {
1760 // FIXME: This will also mark enums with braces in the arguments to enum
1761 // constants as "not simple". This is probably fine in practice, though.
1762 Tok = Tokens->getNextToken();
1764 FormatTok = Tokens->setPosition(StoredPosition);
1772 // Parse the body of a more complex enum.
1773 // First add a line for everything up to the "{".
1778 // Parse the enum constants.
1780 if (FormatTok->is(tok::l_brace)) {
1781 // Parse the constant's class body.
1782 parseBlock(/*MustBeDeclaration=*/true, /*AddLevel=*/true,
1783 /*MunchSemi=*/false);
1784 } else if (FormatTok->is(tok::l_paren)) {
1786 } else if (FormatTok->is(tok::comma)) {
1789 } else if (FormatTok->is(tok::semi)) {
1793 } else if (FormatTok->is(tok::r_brace)) {
1801 // Parse the class body after the enum's ";" if any.
1802 parseLevel(/*HasOpeningBrace=*/true);
1808 void UnwrappedLineParser::parseRecord() {
1809 const FormatToken &InitialToken = *FormatTok;
1812 // The actual identifier can be a nested name specifier, and in macros
1813 // it is often token-pasted.
1814 while (FormatTok->isOneOf(tok::identifier, tok::coloncolon, tok::hashhash,
1815 tok::kw___attribute, tok::kw___declspec,
1817 ((Style.Language == FormatStyle::LK_Java ||
1818 Style.Language == FormatStyle::LK_JavaScript) &&
1819 FormatTok->isOneOf(tok::period, tok::comma))) {
1820 bool IsNonMacroIdentifier =
1821 FormatTok->is(tok::identifier) &&
1822 FormatTok->TokenText != FormatTok->TokenText.upper();
1824 // We can have macros or attributes in between 'class' and the class name.
1825 if (!IsNonMacroIdentifier && FormatTok->Tok.is(tok::l_paren))
1829 // Note that parsing away template declarations here leads to incorrectly
1830 // accepting function declarations as record declarations.
1831 // In general, we cannot solve this problem. Consider:
1832 // class A<int> B() {}
1833 // which can be a function definition or a class definition when B() is a
1834 // macro. If we find enough real-world cases where this is a problem, we
1835 // can parse for the 'template' keyword in the beginning of the statement,
1836 // and thus rule out the record production in case there is no template
1837 // (this would still leave us with an ambiguity between template function
1838 // and class declarations).
1839 if (FormatTok->isOneOf(tok::colon, tok::less)) {
1841 if (FormatTok->is(tok::l_brace)) {
1842 calculateBraceTypes(/*ExpectClassBody=*/true);
1843 if (!tryToParseBracedList())
1846 if (FormatTok->Tok.is(tok::semi))
1851 if (FormatTok->Tok.is(tok::l_brace)) {
1852 if (ShouldBreakBeforeBrace(Style, InitialToken))
1855 parseBlock(/*MustBeDeclaration=*/true, /*AddLevel=*/true,
1856 /*MunchSemi=*/false);
1858 // There is no addUnwrappedLine() here so that we fall through to parsing a
1859 // structural element afterwards. Thus, in "class A {} n, m;",
1860 // "} n, m;" will end up in one unwrapped line.
1863 void UnwrappedLineParser::parseObjCProtocolList() {
1864 assert(FormatTok->Tok.is(tok::less) && "'<' expected.");
1867 while (!eof() && FormatTok->Tok.isNot(tok::greater));
1868 nextToken(); // Skip '>'.
1871 void UnwrappedLineParser::parseObjCUntilAtEnd() {
1873 if (FormatTok->Tok.isObjCAtKeyword(tok::objc_end)) {
1878 if (FormatTok->is(tok::l_brace)) {
1879 parseBlock(/*MustBeDeclaration=*/false);
1880 // In ObjC interfaces, nothing should be following the "}".
1882 } else if (FormatTok->is(tok::r_brace)) {
1883 // Ignore stray "}". parseStructuralElement doesn't consume them.
1887 parseStructuralElement();
1892 void UnwrappedLineParser::parseObjCInterfaceOrImplementation() {
1894 nextToken(); // interface name
1896 // @interface can be followed by either a base class, or a category.
1897 if (FormatTok->Tok.is(tok::colon)) {
1899 nextToken(); // base class name
1900 } else if (FormatTok->Tok.is(tok::l_paren))
1901 // Skip category, if present.
1904 if (FormatTok->Tok.is(tok::less))
1905 parseObjCProtocolList();
1907 if (FormatTok->Tok.is(tok::l_brace)) {
1908 if (Style.BraceWrapping.AfterObjCDeclaration)
1910 parseBlock(/*MustBeDeclaration=*/true);
1913 // With instance variables, this puts '}' on its own line. Without instance
1914 // variables, this ends the @interface line.
1917 parseObjCUntilAtEnd();
1920 void UnwrappedLineParser::parseObjCProtocol() {
1922 nextToken(); // protocol name
1924 if (FormatTok->Tok.is(tok::less))
1925 parseObjCProtocolList();
1927 // Check for protocol declaration.
1928 if (FormatTok->Tok.is(tok::semi)) {
1930 return addUnwrappedLine();
1934 parseObjCUntilAtEnd();
1937 void UnwrappedLineParser::parseJavaScriptEs6ImportExport() {
1938 bool IsImport = FormatTok->is(Keywords.kw_import);
1939 assert(IsImport || FormatTok->is(tok::kw_export));
1942 // Consume the "default" in "export default class/function".
1943 if (FormatTok->is(tok::kw_default))
1946 // Consume "async function", "function" and "default function", so that these
1947 // get parsed as free-standing JS functions, i.e. do not require a trailing
1949 if (FormatTok->is(Keywords.kw_async))
1951 if (FormatTok->is(Keywords.kw_function)) {
1956 // For imports, `export *`, `export {...}`, consume the rest of the line up
1957 // to the terminating `;`. For everything else, just return and continue
1958 // parsing the structural element, i.e. the declaration or expression for
1959 // `export default`.
1960 if (!IsImport && !FormatTok->isOneOf(tok::l_brace, tok::star) &&
1961 !FormatTok->isStringLiteral())
1964 while (!eof() && FormatTok->isNot(tok::semi)) {
1965 if (FormatTok->is(tok::l_brace)) {
1966 FormatTok->BlockKind = BK_Block;
1974 LLVM_ATTRIBUTE_UNUSED static void printDebugInfo(const UnwrappedLine &Line,
1975 StringRef Prefix = "") {
1976 llvm::dbgs() << Prefix << "Line(" << Line.Level << ")"
1977 << (Line.InPPDirective ? " MACRO" : "") << ": ";
1978 for (std::list<UnwrappedLineNode>::const_iterator I = Line.Tokens.begin(),
1979 E = Line.Tokens.end();
1981 llvm::dbgs() << I->Tok->Tok.getName() << "[" << I->Tok->Type << "] ";
1983 for (std::list<UnwrappedLineNode>::const_iterator I = Line.Tokens.begin(),
1984 E = Line.Tokens.end();
1986 const UnwrappedLineNode &Node = *I;
1987 for (SmallVectorImpl<UnwrappedLine>::const_iterator
1988 I = Node.Children.begin(),
1989 E = Node.Children.end();
1991 printDebugInfo(*I, "\nChild: ");
1994 llvm::dbgs() << "\n";
1997 void UnwrappedLineParser::addUnwrappedLine() {
1998 if (Line->Tokens.empty())
2001 if (CurrentLines == &Lines)
2002 printDebugInfo(*Line);
2004 CurrentLines->push_back(std::move(*Line));
2005 Line->Tokens.clear();
2006 if (CurrentLines == &Lines && !PreprocessorDirectives.empty()) {
2007 CurrentLines->append(
2008 std::make_move_iterator(PreprocessorDirectives.begin()),
2009 std::make_move_iterator(PreprocessorDirectives.end()));
2010 PreprocessorDirectives.clear();
2014 bool UnwrappedLineParser::eof() const { return FormatTok->Tok.is(tok::eof); }
2016 bool UnwrappedLineParser::isOnNewLine(const FormatToken &FormatTok) {
2017 return (Line->InPPDirective || FormatTok.HasUnescapedNewline) &&
2018 FormatTok.NewlinesBefore > 0;
2021 void UnwrappedLineParser::flushComments(bool NewlineBeforeNext) {
2022 bool JustComments = Line->Tokens.empty();
2023 for (SmallVectorImpl<FormatToken *>::const_iterator
2024 I = CommentsBeforeNextToken.begin(),
2025 E = CommentsBeforeNextToken.end();
2027 if (isOnNewLine(**I) && JustComments)
2031 if (NewlineBeforeNext && JustComments)
2033 CommentsBeforeNextToken.clear();
2036 void UnwrappedLineParser::nextToken() {
2039 flushComments(isOnNewLine(*FormatTok));
2040 pushToken(FormatTok);
2041 if (Style.Language != FormatStyle::LK_JavaScript)
2044 readTokenWithJavaScriptASI();
2047 const FormatToken *UnwrappedLineParser::getPreviousToken() {
2048 // FIXME: This is a dirty way to access the previous token. Find a better
2050 if (!Line || Line->Tokens.empty())
2052 return Line->Tokens.back().Tok;
2055 void UnwrappedLineParser::readToken() {
2056 bool CommentsInCurrentLine = true;
2058 FormatTok = Tokens->getNextToken();
2060 while (!Line->InPPDirective && FormatTok->Tok.is(tok::hash) &&
2061 (FormatTok->HasUnescapedNewline || FormatTok->IsFirst)) {
2062 // If there is an unfinished unwrapped line, we flush the preprocessor
2063 // directives only after that unwrapped line was finished later.
2064 bool SwitchToPreprocessorLines = !Line->Tokens.empty();
2065 ScopedLineState BlockState(*this, SwitchToPreprocessorLines);
2066 // Comments stored before the preprocessor directive need to be output
2067 // before the preprocessor directive, at the same level as the
2068 // preprocessor directive, as we consider them to apply to the directive.
2069 flushComments(isOnNewLine(*FormatTok));
2072 while (FormatTok->Type == TT_ConflictStart ||
2073 FormatTok->Type == TT_ConflictEnd ||
2074 FormatTok->Type == TT_ConflictAlternative) {
2075 if (FormatTok->Type == TT_ConflictStart) {
2076 conditionalCompilationStart(/*Unreachable=*/false);
2077 } else if (FormatTok->Type == TT_ConflictAlternative) {
2078 conditionalCompilationAlternative();
2079 } else if (FormatTok->Type == TT_ConflictEnd) {
2080 conditionalCompilationEnd();
2082 FormatTok = Tokens->getNextToken();
2083 FormatTok->MustBreakBefore = true;
2086 if (!PPStack.empty() && (PPStack.back() == PP_Unreachable) &&
2087 !Line->InPPDirective) {
2091 if (!FormatTok->Tok.is(tok::comment))
2093 if (isOnNewLine(*FormatTok) || FormatTok->IsFirst) {
2094 CommentsInCurrentLine = false;
2096 if (CommentsInCurrentLine) {
2097 pushToken(FormatTok);
2099 CommentsBeforeNextToken.push_back(FormatTok);
2104 void UnwrappedLineParser::pushToken(FormatToken *Tok) {
2105 Line->Tokens.push_back(UnwrappedLineNode(Tok));
2106 if (MustBreakBeforeNextToken) {
2107 Line->Tokens.back().Tok->MustBreakBefore = true;
2108 MustBreakBeforeNextToken = false;
2112 } // end namespace format
2113 } // end namespace clang