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/Support/Debug.h"
19 #define DEBUG_TYPE "format-parser"
24 class FormatTokenSource {
26 virtual ~FormatTokenSource() {}
27 virtual FormatToken *getNextToken() = 0;
29 virtual unsigned getPosition() = 0;
30 virtual FormatToken *setPosition(unsigned Position) = 0;
35 class ScopedDeclarationState {
37 ScopedDeclarationState(UnwrappedLine &Line, std::vector<bool> &Stack,
38 bool MustBeDeclaration)
39 : Line(Line), Stack(Stack) {
40 Line.MustBeDeclaration = MustBeDeclaration;
41 Stack.push_back(MustBeDeclaration);
43 ~ScopedDeclarationState() {
46 Line.MustBeDeclaration = Stack.back();
48 Line.MustBeDeclaration = true;
53 std::vector<bool> &Stack;
56 class ScopedMacroState : public FormatTokenSource {
58 ScopedMacroState(UnwrappedLine &Line, FormatTokenSource *&TokenSource,
59 FormatToken *&ResetToken, bool &StructuralError)
60 : Line(Line), TokenSource(TokenSource), ResetToken(ResetToken),
61 PreviousLineLevel(Line.Level), PreviousTokenSource(TokenSource),
62 StructuralError(StructuralError),
63 PreviousStructuralError(StructuralError), Token(nullptr) {
66 Line.InPPDirective = true;
70 TokenSource = PreviousTokenSource;
72 Line.InPPDirective = false;
73 Line.Level = PreviousLineLevel;
74 StructuralError = PreviousStructuralError;
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;
113 bool &StructuralError;
114 bool PreviousStructuralError;
119 } // end anonymous namespace
121 class ScopedLineState {
123 ScopedLineState(UnwrappedLineParser &Parser,
124 bool SwitchToPreprocessorLines = false)
126 OriginalLines = Parser.CurrentLines;
127 if (SwitchToPreprocessorLines)
128 Parser.CurrentLines = &Parser.PreprocessorDirectives;
129 else if (!Parser.Line->Tokens.empty())
130 Parser.CurrentLines = &Parser.Line->Tokens.back().Children;
131 PreBlockLine = Parser.Line.release();
132 Parser.Line.reset(new UnwrappedLine());
133 Parser.Line->Level = PreBlockLine->Level;
134 Parser.Line->InPPDirective = PreBlockLine->InPPDirective;
138 if (!Parser.Line->Tokens.empty()) {
139 Parser.addUnwrappedLine();
141 assert(Parser.Line->Tokens.empty());
142 Parser.Line.reset(PreBlockLine);
143 if (Parser.CurrentLines == &Parser.PreprocessorDirectives)
144 Parser.MustBreakBeforeNextToken = true;
145 Parser.CurrentLines = OriginalLines;
149 UnwrappedLineParser &Parser;
151 UnwrappedLine *PreBlockLine;
152 SmallVectorImpl<UnwrappedLine> *OriginalLines;
155 class CompoundStatementIndenter {
157 CompoundStatementIndenter(UnwrappedLineParser *Parser,
158 const FormatStyle &Style, unsigned &LineLevel)
159 : LineLevel(LineLevel), OldLineLevel(LineLevel) {
160 if (Style.BreakBeforeBraces == FormatStyle::BS_Allman) {
161 Parser->addUnwrappedLine();
162 } else if (Style.BreakBeforeBraces == FormatStyle::BS_GNU) {
163 Parser->addUnwrappedLine();
167 ~CompoundStatementIndenter() { LineLevel = OldLineLevel; }
171 unsigned OldLineLevel;
176 class IndexedTokenSource : public FormatTokenSource {
178 IndexedTokenSource(ArrayRef<FormatToken *> Tokens)
179 : Tokens(Tokens), Position(-1) {}
181 FormatToken *getNextToken() override {
183 return Tokens[Position];
186 unsigned getPosition() override {
187 assert(Position >= 0);
191 FormatToken *setPosition(unsigned P) override {
193 return Tokens[Position];
196 void reset() { Position = -1; }
199 ArrayRef<FormatToken *> Tokens;
203 } // end anonymous namespace
205 UnwrappedLineParser::UnwrappedLineParser(const FormatStyle &Style,
206 ArrayRef<FormatToken *> Tokens,
207 UnwrappedLineConsumer &Callback)
208 : Line(new UnwrappedLine), MustBreakBeforeNextToken(false),
209 CurrentLines(&Lines), StructuralError(false), Style(Style),
210 Tokens(nullptr), Callback(Callback), AllTokens(Tokens),
213 void UnwrappedLineParser::reset() {
215 Line.reset(new UnwrappedLine);
216 CommentsBeforeNextToken.clear();
218 MustBreakBeforeNextToken = false;
219 PreprocessorDirectives.clear();
220 CurrentLines = &Lines;
221 DeclarationScopeStack.clear();
222 StructuralError = false;
226 bool UnwrappedLineParser::parse() {
227 IndexedTokenSource TokenSource(AllTokens);
229 DEBUG(llvm::dbgs() << "----\n");
231 Tokens = &TokenSource;
236 // Create line with eof token.
237 pushToken(FormatTok);
240 for (SmallVectorImpl<UnwrappedLine>::iterator I = Lines.begin(),
243 Callback.consumeUnwrappedLine(*I);
245 Callback.finishRun();
247 while (!PPLevelBranchIndex.empty() &&
248 PPLevelBranchIndex.back() + 1 >= PPLevelBranchCount.back()) {
249 PPLevelBranchIndex.resize(PPLevelBranchIndex.size() - 1);
250 PPLevelBranchCount.resize(PPLevelBranchCount.size() - 1);
252 if (!PPLevelBranchIndex.empty()) {
253 ++PPLevelBranchIndex.back();
254 assert(PPLevelBranchIndex.size() == PPLevelBranchCount.size());
255 assert(PPLevelBranchIndex.back() <= PPLevelBranchCount.back());
257 } while (!PPLevelBranchIndex.empty());
259 return StructuralError;
262 void UnwrappedLineParser::parseFile() {
263 ScopedDeclarationState DeclarationState(
264 *Line, DeclarationScopeStack,
265 /*MustBeDeclaration=*/ !Line->InPPDirective);
266 parseLevel(/*HasOpeningBrace=*/false);
267 // Make sure to format the remaining tokens.
272 void UnwrappedLineParser::parseLevel(bool HasOpeningBrace) {
273 bool SwitchLabelEncountered = false;
275 switch (FormatTok->Tok.getKind()) {
281 // FIXME: Add parameter whether this can happen - if this happens, we must
282 // be in a non-declaration context.
283 parseBlock(/*MustBeDeclaration=*/false);
289 StructuralError = true;
293 case tok::kw_default:
295 if (!SwitchLabelEncountered &&
296 (Style.IndentCaseLabels || (Line->InPPDirective && Line->Level == 1)))
298 SwitchLabelEncountered = true;
299 parseStructuralElement();
302 parseStructuralElement();
308 void UnwrappedLineParser::calculateBraceTypes() {
309 // We'll parse forward through the tokens until we hit
310 // a closing brace or eof - note that getNextToken() will
311 // parse macros, so this will magically work inside macro
313 unsigned StoredPosition = Tokens->getPosition();
314 unsigned Position = StoredPosition;
315 FormatToken *Tok = FormatTok;
316 // Keep a stack of positions of lbrace tokens. We will
317 // update information about whether an lbrace starts a
318 // braced init list or a different block during the loop.
319 SmallVector<FormatToken *, 8> LBraceStack;
320 assert(Tok->Tok.is(tok::l_brace));
322 // Get next none-comment token.
323 FormatToken *NextTok;
324 unsigned ReadTokens = 0;
326 NextTok = Tokens->getNextToken();
328 } while (NextTok->is(tok::comment));
330 switch (Tok->Tok.getKind()) {
332 LBraceStack.push_back(Tok);
335 if (!LBraceStack.empty()) {
336 if (LBraceStack.back()->BlockKind == BK_Unknown) {
337 bool ProbablyBracedList = false;
338 if (Style.Language == FormatStyle::LK_Proto) {
339 ProbablyBracedList = NextTok->isOneOf(tok::comma, tok::r_square);
341 // Using OriginalColumn to distinguish between ObjC methods and
342 // binary operators is a bit hacky.
343 bool NextIsObjCMethod = NextTok->isOneOf(tok::plus, tok::minus) &&
344 NextTok->OriginalColumn == 0;
346 // If there is a comma, semicolon or right paren after the closing
347 // brace, we assume this is a braced initializer list. Note that
348 // regardless how we mark inner braces here, we will overwrite the
349 // BlockKind later if we parse a braced list (where all blocks
350 // inside are by default braced lists), or when we explicitly detect
351 // blocks (for example while parsing lambdas).
353 // We exclude + and - as they can be ObjC visibility modifiers.
355 NextTok->isOneOf(tok::comma, tok::semi, tok::period, tok::colon,
356 tok::r_paren, tok::r_square, tok::l_brace,
358 (NextTok->isBinaryOperator() && !NextIsObjCMethod);
360 if (ProbablyBracedList) {
361 Tok->BlockKind = BK_BracedInit;
362 LBraceStack.back()->BlockKind = BK_BracedInit;
364 Tok->BlockKind = BK_Block;
365 LBraceStack.back()->BlockKind = BK_Block;
368 LBraceStack.pop_back();
378 if (!LBraceStack.empty())
379 LBraceStack.back()->BlockKind = BK_Block;
385 Position += ReadTokens;
386 } while (Tok->Tok.isNot(tok::eof) && !LBraceStack.empty());
387 // Assume other blocks for all unclosed opening braces.
388 for (unsigned i = 0, e = LBraceStack.size(); i != e; ++i) {
389 if (LBraceStack[i]->BlockKind == BK_Unknown)
390 LBraceStack[i]->BlockKind = BK_Block;
393 FormatTok = Tokens->setPosition(StoredPosition);
396 void UnwrappedLineParser::parseBlock(bool MustBeDeclaration, bool AddLevel,
398 assert(FormatTok->Tok.is(tok::l_brace) && "'{' expected");
399 unsigned InitialLevel = Line->Level;
404 ScopedDeclarationState DeclarationState(*Line, DeclarationScopeStack,
408 parseLevel(/*HasOpeningBrace=*/true);
410 if (!FormatTok->Tok.is(tok::r_brace)) {
411 Line->Level = InitialLevel;
412 StructuralError = true;
416 nextToken(); // Munch the closing brace.
417 if (MunchSemi && FormatTok->Tok.is(tok::semi))
419 Line->Level = InitialLevel;
422 static bool IsGoogScope(const UnwrappedLine &Line) {
423 if (Line.Tokens.size() < 4)
425 auto I = Line.Tokens.begin();
426 if (I->Tok->TokenText != "goog")
429 if (I->Tok->isNot(tok::period))
432 if (I->Tok->TokenText != "scope")
435 return I->Tok->is(tok::l_paren);
438 void UnwrappedLineParser::parseChildBlock() {
439 FormatTok->BlockKind = BK_Block;
443 Style.Language == FormatStyle::LK_JavaScript && IsGoogScope(*Line);
444 ScopedLineState LineState(*this);
445 ScopedDeclarationState DeclarationState(*Line, DeclarationScopeStack,
446 /*MustBeDeclaration=*/false);
447 Line->Level += GoogScope ? 0 : 1;
448 parseLevel(/*HasOpeningBrace=*/true);
449 Line->Level -= GoogScope ? 0 : 1;
454 void UnwrappedLineParser::parsePPDirective() {
455 assert(FormatTok->Tok.is(tok::hash) && "'#' expected");
456 ScopedMacroState MacroState(*Line, Tokens, FormatTok, StructuralError);
459 if (!FormatTok->Tok.getIdentifierInfo()) {
464 switch (FormatTok->Tok.getIdentifierInfo()->getPPKeywordID()) {
469 parsePPIf(/*IfDef=*/false);
473 parsePPIf(/*IfDef=*/true);
490 void UnwrappedLineParser::conditionalCompilationCondition(bool Unreachable) {
491 if (Unreachable || (!PPStack.empty() && PPStack.back() == PP_Unreachable))
492 PPStack.push_back(PP_Unreachable);
494 PPStack.push_back(PP_Conditional);
497 void UnwrappedLineParser::conditionalCompilationStart(bool Unreachable) {
499 assert(PPBranchLevel >= 0 && PPBranchLevel <= (int)PPLevelBranchIndex.size());
500 if (PPBranchLevel == (int)PPLevelBranchIndex.size()) {
501 PPLevelBranchIndex.push_back(0);
502 PPLevelBranchCount.push_back(0);
504 PPChainBranchIndex.push(0);
505 bool Skip = PPLevelBranchIndex[PPBranchLevel] > 0;
506 conditionalCompilationCondition(Unreachable || Skip);
509 void UnwrappedLineParser::conditionalCompilationAlternative() {
510 if (!PPStack.empty())
512 assert(PPBranchLevel < (int)PPLevelBranchIndex.size());
513 if (!PPChainBranchIndex.empty())
514 ++PPChainBranchIndex.top();
515 conditionalCompilationCondition(
516 PPBranchLevel >= 0 && !PPChainBranchIndex.empty() &&
517 PPLevelBranchIndex[PPBranchLevel] != PPChainBranchIndex.top());
520 void UnwrappedLineParser::conditionalCompilationEnd() {
521 assert(PPBranchLevel < (int)PPLevelBranchIndex.size());
522 if (PPBranchLevel >= 0 && !PPChainBranchIndex.empty()) {
523 if (PPChainBranchIndex.top() + 1 > PPLevelBranchCount[PPBranchLevel]) {
524 PPLevelBranchCount[PPBranchLevel] = PPChainBranchIndex.top() + 1;
527 // Guard against #endif's without #if.
528 if (PPBranchLevel > 0)
530 if (!PPChainBranchIndex.empty())
531 PPChainBranchIndex.pop();
532 if (!PPStack.empty())
536 void UnwrappedLineParser::parsePPIf(bool IfDef) {
538 bool IsLiteralFalse = (FormatTok->Tok.isLiteral() &&
539 StringRef(FormatTok->Tok.getLiteralData(),
540 FormatTok->Tok.getLength()) == "0") ||
541 FormatTok->Tok.is(tok::kw_false);
542 conditionalCompilationStart(!IfDef && IsLiteralFalse);
546 void UnwrappedLineParser::parsePPElse() {
547 conditionalCompilationAlternative();
551 void UnwrappedLineParser::parsePPElIf() { parsePPElse(); }
553 void UnwrappedLineParser::parsePPEndIf() {
554 conditionalCompilationEnd();
558 void UnwrappedLineParser::parsePPDefine() {
561 if (FormatTok->Tok.getKind() != tok::identifier) {
566 if (FormatTok->Tok.getKind() == tok::l_paren &&
567 FormatTok->WhitespaceRange.getBegin() ==
568 FormatTok->WhitespaceRange.getEnd()) {
574 // Errors during a preprocessor directive can only affect the layout of the
575 // preprocessor directive, and thus we ignore them. An alternative approach
576 // would be to use the same approach we use on the file level (no
577 // re-indentation if there was a structural error) within the macro
582 void UnwrappedLineParser::parsePPUnknown() {
589 // Here we blacklist certain tokens that are not usually the first token in an
590 // unwrapped line. This is used in attempt to distinguish macro calls without
591 // trailing semicolons from other constructs split to several lines.
592 bool tokenCanStartNewLine(clang::Token Tok) {
593 // Semicolon can be a null-statement, l_square can be a start of a macro or
594 // a C++11 attribute, but this doesn't seem to be common.
595 return Tok.isNot(tok::semi) && Tok.isNot(tok::l_brace) &&
596 Tok.isNot(tok::l_square) &&
597 // Tokens that can only be used as binary operators and a part of
598 // overloaded operator names.
599 Tok.isNot(tok::period) && Tok.isNot(tok::periodstar) &&
600 Tok.isNot(tok::arrow) && Tok.isNot(tok::arrowstar) &&
601 Tok.isNot(tok::less) && Tok.isNot(tok::greater) &&
602 Tok.isNot(tok::slash) && Tok.isNot(tok::percent) &&
603 Tok.isNot(tok::lessless) && Tok.isNot(tok::greatergreater) &&
604 Tok.isNot(tok::equal) && Tok.isNot(tok::plusequal) &&
605 Tok.isNot(tok::minusequal) && Tok.isNot(tok::starequal) &&
606 Tok.isNot(tok::slashequal) && Tok.isNot(tok::percentequal) &&
607 Tok.isNot(tok::ampequal) && Tok.isNot(tok::pipeequal) &&
608 Tok.isNot(tok::caretequal) && Tok.isNot(tok::greatergreaterequal) &&
609 Tok.isNot(tok::lesslessequal) &&
610 // Colon is used in labels, base class lists, initializer lists,
611 // range-based for loops, ternary operator, but should never be the
612 // first token in an unwrapped line.
613 Tok.isNot(tok::colon) &&
614 // 'noexcept' is a trailing annotation.
615 Tok.isNot(tok::kw_noexcept);
618 void UnwrappedLineParser::parseStructuralElement() {
619 assert(!FormatTok->Tok.is(tok::l_brace));
620 switch (FormatTok->Tok.getKind()) {
623 if (FormatTok->Tok.is(tok::l_brace)) {
627 switch (FormatTok->Tok.getObjCKeywordID()) {
628 case tok::objc_public:
629 case tok::objc_protected:
630 case tok::objc_package:
631 case tok::objc_private:
632 return parseAccessSpecifier();
633 case tok::objc_interface:
634 case tok::objc_implementation:
635 return parseObjCInterfaceOrImplementation();
636 case tok::objc_protocol:
637 return parseObjCProtocol();
639 return; // Handled by the caller.
640 case tok::objc_optional:
641 case tok::objc_required:
649 case tok::kw_namespace:
654 if (FormatTok->Tok.is(tok::kw_namespace)) {
660 case tok::kw_protected:
661 case tok::kw_private:
662 parseAccessSpecifier();
669 parseForOrWhileLoop();
677 case tok::kw_default:
689 if (FormatTok->Tok.is(tok::string_literal)) {
691 if (FormatTok->Tok.is(tok::l_brace)) {
692 parseBlock(/*MustBeDeclaration=*/true, /*AddLevel=*/false);
698 case tok::identifier:
699 if (FormatTok->IsForEachMacro) {
700 parseForOrWhileLoop();
703 // In all other cases, parse the declaration.
709 switch (FormatTok->Tok.getKind()) {
712 if (FormatTok->Tok.is(tok::l_brace))
718 case tok::kw_typedef:
720 // FIXME: Use the IdentifierTable instead.
721 if (FormatTok->TokenText == "NS_ENUM")
728 // A record declaration or definition is always the start of a structural
743 if (FormatTok->Tok.isAnyIdentifier() ||
744 FormatTok->isSimpleTypeSpecifier())
746 if (FormatTok->is(tok::l_paren))
748 if (FormatTok->is(tok::l_brace))
752 if (!tryToParseBracedList()) {
753 // A block outside of parentheses must be the last part of a
754 // structural element.
755 // FIXME: Figure out cases where this is not true, and add projections
756 // for them (the one we know is missing are lambdas).
757 if (Style.BreakBeforeBraces != FormatStyle::BS_Attach)
759 FormatTok->Type = TT_FunctionLBrace;
760 parseBlock(/*MustBeDeclaration=*/false);
764 // Otherwise this was a braced init list, and the structural
765 // element continues.
768 // We arrive here when parsing function-try blocks.
771 case tok::identifier: {
772 StringRef Text = FormatTok->TokenText;
773 // Parse function literal unless 'function' is the first token in a line
774 // in which case this should be treated as a free-standing function.
775 if (Style.Language == FormatStyle::LK_JavaScript && Text == "function" &&
776 Line->Tokens.size() > 0) {
777 tryToParseJSFunction();
781 if (Line->Tokens.size() == 1) {
782 if (FormatTok->Tok.is(tok::colon)) {
786 // Recognize function-like macro usages without trailing semicolon.
787 if (FormatTok->Tok.is(tok::l_paren)) {
789 if (FormatTok->NewlinesBefore > 0 &&
790 tokenCanStartNewLine(FormatTok->Tok) && Text == Text.upper()) {
794 } else if (FormatTok->HasUnescapedNewline && Text.size() >= 5 &&
795 Text == Text.upper()) {
796 // Recognize free-standing macros like Q_OBJECT.
805 if (FormatTok->Tok.is(tok::l_brace)) {
819 bool UnwrappedLineParser::tryToParseLambda() {
820 // FIXME: This is a dirty way to access the previous token. Find a better
822 if (!Line->Tokens.empty() &&
823 (Line->Tokens.back().Tok->isOneOf(tok::identifier, tok::kw_operator) ||
824 Line->Tokens.back().Tok->closesScope() ||
825 Line->Tokens.back().Tok->isSimpleTypeSpecifier())) {
829 assert(FormatTok->is(tok::l_square));
830 FormatToken &LSquare = *FormatTok;
831 if (!tryToParseLambdaIntroducer())
834 while (FormatTok->isNot(tok::l_brace)) {
835 if (FormatTok->isSimpleTypeSpecifier()) {
839 switch (FormatTok->Tok.getKind()) {
847 case tok::identifier:
848 case tok::coloncolon:
849 case tok::kw_mutable:
853 FormatTok->Type = TT_TrailingReturnArrow;
860 LSquare.Type = TT_LambdaLSquare;
865 bool UnwrappedLineParser::tryToParseLambdaIntroducer() {
867 if (FormatTok->is(tok::equal)) {
869 if (FormatTok->is(tok::r_square)) {
873 if (FormatTok->isNot(tok::comma))
876 } else if (FormatTok->is(tok::amp)) {
878 if (FormatTok->is(tok::r_square)) {
882 if (!FormatTok->isOneOf(tok::comma, tok::identifier)) {
885 if (FormatTok->is(tok::comma))
887 } else if (FormatTok->is(tok::r_square)) {
892 if (FormatTok->is(tok::amp))
894 if (!FormatTok->isOneOf(tok::identifier, tok::kw_this))
897 if (FormatTok->is(tok::ellipsis))
899 if (FormatTok->is(tok::comma)) {
901 } else if (FormatTok->is(tok::r_square)) {
911 void UnwrappedLineParser::tryToParseJSFunction() {
914 // Consume function name.
915 if (FormatTok->is(tok::identifier))
918 if (FormatTok->isNot(tok::l_paren))
921 while (FormatTok->isNot(tok::l_brace)) {
922 // Err on the side of caution in order to avoid consuming the full file in
923 // case of incomplete code.
924 if (!FormatTok->isOneOf(tok::identifier, tok::comma, tok::r_paren,
932 bool UnwrappedLineParser::tryToParseBracedList() {
933 if (FormatTok->BlockKind == BK_Unknown)
934 calculateBraceTypes();
935 assert(FormatTok->BlockKind != BK_Unknown);
936 if (FormatTok->BlockKind == BK_Block)
942 bool UnwrappedLineParser::parseBracedList(bool ContinueOnSemicolons) {
943 bool HasError = false;
946 // FIXME: Once we have an expression parser in the UnwrappedLineParser,
947 // replace this by using parseAssigmentExpression() inside.
949 if (Style.Language == FormatStyle::LK_JavaScript &&
950 FormatTok->TokenText == "function") {
951 tryToParseJSFunction();
954 switch (FormatTok->Tok.getKind()) {
957 if (FormatTok->is(tok::l_brace)) {
965 // Assume there are no blocks inside a braced init list apart
966 // from the ones we explicitly parse out (like lambdas).
967 FormatTok->BlockKind = BK_BracedInit;
975 if (!ContinueOnSemicolons)
990 void UnwrappedLineParser::parseParens() {
991 assert(FormatTok->Tok.is(tok::l_paren) && "'(' expected.");
994 switch (FormatTok->Tok.getKind()) {
1002 // A "}" inside parenthesis is an error if there wasn't a matching "{".
1007 case tok::l_brace: {
1008 if (!tryToParseBracedList()) {
1015 if (FormatTok->Tok.is(tok::l_brace))
1025 void UnwrappedLineParser::parseSquare() {
1026 assert(FormatTok->Tok.is(tok::l_square) && "'[' expected.");
1027 if (tryToParseLambda())
1030 switch (FormatTok->Tok.getKind()) {
1038 // A "}" inside parenthesis is an error if there wasn't a matching "{".
1043 case tok::l_brace: {
1044 if (!tryToParseBracedList()) {
1051 if (FormatTok->Tok.is(tok::l_brace))
1061 void UnwrappedLineParser::parseIfThenElse() {
1062 assert(FormatTok->Tok.is(tok::kw_if) && "'if' expected");
1064 if (FormatTok->Tok.is(tok::l_paren))
1066 bool NeedsUnwrappedLine = false;
1067 if (FormatTok->Tok.is(tok::l_brace)) {
1068 CompoundStatementIndenter Indenter(this, Style, Line->Level);
1069 parseBlock(/*MustBeDeclaration=*/false);
1070 if (Style.BreakBeforeBraces == FormatStyle::BS_Allman ||
1071 Style.BreakBeforeBraces == FormatStyle::BS_GNU) {
1074 NeedsUnwrappedLine = true;
1079 parseStructuralElement();
1082 if (FormatTok->Tok.is(tok::kw_else)) {
1084 if (FormatTok->Tok.is(tok::l_brace)) {
1085 CompoundStatementIndenter Indenter(this, Style, Line->Level);
1086 parseBlock(/*MustBeDeclaration=*/false);
1088 } else if (FormatTok->Tok.is(tok::kw_if)) {
1093 parseStructuralElement();
1096 } else if (NeedsUnwrappedLine) {
1101 void UnwrappedLineParser::parseTryCatch() {
1102 assert(FormatTok->is(tok::kw_try) && "'try' expected");
1104 bool NeedsUnwrappedLine = false;
1105 if (FormatTok->is(tok::colon)) {
1106 // We are in a function try block, what comes is an initializer list.
1108 while (FormatTok->is(tok::identifier)) {
1110 if (FormatTok->is(tok::l_paren))
1113 StructuralError = true;
1114 if (FormatTok->is(tok::comma))
1118 if (FormatTok->is(tok::l_brace)) {
1119 CompoundStatementIndenter Indenter(this, Style, Line->Level);
1120 parseBlock(/*MustBeDeclaration=*/false);
1121 if (Style.BreakBeforeBraces == FormatStyle::BS_Allman ||
1122 Style.BreakBeforeBraces == FormatStyle::BS_GNU ||
1123 Style.BreakBeforeBraces == FormatStyle::BS_Stroustrup) {
1126 NeedsUnwrappedLine = true;
1128 } else if (!FormatTok->is(tok::kw_catch)) {
1129 // The C++ standard requires a compound-statement after a try.
1130 // If there's none, we try to assume there's a structuralElement
1131 // and try to continue.
1132 StructuralError = true;
1135 parseStructuralElement();
1138 while (FormatTok->is(tok::kw_catch) ||
1139 (Style.Language == FormatStyle::LK_JavaScript &&
1140 FormatTok->TokenText == "finally")) {
1142 while (FormatTok->isNot(tok::l_brace)) {
1143 if (FormatTok->is(tok::l_paren)) {
1147 if (FormatTok->isOneOf(tok::semi, tok::r_brace))
1151 NeedsUnwrappedLine = false;
1152 CompoundStatementIndenter Indenter(this, Style, Line->Level);
1153 parseBlock(/*MustBeDeclaration=*/false);
1154 if (Style.BreakBeforeBraces == FormatStyle::BS_Allman ||
1155 Style.BreakBeforeBraces == FormatStyle::BS_GNU ||
1156 Style.BreakBeforeBraces == FormatStyle::BS_Stroustrup) {
1159 NeedsUnwrappedLine = true;
1162 if (NeedsUnwrappedLine) {
1167 void UnwrappedLineParser::parseNamespace() {
1168 assert(FormatTok->Tok.is(tok::kw_namespace) && "'namespace' expected");
1170 if (FormatTok->Tok.is(tok::identifier))
1172 if (FormatTok->Tok.is(tok::l_brace)) {
1173 if (Style.BreakBeforeBraces == FormatStyle::BS_Linux ||
1174 Style.BreakBeforeBraces == FormatStyle::BS_Allman ||
1175 Style.BreakBeforeBraces == FormatStyle::BS_GNU)
1178 bool AddLevel = Style.NamespaceIndentation == FormatStyle::NI_All ||
1179 (Style.NamespaceIndentation == FormatStyle::NI_Inner &&
1180 DeclarationScopeStack.size() > 1);
1181 parseBlock(/*MustBeDeclaration=*/true, AddLevel);
1182 // Munch the semicolon after a namespace. This is more common than one would
1183 // think. Puttin the semicolon into its own line is very ugly.
1184 if (FormatTok->Tok.is(tok::semi))
1188 // FIXME: Add error handling.
1191 void UnwrappedLineParser::parseForOrWhileLoop() {
1192 assert((FormatTok->Tok.is(tok::kw_for) || FormatTok->Tok.is(tok::kw_while) ||
1193 FormatTok->IsForEachMacro) &&
1194 "'for', 'while' or foreach macro expected");
1196 if (FormatTok->Tok.is(tok::l_paren))
1198 if (FormatTok->Tok.is(tok::l_brace)) {
1199 CompoundStatementIndenter Indenter(this, Style, Line->Level);
1200 parseBlock(/*MustBeDeclaration=*/false);
1205 parseStructuralElement();
1210 void UnwrappedLineParser::parseDoWhile() {
1211 assert(FormatTok->Tok.is(tok::kw_do) && "'do' expected");
1213 if (FormatTok->Tok.is(tok::l_brace)) {
1214 CompoundStatementIndenter Indenter(this, Style, Line->Level);
1215 parseBlock(/*MustBeDeclaration=*/false);
1216 if (Style.BreakBeforeBraces == FormatStyle::BS_GNU)
1221 parseStructuralElement();
1225 // FIXME: Add error handling.
1226 if (!FormatTok->Tok.is(tok::kw_while)) {
1232 parseStructuralElement();
1235 void UnwrappedLineParser::parseLabel() {
1237 unsigned OldLineLevel = Line->Level;
1238 if (Line->Level > 1 || (!Line->InPPDirective && Line->Level > 0))
1240 if (CommentsBeforeNextToken.empty() && FormatTok->Tok.is(tok::l_brace)) {
1241 CompoundStatementIndenter Indenter(this, Style, Line->Level);
1242 parseBlock(/*MustBeDeclaration=*/false);
1243 if (FormatTok->Tok.is(tok::kw_break)) {
1244 // "break;" after "}" on its own line only for BS_Allman and BS_GNU
1245 if (Style.BreakBeforeBraces == FormatStyle::BS_Allman ||
1246 Style.BreakBeforeBraces == FormatStyle::BS_GNU) {
1249 parseStructuralElement();
1255 Line->Level = OldLineLevel;
1258 void UnwrappedLineParser::parseCaseLabel() {
1259 assert(FormatTok->Tok.is(tok::kw_case) && "'case' expected");
1260 // FIXME: fix handling of complex expressions here.
1263 } while (!eof() && !FormatTok->Tok.is(tok::colon));
1267 void UnwrappedLineParser::parseSwitch() {
1268 assert(FormatTok->Tok.is(tok::kw_switch) && "'switch' expected");
1270 if (FormatTok->Tok.is(tok::l_paren))
1272 if (FormatTok->Tok.is(tok::l_brace)) {
1273 CompoundStatementIndenter Indenter(this, Style, Line->Level);
1274 parseBlock(/*MustBeDeclaration=*/false);
1279 parseStructuralElement();
1284 void UnwrappedLineParser::parseAccessSpecifier() {
1286 // Understand Qt's slots.
1287 if (FormatTok->is(tok::identifier) &&
1288 (FormatTok->TokenText == "slots" || FormatTok->TokenText == "Q_SLOTS"))
1290 // Otherwise, we don't know what it is, and we'd better keep the next token.
1291 if (FormatTok->Tok.is(tok::colon))
1296 void UnwrappedLineParser::parseEnum() {
1297 if (FormatTok->Tok.is(tok::kw_enum)) {
1298 // Won't be 'enum' for NS_ENUMs.
1301 // Eat up enum class ...
1302 if (FormatTok->Tok.is(tok::kw_class) || FormatTok->Tok.is(tok::kw_struct))
1304 while (FormatTok->Tok.getIdentifierInfo() ||
1305 FormatTok->isOneOf(tok::colon, tok::coloncolon)) {
1307 // We can have macros or attributes in between 'enum' and the enum name.
1308 if (FormatTok->Tok.is(tok::l_paren)) {
1311 if (FormatTok->Tok.is(tok::identifier))
1314 if (FormatTok->Tok.is(tok::l_brace)) {
1315 FormatTok->BlockKind = BK_Block;
1316 bool HasError = !parseBracedList(/*ContinueOnSemicolons=*/true);
1318 if (FormatTok->is(tok::semi))
1323 // We fall through to parsing a structural element afterwards, so that in
1325 // "} n, m;" will end up in one unwrapped line.
1328 void UnwrappedLineParser::parseRecord() {
1330 if (FormatTok->Tok.is(tok::identifier) ||
1331 FormatTok->Tok.is(tok::kw___attribute) ||
1332 FormatTok->Tok.is(tok::kw___declspec) ||
1333 FormatTok->Tok.is(tok::kw_alignas)) {
1335 // We can have macros or attributes in between 'class' and the class name.
1336 if (FormatTok->Tok.is(tok::l_paren)) {
1339 // The actual identifier can be a nested name specifier, and in macros
1340 // it is often token-pasted.
1341 while (FormatTok->Tok.is(tok::identifier) ||
1342 FormatTok->Tok.is(tok::coloncolon) ||
1343 FormatTok->Tok.is(tok::hashhash))
1346 // Note that parsing away template declarations here leads to incorrectly
1347 // accepting function declarations as record declarations.
1348 // In general, we cannot solve this problem. Consider:
1349 // class A<int> B() {}
1350 // which can be a function definition or a class definition when B() is a
1351 // macro. If we find enough real-world cases where this is a problem, we
1352 // can parse for the 'template' keyword in the beginning of the statement,
1353 // and thus rule out the record production in case there is no template
1354 // (this would still leave us with an ambiguity between template function
1355 // and class declarations).
1356 if (FormatTok->Tok.is(tok::colon) || FormatTok->Tok.is(tok::less)) {
1357 while (!eof() && FormatTok->Tok.isNot(tok::l_brace)) {
1358 if (FormatTok->Tok.is(tok::semi))
1364 if (FormatTok->Tok.is(tok::l_brace)) {
1365 if (Style.BreakBeforeBraces == FormatStyle::BS_Linux ||
1366 Style.BreakBeforeBraces == FormatStyle::BS_Allman ||
1367 Style.BreakBeforeBraces == FormatStyle::BS_GNU)
1370 parseBlock(/*MustBeDeclaration=*/true, /*AddLevel=*/true,
1371 /*MunchSemi=*/false);
1373 // We fall through to parsing a structural element afterwards, so
1375 // will end up in one unwrapped line.
1378 void UnwrappedLineParser::parseObjCProtocolList() {
1379 assert(FormatTok->Tok.is(tok::less) && "'<' expected.");
1382 while (!eof() && FormatTok->Tok.isNot(tok::greater));
1383 nextToken(); // Skip '>'.
1386 void UnwrappedLineParser::parseObjCUntilAtEnd() {
1388 if (FormatTok->Tok.isObjCAtKeyword(tok::objc_end)) {
1393 if (FormatTok->is(tok::l_brace)) {
1394 parseBlock(/*MustBeDeclaration=*/false);
1395 // In ObjC interfaces, nothing should be following the "}".
1397 } else if (FormatTok->is(tok::r_brace)) {
1398 // Ignore stray "}". parseStructuralElement doesn't consume them.
1402 parseStructuralElement();
1407 void UnwrappedLineParser::parseObjCInterfaceOrImplementation() {
1409 nextToken(); // interface name
1411 // @interface can be followed by either a base class, or a category.
1412 if (FormatTok->Tok.is(tok::colon)) {
1414 nextToken(); // base class name
1415 } else if (FormatTok->Tok.is(tok::l_paren))
1416 // Skip category, if present.
1419 if (FormatTok->Tok.is(tok::less))
1420 parseObjCProtocolList();
1422 if (FormatTok->Tok.is(tok::l_brace)) {
1423 if (Style.BreakBeforeBraces == FormatStyle::BS_Allman ||
1424 Style.BreakBeforeBraces == FormatStyle::BS_GNU)
1426 parseBlock(/*MustBeDeclaration=*/true);
1429 // With instance variables, this puts '}' on its own line. Without instance
1430 // variables, this ends the @interface line.
1433 parseObjCUntilAtEnd();
1436 void UnwrappedLineParser::parseObjCProtocol() {
1438 nextToken(); // protocol name
1440 if (FormatTok->Tok.is(tok::less))
1441 parseObjCProtocolList();
1443 // Check for protocol declaration.
1444 if (FormatTok->Tok.is(tok::semi)) {
1446 return addUnwrappedLine();
1450 parseObjCUntilAtEnd();
1453 LLVM_ATTRIBUTE_UNUSED static void printDebugInfo(const UnwrappedLine &Line,
1454 StringRef Prefix = "") {
1455 llvm::dbgs() << Prefix << "Line(" << Line.Level << ")"
1456 << (Line.InPPDirective ? " MACRO" : "") << ": ";
1457 for (std::list<UnwrappedLineNode>::const_iterator I = Line.Tokens.begin(),
1458 E = Line.Tokens.end();
1460 llvm::dbgs() << I->Tok->Tok.getName() << "[" << I->Tok->Type << "] ";
1462 for (std::list<UnwrappedLineNode>::const_iterator I = Line.Tokens.begin(),
1463 E = Line.Tokens.end();
1465 const UnwrappedLineNode &Node = *I;
1466 for (SmallVectorImpl<UnwrappedLine>::const_iterator
1467 I = Node.Children.begin(),
1468 E = Node.Children.end();
1470 printDebugInfo(*I, "\nChild: ");
1473 llvm::dbgs() << "\n";
1476 void UnwrappedLineParser::addUnwrappedLine() {
1477 if (Line->Tokens.empty())
1480 if (CurrentLines == &Lines)
1481 printDebugInfo(*Line);
1483 CurrentLines->push_back(*Line);
1484 Line->Tokens.clear();
1485 if (CurrentLines == &Lines && !PreprocessorDirectives.empty()) {
1486 for (SmallVectorImpl<UnwrappedLine>::iterator
1487 I = PreprocessorDirectives.begin(),
1488 E = PreprocessorDirectives.end();
1490 CurrentLines->push_back(*I);
1492 PreprocessorDirectives.clear();
1496 bool UnwrappedLineParser::eof() const { return FormatTok->Tok.is(tok::eof); }
1498 bool UnwrappedLineParser::isOnNewLine(const FormatToken &FormatTok) {
1499 return (Line->InPPDirective || FormatTok.HasUnescapedNewline) &&
1500 FormatTok.NewlinesBefore > 0;
1503 void UnwrappedLineParser::flushComments(bool NewlineBeforeNext) {
1504 bool JustComments = Line->Tokens.empty();
1505 for (SmallVectorImpl<FormatToken *>::const_iterator
1506 I = CommentsBeforeNextToken.begin(),
1507 E = CommentsBeforeNextToken.end();
1509 if (isOnNewLine(**I) && JustComments) {
1514 if (NewlineBeforeNext && JustComments) {
1517 CommentsBeforeNextToken.clear();
1520 void UnwrappedLineParser::nextToken() {
1523 flushComments(isOnNewLine(*FormatTok));
1524 pushToken(FormatTok);
1528 void UnwrappedLineParser::readToken() {
1529 bool CommentsInCurrentLine = true;
1531 FormatTok = Tokens->getNextToken();
1533 while (!Line->InPPDirective && FormatTok->Tok.is(tok::hash) &&
1534 (FormatTok->HasUnescapedNewline || FormatTok->IsFirst)) {
1535 // If there is an unfinished unwrapped line, we flush the preprocessor
1536 // directives only after that unwrapped line was finished later.
1537 bool SwitchToPreprocessorLines =
1538 !Line->Tokens.empty() && CurrentLines == &Lines;
1539 ScopedLineState BlockState(*this, SwitchToPreprocessorLines);
1540 // Comments stored before the preprocessor directive need to be output
1541 // before the preprocessor directive, at the same level as the
1542 // preprocessor directive, as we consider them to apply to the directive.
1543 flushComments(isOnNewLine(*FormatTok));
1546 while (FormatTok->Type == TT_ConflictStart ||
1547 FormatTok->Type == TT_ConflictEnd ||
1548 FormatTok->Type == TT_ConflictAlternative) {
1549 if (FormatTok->Type == TT_ConflictStart) {
1550 conditionalCompilationStart(/*Unreachable=*/false);
1551 } else if (FormatTok->Type == TT_ConflictAlternative) {
1552 conditionalCompilationAlternative();
1553 } else if (FormatTok->Type == TT_ConflictEnd) {
1554 conditionalCompilationEnd();
1556 FormatTok = Tokens->getNextToken();
1557 FormatTok->MustBreakBefore = true;
1560 if (!PPStack.empty() && (PPStack.back() == PP_Unreachable) &&
1561 !Line->InPPDirective) {
1565 if (!FormatTok->Tok.is(tok::comment))
1567 if (isOnNewLine(*FormatTok) || FormatTok->IsFirst) {
1568 CommentsInCurrentLine = false;
1570 if (CommentsInCurrentLine) {
1571 pushToken(FormatTok);
1573 CommentsBeforeNextToken.push_back(FormatTok);
1578 void UnwrappedLineParser::pushToken(FormatToken *Tok) {
1579 Line->Tokens.push_back(UnwrappedLineNode(Tok));
1580 if (MustBreakBeforeNextToken) {
1581 Line->Tokens.back().Tok->MustBreakBefore = true;
1582 MustBreakBeforeNextToken = false;
1586 } // end namespace format
1587 } // end namespace clang