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.BreakBeforeBraces == FormatStyle::BS_Allman) {
158 Parser->addUnwrappedLine();
159 } else if (Style.BreakBeforeBraces == FormatStyle::BS_GNU) {
160 Parser->addUnwrappedLine();
164 ~CompoundStatementIndenter() { LineLevel = OldLineLevel; }
168 unsigned OldLineLevel;
173 class IndexedTokenSource : public FormatTokenSource {
175 IndexedTokenSource(ArrayRef<FormatToken *> Tokens)
176 : Tokens(Tokens), Position(-1) {}
178 FormatToken *getNextToken() override {
180 return Tokens[Position];
183 unsigned getPosition() override {
184 assert(Position >= 0);
188 FormatToken *setPosition(unsigned P) override {
190 return Tokens[Position];
193 void reset() { Position = -1; }
196 ArrayRef<FormatToken *> Tokens;
200 } // end anonymous namespace
202 UnwrappedLineParser::UnwrappedLineParser(const FormatStyle &Style,
203 const AdditionalKeywords &Keywords,
204 ArrayRef<FormatToken *> Tokens,
205 UnwrappedLineConsumer &Callback)
206 : Line(new UnwrappedLine), MustBreakBeforeNextToken(false),
207 CurrentLines(&Lines), Style(Style), Keywords(Keywords), Tokens(nullptr),
208 Callback(Callback), AllTokens(Tokens), PPBranchLevel(-1) {}
210 void UnwrappedLineParser::reset() {
212 Line.reset(new UnwrappedLine);
213 CommentsBeforeNextToken.clear();
215 MustBreakBeforeNextToken = false;
216 PreprocessorDirectives.clear();
217 CurrentLines = &Lines;
218 DeclarationScopeStack.clear();
222 void UnwrappedLineParser::parse() {
223 IndexedTokenSource TokenSource(AllTokens);
225 DEBUG(llvm::dbgs() << "----\n");
227 Tokens = &TokenSource;
232 // Create line with eof token.
233 pushToken(FormatTok);
236 for (SmallVectorImpl<UnwrappedLine>::iterator I = Lines.begin(),
239 Callback.consumeUnwrappedLine(*I);
241 Callback.finishRun();
243 while (!PPLevelBranchIndex.empty() &&
244 PPLevelBranchIndex.back() + 1 >= PPLevelBranchCount.back()) {
245 PPLevelBranchIndex.resize(PPLevelBranchIndex.size() - 1);
246 PPLevelBranchCount.resize(PPLevelBranchCount.size() - 1);
248 if (!PPLevelBranchIndex.empty()) {
249 ++PPLevelBranchIndex.back();
250 assert(PPLevelBranchIndex.size() == PPLevelBranchCount.size());
251 assert(PPLevelBranchIndex.back() <= PPLevelBranchCount.back());
253 } while (!PPLevelBranchIndex.empty());
256 void UnwrappedLineParser::parseFile() {
257 // The top-level context in a file always has declarations, except for pre-
258 // processor directives and JavaScript files.
259 bool MustBeDeclaration =
260 !Line->InPPDirective && Style.Language != FormatStyle::LK_JavaScript;
261 ScopedDeclarationState DeclarationState(*Line, DeclarationScopeStack,
263 parseLevel(/*HasOpeningBrace=*/false);
264 // Make sure to format the remaining tokens.
269 void UnwrappedLineParser::parseLevel(bool HasOpeningBrace) {
270 bool SwitchLabelEncountered = false;
272 switch (FormatTok->Tok.getKind()) {
278 // FIXME: Add parameter whether this can happen - if this happens, we must
279 // be in a non-declaration context.
280 parseBlock(/*MustBeDeclaration=*/false);
289 case tok::kw_default:
291 if (!SwitchLabelEncountered &&
292 (Style.IndentCaseLabels || (Line->InPPDirective && Line->Level == 1)))
294 SwitchLabelEncountered = true;
295 parseStructuralElement();
298 parseStructuralElement();
304 void UnwrappedLineParser::calculateBraceTypes(bool ExpectClassBody) {
305 // We'll parse forward through the tokens until we hit
306 // a closing brace or eof - note that getNextToken() will
307 // parse macros, so this will magically work inside macro
309 unsigned StoredPosition = Tokens->getPosition();
310 FormatToken *Tok = FormatTok;
311 // Keep a stack of positions of lbrace tokens. We will
312 // update information about whether an lbrace starts a
313 // braced init list or a different block during the loop.
314 SmallVector<FormatToken *, 8> LBraceStack;
315 assert(Tok->Tok.is(tok::l_brace));
317 // Get next none-comment token.
318 FormatToken *NextTok;
319 unsigned ReadTokens = 0;
321 NextTok = Tokens->getNextToken();
323 } while (NextTok->is(tok::comment));
325 switch (Tok->Tok.getKind()) {
327 Tok->BlockKind = BK_Unknown;
328 LBraceStack.push_back(Tok);
331 if (!LBraceStack.empty()) {
332 if (LBraceStack.back()->BlockKind == BK_Unknown) {
333 bool ProbablyBracedList = false;
334 if (Style.Language == FormatStyle::LK_Proto) {
335 ProbablyBracedList = NextTok->isOneOf(tok::comma, tok::r_square);
337 // Using OriginalColumn to distinguish between ObjC methods and
338 // binary operators is a bit hacky.
339 bool NextIsObjCMethod = NextTok->isOneOf(tok::plus, tok::minus) &&
340 NextTok->OriginalColumn == 0;
342 // If there is a comma, semicolon or right paren after the closing
343 // brace, we assume this is a braced initializer list. Note that
344 // regardless how we mark inner braces here, we will overwrite the
345 // BlockKind later if we parse a braced list (where all blocks
346 // inside are by default braced lists), or when we explicitly detect
347 // blocks (for example while parsing lambdas).
349 // We exclude + and - as they can be ObjC visibility modifiers.
351 NextTok->isOneOf(tok::comma, tok::period, tok::colon,
352 tok::r_paren, tok::r_square, tok::l_brace,
353 tok::l_paren, tok::ellipsis) ||
354 (NextTok->is(tok::semi) &&
355 (!ExpectClassBody || LBraceStack.size() != 1)) ||
356 (NextTok->isBinaryOperator() && !NextIsObjCMethod);
358 if (ProbablyBracedList) {
359 Tok->BlockKind = BK_BracedInit;
360 LBraceStack.back()->BlockKind = BK_BracedInit;
362 Tok->BlockKind = BK_Block;
363 LBraceStack.back()->BlockKind = BK_Block;
366 LBraceStack.pop_back();
377 if (!LBraceStack.empty())
378 LBraceStack.back()->BlockKind = BK_Block;
384 } while (Tok->Tok.isNot(tok::eof) && !LBraceStack.empty());
385 // Assume other blocks for all unclosed opening braces.
386 for (unsigned i = 0, e = LBraceStack.size(); i != e; ++i) {
387 if (LBraceStack[i]->BlockKind == BK_Unknown)
388 LBraceStack[i]->BlockKind = BK_Block;
391 FormatTok = Tokens->setPosition(StoredPosition);
394 void UnwrappedLineParser::parseBlock(bool MustBeDeclaration, bool AddLevel,
396 assert(FormatTok->Tok.is(tok::l_brace) && "'{' expected");
397 unsigned InitialLevel = Line->Level;
402 ScopedDeclarationState DeclarationState(*Line, DeclarationScopeStack,
406 parseLevel(/*HasOpeningBrace=*/true);
408 if (!FormatTok->Tok.is(tok::r_brace)) {
409 Line->Level = InitialLevel;
413 nextToken(); // Munch the closing brace.
414 if (MunchSemi && FormatTok->Tok.is(tok::semi))
416 Line->Level = InitialLevel;
419 static bool isGoogScope(const UnwrappedLine &Line) {
420 // FIXME: Closure-library specific stuff should not be hard-coded but be
422 if (Line.Tokens.size() < 4)
424 auto I = Line.Tokens.begin();
425 if (I->Tok->TokenText != "goog")
428 if (I->Tok->isNot(tok::period))
431 if (I->Tok->TokenText != "scope")
434 return I->Tok->is(tok::l_paren);
437 static bool ShouldBreakBeforeBrace(const FormatStyle &Style,
438 const FormatToken &InitialToken) {
439 switch (Style.BreakBeforeBraces) {
440 case FormatStyle::BS_Linux:
441 return InitialToken.isOneOf(tok::kw_namespace, tok::kw_class);
442 case FormatStyle::BS_Allman:
443 case FormatStyle::BS_GNU:
450 void UnwrappedLineParser::parseChildBlock() {
451 FormatTok->BlockKind = BK_Block;
455 Style.Language == FormatStyle::LK_JavaScript && isGoogScope(*Line);
456 ScopedLineState LineState(*this);
457 ScopedDeclarationState DeclarationState(*Line, DeclarationScopeStack,
458 /*MustBeDeclaration=*/false);
459 Line->Level += GoogScope ? 0 : 1;
460 parseLevel(/*HasOpeningBrace=*/true);
461 flushComments(isOnNewLine(*FormatTok));
462 Line->Level -= GoogScope ? 0 : 1;
467 void UnwrappedLineParser::parsePPDirective() {
468 assert(FormatTok->Tok.is(tok::hash) && "'#' expected");
469 ScopedMacroState MacroState(*Line, Tokens, FormatTok);
472 if (!FormatTok->Tok.getIdentifierInfo()) {
477 switch (FormatTok->Tok.getIdentifierInfo()->getPPKeywordID()) {
482 parsePPIf(/*IfDef=*/false);
486 parsePPIf(/*IfDef=*/true);
503 void UnwrappedLineParser::conditionalCompilationCondition(bool Unreachable) {
504 if (Unreachable || (!PPStack.empty() && PPStack.back() == PP_Unreachable))
505 PPStack.push_back(PP_Unreachable);
507 PPStack.push_back(PP_Conditional);
510 void UnwrappedLineParser::conditionalCompilationStart(bool Unreachable) {
512 assert(PPBranchLevel >= 0 && PPBranchLevel <= (int)PPLevelBranchIndex.size());
513 if (PPBranchLevel == (int)PPLevelBranchIndex.size()) {
514 PPLevelBranchIndex.push_back(0);
515 PPLevelBranchCount.push_back(0);
517 PPChainBranchIndex.push(0);
518 bool Skip = PPLevelBranchIndex[PPBranchLevel] > 0;
519 conditionalCompilationCondition(Unreachable || Skip);
522 void UnwrappedLineParser::conditionalCompilationAlternative() {
523 if (!PPStack.empty())
525 assert(PPBranchLevel < (int)PPLevelBranchIndex.size());
526 if (!PPChainBranchIndex.empty())
527 ++PPChainBranchIndex.top();
528 conditionalCompilationCondition(
529 PPBranchLevel >= 0 && !PPChainBranchIndex.empty() &&
530 PPLevelBranchIndex[PPBranchLevel] != PPChainBranchIndex.top());
533 void UnwrappedLineParser::conditionalCompilationEnd() {
534 assert(PPBranchLevel < (int)PPLevelBranchIndex.size());
535 if (PPBranchLevel >= 0 && !PPChainBranchIndex.empty()) {
536 if (PPChainBranchIndex.top() + 1 > PPLevelBranchCount[PPBranchLevel]) {
537 PPLevelBranchCount[PPBranchLevel] = PPChainBranchIndex.top() + 1;
540 // Guard against #endif's without #if.
541 if (PPBranchLevel > 0)
543 if (!PPChainBranchIndex.empty())
544 PPChainBranchIndex.pop();
545 if (!PPStack.empty())
549 void UnwrappedLineParser::parsePPIf(bool IfDef) {
551 bool IsLiteralFalse = (FormatTok->Tok.isLiteral() &&
552 FormatTok->Tok.getLiteralData() != nullptr &&
553 StringRef(FormatTok->Tok.getLiteralData(),
554 FormatTok->Tok.getLength()) == "0") ||
555 FormatTok->Tok.is(tok::kw_false);
556 conditionalCompilationStart(!IfDef && IsLiteralFalse);
560 void UnwrappedLineParser::parsePPElse() {
561 conditionalCompilationAlternative();
565 void UnwrappedLineParser::parsePPElIf() { parsePPElse(); }
567 void UnwrappedLineParser::parsePPEndIf() {
568 conditionalCompilationEnd();
572 void UnwrappedLineParser::parsePPDefine() {
575 if (FormatTok->Tok.getKind() != tok::identifier) {
580 if (FormatTok->Tok.getKind() == tok::l_paren &&
581 FormatTok->WhitespaceRange.getBegin() ==
582 FormatTok->WhitespaceRange.getEnd()) {
588 // Errors during a preprocessor directive can only affect the layout of the
589 // preprocessor directive, and thus we ignore them. An alternative approach
590 // would be to use the same approach we use on the file level (no
591 // re-indentation if there was a structural error) within the macro
596 void UnwrappedLineParser::parsePPUnknown() {
603 // Here we blacklist certain tokens that are not usually the first token in an
604 // unwrapped line. This is used in attempt to distinguish macro calls without
605 // trailing semicolons from other constructs split to several lines.
606 static bool tokenCanStartNewLine(const clang::Token &Tok) {
607 // Semicolon can be a null-statement, l_square can be a start of a macro or
608 // a C++11 attribute, but this doesn't seem to be common.
609 return Tok.isNot(tok::semi) && Tok.isNot(tok::l_brace) &&
610 Tok.isNot(tok::l_square) &&
611 // Tokens that can only be used as binary operators and a part of
612 // overloaded operator names.
613 Tok.isNot(tok::period) && Tok.isNot(tok::periodstar) &&
614 Tok.isNot(tok::arrow) && Tok.isNot(tok::arrowstar) &&
615 Tok.isNot(tok::less) && Tok.isNot(tok::greater) &&
616 Tok.isNot(tok::slash) && Tok.isNot(tok::percent) &&
617 Tok.isNot(tok::lessless) && Tok.isNot(tok::greatergreater) &&
618 Tok.isNot(tok::equal) && Tok.isNot(tok::plusequal) &&
619 Tok.isNot(tok::minusequal) && Tok.isNot(tok::starequal) &&
620 Tok.isNot(tok::slashequal) && Tok.isNot(tok::percentequal) &&
621 Tok.isNot(tok::ampequal) && Tok.isNot(tok::pipeequal) &&
622 Tok.isNot(tok::caretequal) && Tok.isNot(tok::greatergreaterequal) &&
623 Tok.isNot(tok::lesslessequal) &&
624 // Colon is used in labels, base class lists, initializer lists,
625 // range-based for loops, ternary operator, but should never be the
626 // first token in an unwrapped line.
627 Tok.isNot(tok::colon) &&
628 // 'noexcept' is a trailing annotation.
629 Tok.isNot(tok::kw_noexcept);
632 void UnwrappedLineParser::parseStructuralElement() {
633 assert(!FormatTok->Tok.is(tok::l_brace));
634 switch (FormatTok->Tok.getKind()) {
637 if (FormatTok->Tok.is(tok::l_brace)) {
641 switch (FormatTok->Tok.getObjCKeywordID()) {
642 case tok::objc_public:
643 case tok::objc_protected:
644 case tok::objc_package:
645 case tok::objc_private:
646 return parseAccessSpecifier();
647 case tok::objc_interface:
648 case tok::objc_implementation:
649 return parseObjCInterfaceOrImplementation();
650 case tok::objc_protocol:
651 return parseObjCProtocol();
653 return; // Handled by the caller.
654 case tok::objc_optional:
655 case tok::objc_required:
660 // This branch isn't strictly necessary (the kw_try case below would
661 // do this too after the tok::at is parsed above). But be explicit.
670 if (FormatTok->is(tok::l_brace)) {
671 FormatTok->Type = TT_InlineASMBrace;
673 while (FormatTok && FormatTok->isNot(tok::eof)) {
674 if (FormatTok->is(tok::r_brace)) {
675 FormatTok->Type = TT_InlineASMBrace;
680 FormatTok->Finalized = true;
685 case tok::kw_namespace:
690 if (FormatTok->Tok.is(tok::kw_namespace)) {
696 case tok::kw_protected:
697 case tok::kw_private:
698 if (Style.Language == FormatStyle::LK_Java ||
699 Style.Language == FormatStyle::LK_JavaScript)
702 parseAccessSpecifier();
709 parseForOrWhileLoop();
717 case tok::kw_default:
730 if (FormatTok->Tok.is(tok::string_literal)) {
732 if (FormatTok->Tok.is(tok::l_brace)) {
733 parseBlock(/*MustBeDeclaration=*/true, /*AddLevel=*/false);
740 if (Style.Language == FormatStyle::LK_JavaScript) {
741 parseJavaScriptEs6ImportExport();
745 case tok::identifier:
746 if (FormatTok->is(TT_ForEachMacro)) {
747 parseForOrWhileLoop();
750 if (Style.Language == FormatStyle::LK_JavaScript &&
751 FormatTok->is(Keywords.kw_import)) {
752 parseJavaScriptEs6ImportExport();
755 if (FormatTok->is(Keywords.kw_signals)) {
757 if (FormatTok->is(tok::colon)) {
763 // In all other cases, parse the declaration.
769 switch (FormatTok->Tok.getKind()) {
772 if (FormatTok->Tok.is(tok::l_brace))
776 // parseEnum falls through and does not yet add an unwrapped line as an
777 // enum definition can start a structural element.
779 // This does not apply for Java and JavaScript.
780 if (Style.Language == FormatStyle::LK_Java ||
781 Style.Language == FormatStyle::LK_JavaScript) {
786 case tok::kw_typedef:
788 if (FormatTok->isOneOf(Keywords.kw_NS_ENUM, Keywords.kw_NS_OPTIONS,
789 Keywords.kw_CF_ENUM, Keywords.kw_CF_OPTIONS))
795 // parseRecord falls through and does not yet add an unwrapped line as a
796 // record declaration or definition can start a structural element.
798 // This does not apply for Java and JavaScript.
799 if (Style.Language == FormatStyle::LK_Java ||
800 Style.Language == FormatStyle::LK_JavaScript) {
807 // In Java, classes have an implicit static member "class".
808 if (Style.Language == FormatStyle::LK_Java && FormatTok &&
809 FormatTok->is(tok::kw_class))
824 if (FormatTok->Tok.isAnyIdentifier() ||
825 FormatTok->isSimpleTypeSpecifier())
827 if (FormatTok->is(tok::l_paren))
829 if (FormatTok->is(tok::l_brace))
833 if (!tryToParseBracedList()) {
834 // A block outside of parentheses must be the last part of a
835 // structural element.
836 // FIXME: Figure out cases where this is not true, and add projections
837 // for them (the one we know is missing are lambdas).
838 if (Style.BreakBeforeBraces != FormatStyle::BS_Attach)
840 FormatTok->Type = TT_FunctionLBrace;
841 parseBlock(/*MustBeDeclaration=*/false);
845 // Otherwise this was a braced init list, and the structural
846 // element continues.
849 // We arrive here when parsing function-try blocks.
852 case tok::identifier: {
853 // Parse function literal unless 'function' is the first token in a line
854 // in which case this should be treated as a free-standing function.
855 if (Style.Language == FormatStyle::LK_JavaScript &&
856 FormatTok->is(Keywords.kw_function) && Line->Tokens.size() > 0) {
857 tryToParseJSFunction();
860 if ((Style.Language == FormatStyle::LK_JavaScript ||
861 Style.Language == FormatStyle::LK_Java) &&
862 FormatTok->is(Keywords.kw_interface)) {
868 StringRef Text = FormatTok->TokenText;
870 if (Line->Tokens.size() == 1 &&
871 // JS doesn't have macros, and within classes colons indicate fields,
873 Style.Language != FormatStyle::LK_JavaScript) {
874 if (FormatTok->Tok.is(tok::colon) && !Line->MustBeDeclaration) {
878 // Recognize function-like macro usages without trailing semicolon as
879 // well as free-standing macros like Q_OBJECT.
880 bool FunctionLike = FormatTok->is(tok::l_paren);
884 bool FollowedByNewline =
885 CommentsBeforeNextToken.empty()
886 ? FormatTok->NewlinesBefore > 0
887 : CommentsBeforeNextToken.front()->NewlinesBefore > 0;
889 if (FollowedByNewline && (Text.size() >= 5 || FunctionLike) &&
890 tokenCanStartNewLine(FormatTok->Tok) && Text == Text.upper()) {
898 // Fat arrows (=>) have tok::TokenKind tok::equal but TokenType
899 // TT_JsFatArrow. The always start an expression or a child block if
900 // followed by a curly.
901 if (FormatTok->is(TT_JsFatArrow)) {
903 if (FormatTok->is(tok::l_brace))
909 if (FormatTok->Tok.is(tok::l_brace)) {
926 bool UnwrappedLineParser::tryToParseLambda() {
927 if (Style.Language != FormatStyle::LK_Cpp) {
931 // FIXME: This is a dirty way to access the previous token. Find a better
933 if (!Line->Tokens.empty() &&
934 (Line->Tokens.back().Tok->isOneOf(tok::identifier, tok::kw_operator,
935 tok::kw_new, tok::kw_delete) ||
936 Line->Tokens.back().Tok->closesScope() ||
937 Line->Tokens.back().Tok->isSimpleTypeSpecifier())) {
941 assert(FormatTok->is(tok::l_square));
942 FormatToken &LSquare = *FormatTok;
943 if (!tryToParseLambdaIntroducer())
946 while (FormatTok->isNot(tok::l_brace)) {
947 if (FormatTok->isSimpleTypeSpecifier()) {
951 switch (FormatTok->Tok.getKind()) {
963 case tok::identifier:
964 case tok::coloncolon:
965 case tok::kw_mutable:
969 FormatTok->Type = TT_LambdaArrow;
976 LSquare.Type = TT_LambdaLSquare;
981 bool UnwrappedLineParser::tryToParseLambdaIntroducer() {
983 if (FormatTok->is(tok::equal)) {
985 if (FormatTok->is(tok::r_square)) {
989 if (FormatTok->isNot(tok::comma))
992 } else if (FormatTok->is(tok::amp)) {
994 if (FormatTok->is(tok::r_square)) {
998 if (!FormatTok->isOneOf(tok::comma, tok::identifier)) {
1001 if (FormatTok->is(tok::comma))
1003 } else if (FormatTok->is(tok::r_square)) {
1008 if (FormatTok->is(tok::amp))
1010 if (!FormatTok->isOneOf(tok::identifier, tok::kw_this))
1013 if (FormatTok->is(tok::ellipsis))
1015 if (FormatTok->is(tok::comma)) {
1017 } else if (FormatTok->is(tok::r_square)) {
1027 void UnwrappedLineParser::tryToParseJSFunction() {
1030 // Consume function name.
1031 if (FormatTok->is(tok::identifier))
1034 if (FormatTok->isNot(tok::l_paren))
1037 // Parse formal parameter list.
1040 if (FormatTok->is(tok::colon)) {
1041 // Parse a type definition.
1044 // Eat the type declaration. For braced inline object types, balance braces,
1045 // otherwise just parse until finding an l_brace for the function body.
1046 if (FormatTok->is(tok::l_brace))
1047 tryToParseBracedList();
1049 while (FormatTok->isNot(tok::l_brace) && !eof())
1056 bool UnwrappedLineParser::tryToParseBracedList() {
1057 if (FormatTok->BlockKind == BK_Unknown)
1058 calculateBraceTypes();
1059 assert(FormatTok->BlockKind != BK_Unknown);
1060 if (FormatTok->BlockKind == BK_Block)
1066 bool UnwrappedLineParser::parseBracedList(bool ContinueOnSemicolons) {
1067 bool HasError = false;
1070 // FIXME: Once we have an expression parser in the UnwrappedLineParser,
1071 // replace this by using parseAssigmentExpression() inside.
1073 if (Style.Language == FormatStyle::LK_JavaScript) {
1074 if (FormatTok->is(Keywords.kw_function)) {
1075 tryToParseJSFunction();
1078 if (FormatTok->is(TT_JsFatArrow)) {
1080 // Fat arrows can be followed by simple expressions or by child blocks
1082 if (FormatTok->is(tok::l_brace)) {
1088 switch (FormatTok->Tok.getKind()) {
1091 if (FormatTok->is(tok::l_brace)) {
1099 // Assume there are no blocks inside a braced init list apart
1100 // from the ones we explicitly parse out (like lambdas).
1101 FormatTok->BlockKind = BK_BracedInit;
1105 // JavaScript can just have free standing methods and getters/setters in
1106 // object literals. Detect them by a "{" following ")".
1107 if (Style.Language == FormatStyle::LK_JavaScript) {
1109 if (FormatTok->is(tok::l_brace))
1120 if (!ContinueOnSemicolons)
1135 void UnwrappedLineParser::parseParens() {
1136 assert(FormatTok->Tok.is(tok::l_paren) && "'(' expected.");
1139 switch (FormatTok->Tok.getKind()) {
1142 if (Style.Language == FormatStyle::LK_Java && FormatTok->is(tok::l_brace))
1149 // A "}" inside parenthesis is an error if there wasn't a matching "{".
1155 if (!tryToParseBracedList())
1160 if (FormatTok->Tok.is(tok::l_brace))
1163 case tok::identifier:
1164 if (Style.Language == FormatStyle::LK_JavaScript &&
1165 FormatTok->is(Keywords.kw_function))
1166 tryToParseJSFunction();
1177 void UnwrappedLineParser::parseSquare() {
1178 assert(FormatTok->Tok.is(tok::l_square) && "'[' expected.");
1179 if (tryToParseLambda())
1182 switch (FormatTok->Tok.getKind()) {
1190 // A "}" inside parenthesis is an error if there wasn't a matching "{".
1195 case tok::l_brace: {
1196 if (!tryToParseBracedList())
1202 if (FormatTok->Tok.is(tok::l_brace))
1212 void UnwrappedLineParser::parseIfThenElse() {
1213 assert(FormatTok->Tok.is(tok::kw_if) && "'if' expected");
1215 if (FormatTok->Tok.is(tok::l_paren))
1217 bool NeedsUnwrappedLine = false;
1218 if (FormatTok->Tok.is(tok::l_brace)) {
1219 CompoundStatementIndenter Indenter(this, Style, Line->Level);
1220 parseBlock(/*MustBeDeclaration=*/false);
1221 if (Style.BreakBeforeBraces == FormatStyle::BS_Allman ||
1222 Style.BreakBeforeBraces == FormatStyle::BS_GNU) {
1225 NeedsUnwrappedLine = true;
1230 parseStructuralElement();
1233 if (FormatTok->Tok.is(tok::kw_else)) {
1234 if (Style.BreakBeforeBraces == FormatStyle::BS_Stroustrup)
1237 if (FormatTok->Tok.is(tok::l_brace)) {
1238 CompoundStatementIndenter Indenter(this, Style, Line->Level);
1239 parseBlock(/*MustBeDeclaration=*/false);
1241 } else if (FormatTok->Tok.is(tok::kw_if)) {
1246 parseStructuralElement();
1249 } else if (NeedsUnwrappedLine) {
1254 void UnwrappedLineParser::parseTryCatch() {
1255 assert(FormatTok->isOneOf(tok::kw_try, tok::kw___try) && "'try' expected");
1257 bool NeedsUnwrappedLine = false;
1258 if (FormatTok->is(tok::colon)) {
1259 // We are in a function try block, what comes is an initializer list.
1261 while (FormatTok->is(tok::identifier)) {
1263 if (FormatTok->is(tok::l_paren))
1265 if (FormatTok->is(tok::comma))
1269 // Parse try with resource.
1270 if (Style.Language == FormatStyle::LK_Java && FormatTok->is(tok::l_paren)) {
1273 if (FormatTok->is(tok::l_brace)) {
1274 CompoundStatementIndenter Indenter(this, Style, Line->Level);
1275 parseBlock(/*MustBeDeclaration=*/false);
1276 if (Style.BreakBeforeBraces == FormatStyle::BS_Allman ||
1277 Style.BreakBeforeBraces == FormatStyle::BS_GNU ||
1278 Style.BreakBeforeBraces == FormatStyle::BS_Stroustrup) {
1281 NeedsUnwrappedLine = true;
1283 } else if (!FormatTok->is(tok::kw_catch)) {
1284 // The C++ standard requires a compound-statement after a try.
1285 // If there's none, we try to assume there's a structuralElement
1286 // and try to continue.
1289 parseStructuralElement();
1293 if (FormatTok->is(tok::at))
1295 if (!(FormatTok->isOneOf(tok::kw_catch, Keywords.kw___except,
1296 tok::kw___finally) ||
1297 ((Style.Language == FormatStyle::LK_Java ||
1298 Style.Language == FormatStyle::LK_JavaScript) &&
1299 FormatTok->is(Keywords.kw_finally)) ||
1300 (FormatTok->Tok.isObjCAtKeyword(tok::objc_catch) ||
1301 FormatTok->Tok.isObjCAtKeyword(tok::objc_finally))))
1304 while (FormatTok->isNot(tok::l_brace)) {
1305 if (FormatTok->is(tok::l_paren)) {
1309 if (FormatTok->isOneOf(tok::semi, tok::r_brace, tok::eof))
1313 NeedsUnwrappedLine = false;
1314 CompoundStatementIndenter Indenter(this, Style, Line->Level);
1315 parseBlock(/*MustBeDeclaration=*/false);
1316 if (Style.BreakBeforeBraces == FormatStyle::BS_Allman ||
1317 Style.BreakBeforeBraces == FormatStyle::BS_GNU ||
1318 Style.BreakBeforeBraces == FormatStyle::BS_Stroustrup) {
1321 NeedsUnwrappedLine = true;
1324 if (NeedsUnwrappedLine) {
1329 void UnwrappedLineParser::parseNamespace() {
1330 assert(FormatTok->Tok.is(tok::kw_namespace) && "'namespace' expected");
1332 const FormatToken &InitialToken = *FormatTok;
1334 if (FormatTok->Tok.is(tok::identifier))
1336 if (FormatTok->Tok.is(tok::l_brace)) {
1337 if (ShouldBreakBeforeBrace(Style, InitialToken))
1340 bool AddLevel = Style.NamespaceIndentation == FormatStyle::NI_All ||
1341 (Style.NamespaceIndentation == FormatStyle::NI_Inner &&
1342 DeclarationScopeStack.size() > 1);
1343 parseBlock(/*MustBeDeclaration=*/true, AddLevel);
1344 // Munch the semicolon after a namespace. This is more common than one would
1345 // think. Puttin the semicolon into its own line is very ugly.
1346 if (FormatTok->Tok.is(tok::semi))
1350 // FIXME: Add error handling.
1353 void UnwrappedLineParser::parseNew() {
1354 assert(FormatTok->is(tok::kw_new) && "'new' expected");
1356 if (Style.Language != FormatStyle::LK_Java)
1359 // In Java, we can parse everything up to the parens, which aren't optional.
1361 // There should not be a ;, { or } before the new's open paren.
1362 if (FormatTok->isOneOf(tok::semi, tok::l_brace, tok::r_brace))
1365 // Consume the parens.
1366 if (FormatTok->is(tok::l_paren)) {
1369 // If there is a class body of an anonymous class, consume that as child.
1370 if (FormatTok->is(tok::l_brace))
1378 void UnwrappedLineParser::parseForOrWhileLoop() {
1379 assert(FormatTok->isOneOf(tok::kw_for, tok::kw_while, TT_ForEachMacro) &&
1380 "'for', 'while' or foreach macro expected");
1382 if (FormatTok->Tok.is(tok::l_paren))
1384 if (FormatTok->Tok.is(tok::l_brace)) {
1385 CompoundStatementIndenter Indenter(this, Style, Line->Level);
1386 parseBlock(/*MustBeDeclaration=*/false);
1391 parseStructuralElement();
1396 void UnwrappedLineParser::parseDoWhile() {
1397 assert(FormatTok->Tok.is(tok::kw_do) && "'do' expected");
1399 if (FormatTok->Tok.is(tok::l_brace)) {
1400 CompoundStatementIndenter Indenter(this, Style, Line->Level);
1401 parseBlock(/*MustBeDeclaration=*/false);
1402 if (Style.BreakBeforeBraces == FormatStyle::BS_GNU)
1407 parseStructuralElement();
1411 // FIXME: Add error handling.
1412 if (!FormatTok->Tok.is(tok::kw_while)) {
1418 parseStructuralElement();
1421 void UnwrappedLineParser::parseLabel() {
1423 unsigned OldLineLevel = Line->Level;
1424 if (Line->Level > 1 || (!Line->InPPDirective && Line->Level > 0))
1426 if (CommentsBeforeNextToken.empty() && FormatTok->Tok.is(tok::l_brace)) {
1427 CompoundStatementIndenter Indenter(this, Style, Line->Level);
1428 parseBlock(/*MustBeDeclaration=*/false);
1429 if (FormatTok->Tok.is(tok::kw_break)) {
1430 // "break;" after "}" on its own line only for BS_Allman and BS_GNU
1431 if (Style.BreakBeforeBraces == FormatStyle::BS_Allman ||
1432 Style.BreakBeforeBraces == FormatStyle::BS_GNU) {
1435 parseStructuralElement();
1439 if (FormatTok->is(tok::semi))
1443 Line->Level = OldLineLevel;
1446 void UnwrappedLineParser::parseCaseLabel() {
1447 assert(FormatTok->Tok.is(tok::kw_case) && "'case' expected");
1448 // FIXME: fix handling of complex expressions here.
1451 } while (!eof() && !FormatTok->Tok.is(tok::colon));
1455 void UnwrappedLineParser::parseSwitch() {
1456 assert(FormatTok->Tok.is(tok::kw_switch) && "'switch' expected");
1458 if (FormatTok->Tok.is(tok::l_paren))
1460 if (FormatTok->Tok.is(tok::l_brace)) {
1461 CompoundStatementIndenter Indenter(this, Style, Line->Level);
1462 parseBlock(/*MustBeDeclaration=*/false);
1467 parseStructuralElement();
1472 void UnwrappedLineParser::parseAccessSpecifier() {
1474 // Understand Qt's slots.
1475 if (FormatTok->isOneOf(Keywords.kw_slots, Keywords.kw_qslots))
1477 // Otherwise, we don't know what it is, and we'd better keep the next token.
1478 if (FormatTok->Tok.is(tok::colon))
1483 void UnwrappedLineParser::parseEnum() {
1484 // Won't be 'enum' for NS_ENUMs.
1485 if (FormatTok->Tok.is(tok::kw_enum))
1488 // Eat up enum class ...
1489 if (FormatTok->Tok.is(tok::kw_class) || FormatTok->Tok.is(tok::kw_struct))
1492 while (FormatTok->Tok.getIdentifierInfo() ||
1493 FormatTok->isOneOf(tok::colon, tok::coloncolon, tok::less,
1494 tok::greater, tok::comma, tok::question)) {
1496 // We can have macros or attributes in between 'enum' and the enum name.
1497 if (FormatTok->is(tok::l_paren))
1499 if (FormatTok->is(tok::identifier)) {
1501 // If there are two identifiers in a row, this is likely an elaborate
1502 // return type. In Java, this can be "implements", etc.
1503 if (Style.Language == FormatStyle::LK_Cpp &&
1504 FormatTok->is(tok::identifier))
1509 // Just a declaration or something is wrong.
1510 if (FormatTok->isNot(tok::l_brace))
1512 FormatTok->BlockKind = BK_Block;
1514 if (Style.Language == FormatStyle::LK_Java) {
1515 // Java enums are different.
1516 parseJavaEnumBody();
1521 bool HasError = !parseBracedList(/*ContinueOnSemicolons=*/true);
1523 if (FormatTok->is(tok::semi))
1528 // There is no addUnwrappedLine() here so that we fall through to parsing a
1529 // structural element afterwards. Thus, in "enum A {} n, m;",
1530 // "} n, m;" will end up in one unwrapped line.
1533 void UnwrappedLineParser::parseJavaEnumBody() {
1534 // Determine whether the enum is simple, i.e. does not have a semicolon or
1535 // constants with class bodies. Simple enums can be formatted like braced
1536 // lists, contracted to a single line, etc.
1537 unsigned StoredPosition = Tokens->getPosition();
1538 bool IsSimple = true;
1539 FormatToken *Tok = Tokens->getNextToken();
1541 if (Tok->is(tok::r_brace))
1543 if (Tok->isOneOf(tok::l_brace, tok::semi)) {
1547 // FIXME: This will also mark enums with braces in the arguments to enum
1548 // constants as "not simple". This is probably fine in practice, though.
1549 Tok = Tokens->getNextToken();
1551 FormatTok = Tokens->setPosition(StoredPosition);
1559 // Parse the body of a more complex enum.
1560 // First add a line for everything up to the "{".
1565 // Parse the enum constants.
1567 if (FormatTok->is(tok::l_brace)) {
1568 // Parse the constant's class body.
1569 parseBlock(/*MustBeDeclaration=*/true, /*AddLevel=*/true,
1570 /*MunchSemi=*/false);
1571 } else if (FormatTok->is(tok::l_paren)) {
1573 } else if (FormatTok->is(tok::comma)) {
1576 } else if (FormatTok->is(tok::semi)) {
1580 } else if (FormatTok->is(tok::r_brace)) {
1588 // Parse the class body after the enum's ";" if any.
1589 parseLevel(/*HasOpeningBrace=*/true);
1595 void UnwrappedLineParser::parseRecord() {
1596 const FormatToken &InitialToken = *FormatTok;
1599 // The actual identifier can be a nested name specifier, and in macros
1600 // it is often token-pasted.
1601 while (FormatTok->isOneOf(tok::identifier, tok::coloncolon, tok::hashhash,
1602 tok::kw___attribute, tok::kw___declspec,
1604 ((Style.Language == FormatStyle::LK_Java ||
1605 Style.Language == FormatStyle::LK_JavaScript) &&
1606 FormatTok->isOneOf(tok::period, tok::comma))) {
1607 bool IsNonMacroIdentifier =
1608 FormatTok->is(tok::identifier) &&
1609 FormatTok->TokenText != FormatTok->TokenText.upper();
1611 // We can have macros or attributes in between 'class' and the class name.
1612 if (!IsNonMacroIdentifier && FormatTok->Tok.is(tok::l_paren))
1616 // Note that parsing away template declarations here leads to incorrectly
1617 // accepting function declarations as record declarations.
1618 // In general, we cannot solve this problem. Consider:
1619 // class A<int> B() {}
1620 // which can be a function definition or a class definition when B() is a
1621 // macro. If we find enough real-world cases where this is a problem, we
1622 // can parse for the 'template' keyword in the beginning of the statement,
1623 // and thus rule out the record production in case there is no template
1624 // (this would still leave us with an ambiguity between template function
1625 // and class declarations).
1626 if (FormatTok->isOneOf(tok::colon, tok::less)) {
1628 if (FormatTok->is(tok::l_brace)) {
1629 calculateBraceTypes(/*ExpectClassBody=*/true);
1630 if (!tryToParseBracedList())
1633 if (FormatTok->Tok.is(tok::semi))
1638 if (FormatTok->Tok.is(tok::l_brace)) {
1639 if (ShouldBreakBeforeBrace(Style, InitialToken))
1642 parseBlock(/*MustBeDeclaration=*/true, /*AddLevel=*/true,
1643 /*MunchSemi=*/false);
1645 // There is no addUnwrappedLine() here so that we fall through to parsing a
1646 // structural element afterwards. Thus, in "class A {} n, m;",
1647 // "} n, m;" will end up in one unwrapped line.
1650 void UnwrappedLineParser::parseObjCProtocolList() {
1651 assert(FormatTok->Tok.is(tok::less) && "'<' expected.");
1654 while (!eof() && FormatTok->Tok.isNot(tok::greater));
1655 nextToken(); // Skip '>'.
1658 void UnwrappedLineParser::parseObjCUntilAtEnd() {
1660 if (FormatTok->Tok.isObjCAtKeyword(tok::objc_end)) {
1665 if (FormatTok->is(tok::l_brace)) {
1666 parseBlock(/*MustBeDeclaration=*/false);
1667 // In ObjC interfaces, nothing should be following the "}".
1669 } else if (FormatTok->is(tok::r_brace)) {
1670 // Ignore stray "}". parseStructuralElement doesn't consume them.
1674 parseStructuralElement();
1679 void UnwrappedLineParser::parseObjCInterfaceOrImplementation() {
1681 nextToken(); // interface name
1683 // @interface can be followed by either a base class, or a category.
1684 if (FormatTok->Tok.is(tok::colon)) {
1686 nextToken(); // base class name
1687 } else if (FormatTok->Tok.is(tok::l_paren))
1688 // Skip category, if present.
1691 if (FormatTok->Tok.is(tok::less))
1692 parseObjCProtocolList();
1694 if (FormatTok->Tok.is(tok::l_brace)) {
1695 if (Style.BreakBeforeBraces == FormatStyle::BS_Allman ||
1696 Style.BreakBeforeBraces == FormatStyle::BS_GNU)
1698 parseBlock(/*MustBeDeclaration=*/true);
1701 // With instance variables, this puts '}' on its own line. Without instance
1702 // variables, this ends the @interface line.
1705 parseObjCUntilAtEnd();
1708 void UnwrappedLineParser::parseObjCProtocol() {
1710 nextToken(); // protocol name
1712 if (FormatTok->Tok.is(tok::less))
1713 parseObjCProtocolList();
1715 // Check for protocol declaration.
1716 if (FormatTok->Tok.is(tok::semi)) {
1718 return addUnwrappedLine();
1722 parseObjCUntilAtEnd();
1725 void UnwrappedLineParser::parseJavaScriptEs6ImportExport() {
1726 assert(FormatTok->isOneOf(Keywords.kw_import, tok::kw_export));
1729 // Consume the "default" in "export default class/function".
1730 if (FormatTok->is(tok::kw_default))
1733 // Consume "function" and "default function", so that these get parsed as
1734 // free-standing JS functions, i.e. do not require a trailing semicolon.
1735 if (FormatTok->is(Keywords.kw_function)) {
1740 if (FormatTok->isOneOf(tok::kw_const, tok::kw_class, tok::kw_enum,
1742 return; // Fall through to parsing the corresponding structure.
1744 if (FormatTok->is(tok::l_brace)) {
1745 FormatTok->BlockKind = BK_Block;
1749 while (!eof() && FormatTok->isNot(tok::semi) &&
1750 FormatTok->isNot(tok::l_brace)) {
1755 LLVM_ATTRIBUTE_UNUSED static void printDebugInfo(const UnwrappedLine &Line,
1756 StringRef Prefix = "") {
1757 llvm::dbgs() << Prefix << "Line(" << Line.Level << ")"
1758 << (Line.InPPDirective ? " MACRO" : "") << ": ";
1759 for (std::list<UnwrappedLineNode>::const_iterator I = Line.Tokens.begin(),
1760 E = Line.Tokens.end();
1762 llvm::dbgs() << I->Tok->Tok.getName() << "[" << I->Tok->Type << "] ";
1764 for (std::list<UnwrappedLineNode>::const_iterator I = Line.Tokens.begin(),
1765 E = Line.Tokens.end();
1767 const UnwrappedLineNode &Node = *I;
1768 for (SmallVectorImpl<UnwrappedLine>::const_iterator
1769 I = Node.Children.begin(),
1770 E = Node.Children.end();
1772 printDebugInfo(*I, "\nChild: ");
1775 llvm::dbgs() << "\n";
1778 void UnwrappedLineParser::addUnwrappedLine() {
1779 if (Line->Tokens.empty())
1782 if (CurrentLines == &Lines)
1783 printDebugInfo(*Line);
1785 CurrentLines->push_back(std::move(*Line));
1786 Line->Tokens.clear();
1787 if (CurrentLines == &Lines && !PreprocessorDirectives.empty()) {
1788 CurrentLines->append(
1789 std::make_move_iterator(PreprocessorDirectives.begin()),
1790 std::make_move_iterator(PreprocessorDirectives.end()));
1791 PreprocessorDirectives.clear();
1795 bool UnwrappedLineParser::eof() const { return FormatTok->Tok.is(tok::eof); }
1797 bool UnwrappedLineParser::isOnNewLine(const FormatToken &FormatTok) {
1798 return (Line->InPPDirective || FormatTok.HasUnescapedNewline) &&
1799 FormatTok.NewlinesBefore > 0;
1802 void UnwrappedLineParser::flushComments(bool NewlineBeforeNext) {
1803 bool JustComments = Line->Tokens.empty();
1804 for (SmallVectorImpl<FormatToken *>::const_iterator
1805 I = CommentsBeforeNextToken.begin(),
1806 E = CommentsBeforeNextToken.end();
1808 if (isOnNewLine(**I) && JustComments)
1812 if (NewlineBeforeNext && JustComments)
1814 CommentsBeforeNextToken.clear();
1817 void UnwrappedLineParser::nextToken() {
1820 flushComments(isOnNewLine(*FormatTok));
1821 pushToken(FormatTok);
1825 void UnwrappedLineParser::readToken() {
1826 bool CommentsInCurrentLine = true;
1828 FormatTok = Tokens->getNextToken();
1830 while (!Line->InPPDirective && FormatTok->Tok.is(tok::hash) &&
1831 (FormatTok->HasUnescapedNewline || FormatTok->IsFirst)) {
1832 // If there is an unfinished unwrapped line, we flush the preprocessor
1833 // directives only after that unwrapped line was finished later.
1834 bool SwitchToPreprocessorLines = !Line->Tokens.empty();
1835 ScopedLineState BlockState(*this, SwitchToPreprocessorLines);
1836 // Comments stored before the preprocessor directive need to be output
1837 // before the preprocessor directive, at the same level as the
1838 // preprocessor directive, as we consider them to apply to the directive.
1839 flushComments(isOnNewLine(*FormatTok));
1842 while (FormatTok->Type == TT_ConflictStart ||
1843 FormatTok->Type == TT_ConflictEnd ||
1844 FormatTok->Type == TT_ConflictAlternative) {
1845 if (FormatTok->Type == TT_ConflictStart) {
1846 conditionalCompilationStart(/*Unreachable=*/false);
1847 } else if (FormatTok->Type == TT_ConflictAlternative) {
1848 conditionalCompilationAlternative();
1849 } else if (FormatTok->Type == TT_ConflictEnd) {
1850 conditionalCompilationEnd();
1852 FormatTok = Tokens->getNextToken();
1853 FormatTok->MustBreakBefore = true;
1856 if (!PPStack.empty() && (PPStack.back() == PP_Unreachable) &&
1857 !Line->InPPDirective) {
1861 if (!FormatTok->Tok.is(tok::comment))
1863 if (isOnNewLine(*FormatTok) || FormatTok->IsFirst) {
1864 CommentsInCurrentLine = false;
1866 if (CommentsInCurrentLine) {
1867 pushToken(FormatTok);
1869 CommentsBeforeNextToken.push_back(FormatTok);
1874 void UnwrappedLineParser::pushToken(FormatToken *Tok) {
1875 Line->Tokens.push_back(UnwrappedLineNode(Tok));
1876 if (MustBreakBeforeNextToken) {
1877 Line->Tokens.back().Tok->MustBreakBefore = true;
1878 MustBreakBeforeNextToken = false;
1882 } // end namespace format
1883 } // end namespace clang