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());
257 void UnwrappedLineParser::parseFile() {
258 // The top-level context in a file always has declarations, except for pre-
259 // processor directives and JavaScript files.
260 bool MustBeDeclaration =
261 !Line->InPPDirective && Style.Language != FormatStyle::LK_JavaScript;
262 ScopedDeclarationState DeclarationState(*Line, DeclarationScopeStack,
264 parseLevel(/*HasOpeningBrace=*/false);
265 // Make sure to format the remaining tokens.
270 void UnwrappedLineParser::parseLevel(bool HasOpeningBrace) {
271 bool SwitchLabelEncountered = false;
273 switch (FormatTok->Tok.getKind()) {
279 // FIXME: Add parameter whether this can happen - if this happens, we must
280 // be in a non-declaration context.
281 parseBlock(/*MustBeDeclaration=*/false);
290 case tok::kw_default:
292 if (!SwitchLabelEncountered &&
293 (Style.IndentCaseLabels || (Line->InPPDirective && Line->Level == 1)))
295 SwitchLabelEncountered = true;
296 parseStructuralElement();
299 parseStructuralElement();
305 void UnwrappedLineParser::calculateBraceTypes(bool ExpectClassBody) {
306 // We'll parse forward through the tokens until we hit
307 // a closing brace or eof - note that getNextToken() will
308 // parse macros, so this will magically work inside macro
310 unsigned StoredPosition = Tokens->getPosition();
311 FormatToken *Tok = FormatTok;
312 // Keep a stack of positions of lbrace tokens. We will
313 // update information about whether an lbrace starts a
314 // braced init list or a different block during the loop.
315 SmallVector<FormatToken *, 8> LBraceStack;
316 assert(Tok->Tok.is(tok::l_brace));
318 // Get next none-comment token.
319 FormatToken *NextTok;
320 unsigned ReadTokens = 0;
322 NextTok = Tokens->getNextToken();
324 } while (NextTok->is(tok::comment));
326 switch (Tok->Tok.getKind()) {
328 Tok->BlockKind = BK_Unknown;
329 LBraceStack.push_back(Tok);
332 if (!LBraceStack.empty()) {
333 if (LBraceStack.back()->BlockKind == BK_Unknown) {
334 bool ProbablyBracedList = false;
335 if (Style.Language == FormatStyle::LK_Proto) {
336 ProbablyBracedList = NextTok->isOneOf(tok::comma, tok::r_square);
338 // Using OriginalColumn to distinguish between ObjC methods and
339 // binary operators is a bit hacky.
340 bool NextIsObjCMethod = NextTok->isOneOf(tok::plus, tok::minus) &&
341 NextTok->OriginalColumn == 0;
343 // If there is a comma, semicolon or right paren after the closing
344 // brace, we assume this is a braced initializer list. Note that
345 // regardless how we mark inner braces here, we will overwrite the
346 // BlockKind later if we parse a braced list (where all blocks
347 // inside are by default braced lists), or when we explicitly detect
348 // blocks (for example while parsing lambdas).
350 // We exclude + and - as they can be ObjC visibility modifiers.
352 NextTok->isOneOf(tok::comma, tok::period, tok::colon,
353 tok::r_paren, tok::r_square, tok::l_brace,
354 tok::l_paren, tok::ellipsis) ||
355 (NextTok->is(tok::semi) &&
356 (!ExpectClassBody || LBraceStack.size() != 1)) ||
357 (NextTok->isBinaryOperator() && !NextIsObjCMethod);
359 if (ProbablyBracedList) {
360 Tok->BlockKind = BK_BracedInit;
361 LBraceStack.back()->BlockKind = BK_BracedInit;
363 Tok->BlockKind = BK_Block;
364 LBraceStack.back()->BlockKind = BK_Block;
367 LBraceStack.pop_back();
378 if (!LBraceStack.empty())
379 LBraceStack.back()->BlockKind = BK_Block;
385 } while (Tok->Tok.isNot(tok::eof) && !LBraceStack.empty());
386 // Assume other blocks for all unclosed opening braces.
387 for (unsigned i = 0, e = LBraceStack.size(); i != e; ++i) {
388 if (LBraceStack[i]->BlockKind == BK_Unknown)
389 LBraceStack[i]->BlockKind = BK_Block;
392 FormatTok = Tokens->setPosition(StoredPosition);
395 void UnwrappedLineParser::parseBlock(bool MustBeDeclaration, bool AddLevel,
397 assert(FormatTok->Tok.is(tok::l_brace) && "'{' expected");
398 unsigned InitialLevel = Line->Level;
403 ScopedDeclarationState DeclarationState(*Line, DeclarationScopeStack,
407 parseLevel(/*HasOpeningBrace=*/true);
409 if (!FormatTok->Tok.is(tok::r_brace)) {
410 Line->Level = InitialLevel;
414 nextToken(); // Munch the closing brace.
415 if (MunchSemi && FormatTok->Tok.is(tok::semi))
417 Line->Level = InitialLevel;
420 static bool isGoogScope(const UnwrappedLine &Line) {
421 // FIXME: Closure-library specific stuff should not be hard-coded but be
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 static bool ShouldBreakBeforeBrace(const FormatStyle &Style,
439 const FormatToken &InitialToken) {
440 switch (Style.BreakBeforeBraces) {
441 case FormatStyle::BS_Linux:
442 return InitialToken.isOneOf(tok::kw_namespace, tok::kw_class);
443 case FormatStyle::BS_Allman:
444 case FormatStyle::BS_GNU:
451 void UnwrappedLineParser::parseChildBlock() {
452 FormatTok->BlockKind = BK_Block;
456 Style.Language == FormatStyle::LK_JavaScript && isGoogScope(*Line);
457 ScopedLineState LineState(*this);
458 ScopedDeclarationState DeclarationState(*Line, DeclarationScopeStack,
459 /*MustBeDeclaration=*/false);
460 Line->Level += GoogScope ? 0 : 1;
461 parseLevel(/*HasOpeningBrace=*/true);
462 flushComments(isOnNewLine(*FormatTok));
463 Line->Level -= GoogScope ? 0 : 1;
468 void UnwrappedLineParser::parsePPDirective() {
469 assert(FormatTok->Tok.is(tok::hash) && "'#' expected");
470 ScopedMacroState MacroState(*Line, Tokens, FormatTok);
473 if (!FormatTok->Tok.getIdentifierInfo()) {
478 switch (FormatTok->Tok.getIdentifierInfo()->getPPKeywordID()) {
483 parsePPIf(/*IfDef=*/false);
487 parsePPIf(/*IfDef=*/true);
504 void UnwrappedLineParser::conditionalCompilationCondition(bool Unreachable) {
505 if (Unreachable || (!PPStack.empty() && PPStack.back() == PP_Unreachable))
506 PPStack.push_back(PP_Unreachable);
508 PPStack.push_back(PP_Conditional);
511 void UnwrappedLineParser::conditionalCompilationStart(bool Unreachable) {
513 assert(PPBranchLevel >= 0 && PPBranchLevel <= (int)PPLevelBranchIndex.size());
514 if (PPBranchLevel == (int)PPLevelBranchIndex.size()) {
515 PPLevelBranchIndex.push_back(0);
516 PPLevelBranchCount.push_back(0);
518 PPChainBranchIndex.push(0);
519 bool Skip = PPLevelBranchIndex[PPBranchLevel] > 0;
520 conditionalCompilationCondition(Unreachable || Skip);
523 void UnwrappedLineParser::conditionalCompilationAlternative() {
524 if (!PPStack.empty())
526 assert(PPBranchLevel < (int)PPLevelBranchIndex.size());
527 if (!PPChainBranchIndex.empty())
528 ++PPChainBranchIndex.top();
529 conditionalCompilationCondition(
530 PPBranchLevel >= 0 && !PPChainBranchIndex.empty() &&
531 PPLevelBranchIndex[PPBranchLevel] != PPChainBranchIndex.top());
534 void UnwrappedLineParser::conditionalCompilationEnd() {
535 assert(PPBranchLevel < (int)PPLevelBranchIndex.size());
536 if (PPBranchLevel >= 0 && !PPChainBranchIndex.empty()) {
537 if (PPChainBranchIndex.top() + 1 > PPLevelBranchCount[PPBranchLevel]) {
538 PPLevelBranchCount[PPBranchLevel] = PPChainBranchIndex.top() + 1;
541 // Guard against #endif's without #if.
542 if (PPBranchLevel > 0)
544 if (!PPChainBranchIndex.empty())
545 PPChainBranchIndex.pop();
546 if (!PPStack.empty())
550 void UnwrappedLineParser::parsePPIf(bool IfDef) {
552 bool IsLiteralFalse = (FormatTok->Tok.isLiteral() &&
553 FormatTok->Tok.getLiteralData() != nullptr &&
554 StringRef(FormatTok->Tok.getLiteralData(),
555 FormatTok->Tok.getLength()) == "0") ||
556 FormatTok->Tok.is(tok::kw_false);
557 conditionalCompilationStart(!IfDef && IsLiteralFalse);
561 void UnwrappedLineParser::parsePPElse() {
562 conditionalCompilationAlternative();
566 void UnwrappedLineParser::parsePPElIf() { parsePPElse(); }
568 void UnwrappedLineParser::parsePPEndIf() {
569 conditionalCompilationEnd();
573 void UnwrappedLineParser::parsePPDefine() {
576 if (FormatTok->Tok.getKind() != tok::identifier) {
581 if (FormatTok->Tok.getKind() == tok::l_paren &&
582 FormatTok->WhitespaceRange.getBegin() ==
583 FormatTok->WhitespaceRange.getEnd()) {
589 // Errors during a preprocessor directive can only affect the layout of the
590 // preprocessor directive, and thus we ignore them. An alternative approach
591 // would be to use the same approach we use on the file level (no
592 // re-indentation if there was a structural error) within the macro
597 void UnwrappedLineParser::parsePPUnknown() {
604 // Here we blacklist certain tokens that are not usually the first token in an
605 // unwrapped line. This is used in attempt to distinguish macro calls without
606 // trailing semicolons from other constructs split to several lines.
607 static bool tokenCanStartNewLine(const clang::Token &Tok) {
608 // Semicolon can be a null-statement, l_square can be a start of a macro or
609 // a C++11 attribute, but this doesn't seem to be common.
610 return Tok.isNot(tok::semi) && Tok.isNot(tok::l_brace) &&
611 Tok.isNot(tok::l_square) &&
612 // Tokens that can only be used as binary operators and a part of
613 // overloaded operator names.
614 Tok.isNot(tok::period) && Tok.isNot(tok::periodstar) &&
615 Tok.isNot(tok::arrow) && Tok.isNot(tok::arrowstar) &&
616 Tok.isNot(tok::less) && Tok.isNot(tok::greater) &&
617 Tok.isNot(tok::slash) && Tok.isNot(tok::percent) &&
618 Tok.isNot(tok::lessless) && Tok.isNot(tok::greatergreater) &&
619 Tok.isNot(tok::equal) && Tok.isNot(tok::plusequal) &&
620 Tok.isNot(tok::minusequal) && Tok.isNot(tok::starequal) &&
621 Tok.isNot(tok::slashequal) && Tok.isNot(tok::percentequal) &&
622 Tok.isNot(tok::ampequal) && Tok.isNot(tok::pipeequal) &&
623 Tok.isNot(tok::caretequal) && Tok.isNot(tok::greatergreaterequal) &&
624 Tok.isNot(tok::lesslessequal) &&
625 // Colon is used in labels, base class lists, initializer lists,
626 // range-based for loops, ternary operator, but should never be the
627 // first token in an unwrapped line.
628 Tok.isNot(tok::colon) &&
629 // 'noexcept' is a trailing annotation.
630 Tok.isNot(tok::kw_noexcept);
633 void UnwrappedLineParser::parseStructuralElement() {
634 assert(!FormatTok->Tok.is(tok::l_brace));
635 switch (FormatTok->Tok.getKind()) {
638 if (FormatTok->Tok.is(tok::l_brace)) {
642 switch (FormatTok->Tok.getObjCKeywordID()) {
643 case tok::objc_public:
644 case tok::objc_protected:
645 case tok::objc_package:
646 case tok::objc_private:
647 return parseAccessSpecifier();
648 case tok::objc_interface:
649 case tok::objc_implementation:
650 return parseObjCInterfaceOrImplementation();
651 case tok::objc_protocol:
652 return parseObjCProtocol();
654 return; // Handled by the caller.
655 case tok::objc_optional:
656 case tok::objc_required:
661 // This branch isn't strictly necessary (the kw_try case below would
662 // do this too after the tok::at is parsed above). But be explicit.
671 if (FormatTok->is(tok::l_brace)) {
672 FormatTok->Type = TT_InlineASMBrace;
674 while (FormatTok && FormatTok->isNot(tok::eof)) {
675 if (FormatTok->is(tok::r_brace)) {
676 FormatTok->Type = TT_InlineASMBrace;
681 FormatTok->Finalized = true;
686 case tok::kw_namespace:
691 if (FormatTok->Tok.is(tok::kw_namespace)) {
697 case tok::kw_protected:
698 case tok::kw_private:
699 if (Style.Language == FormatStyle::LK_Java ||
700 Style.Language == FormatStyle::LK_JavaScript)
703 parseAccessSpecifier();
710 parseForOrWhileLoop();
718 case tok::kw_default:
731 if (FormatTok->Tok.is(tok::string_literal)) {
733 if (FormatTok->Tok.is(tok::l_brace)) {
734 parseBlock(/*MustBeDeclaration=*/true, /*AddLevel=*/false);
741 if (Style.Language == FormatStyle::LK_JavaScript) {
742 parseJavaScriptEs6ImportExport();
746 case tok::identifier:
747 if (FormatTok->is(TT_ForEachMacro)) {
748 parseForOrWhileLoop();
751 if (Style.Language == FormatStyle::LK_JavaScript &&
752 FormatTok->is(Keywords.kw_import)) {
753 parseJavaScriptEs6ImportExport();
756 if (FormatTok->is(Keywords.kw_signals)) {
758 if (FormatTok->is(tok::colon)) {
764 // In all other cases, parse the declaration.
770 switch (FormatTok->Tok.getKind()) {
773 if (FormatTok->Tok.is(tok::l_brace))
779 case tok::kw_typedef:
781 if (FormatTok->isOneOf(Keywords.kw_NS_ENUM, Keywords.kw_NS_OPTIONS,
782 Keywords.kw_CF_ENUM, Keywords.kw_CF_OPTIONS))
789 // A record declaration or definition is always the start of a structural
794 // In Java, classes have an implicit static member "class".
795 if (Style.Language == FormatStyle::LK_Java && FormatTok &&
796 FormatTok->is(tok::kw_class))
811 if (FormatTok->Tok.isAnyIdentifier() ||
812 FormatTok->isSimpleTypeSpecifier())
814 if (FormatTok->is(tok::l_paren))
816 if (FormatTok->is(tok::l_brace))
820 if (!tryToParseBracedList()) {
821 // A block outside of parentheses must be the last part of a
822 // structural element.
823 // FIXME: Figure out cases where this is not true, and add projections
824 // for them (the one we know is missing are lambdas).
825 if (Style.BreakBeforeBraces != FormatStyle::BS_Attach)
827 FormatTok->Type = TT_FunctionLBrace;
828 parseBlock(/*MustBeDeclaration=*/false);
832 // Otherwise this was a braced init list, and the structural
833 // element continues.
836 // We arrive here when parsing function-try blocks.
839 case tok::identifier: {
840 // Parse function literal unless 'function' is the first token in a line
841 // in which case this should be treated as a free-standing function.
842 if (Style.Language == FormatStyle::LK_JavaScript &&
843 FormatTok->is(Keywords.kw_function) && Line->Tokens.size() > 0) {
844 tryToParseJSFunction();
847 if ((Style.Language == FormatStyle::LK_JavaScript ||
848 Style.Language == FormatStyle::LK_Java) &&
849 FormatTok->is(Keywords.kw_interface)) {
854 StringRef Text = FormatTok->TokenText;
856 if (Line->Tokens.size() == 1 &&
857 // JS doesn't have macros, and within classes colons indicate fields,
859 Style.Language != FormatStyle::LK_JavaScript) {
860 if (FormatTok->Tok.is(tok::colon) && !Line->MustBeDeclaration) {
864 // Recognize function-like macro usages without trailing semicolon as
865 // well as free-standing macros like Q_OBJECT.
866 bool FunctionLike = FormatTok->is(tok::l_paren);
870 bool FollowedByNewline =
871 CommentsBeforeNextToken.empty()
872 ? FormatTok->NewlinesBefore > 0
873 : CommentsBeforeNextToken.front()->NewlinesBefore > 0;
875 if (FollowedByNewline &&
876 (Text.size() >= 5 || FunctionLike) &&
877 tokenCanStartNewLine(FormatTok->Tok) && Text == Text.upper()) {
885 // Fat arrows (=>) have tok::TokenKind tok::equal but TokenType
886 // TT_JsFatArrow. The always start an expression or a child block if
887 // followed by a curly.
888 if (FormatTok->is(TT_JsFatArrow)) {
890 if (FormatTok->is(tok::l_brace)) {
897 if (FormatTok->Tok.is(tok::l_brace)) {
914 bool UnwrappedLineParser::tryToParseLambda() {
915 // FIXME: This is a dirty way to access the previous token. Find a better
917 if (!Line->Tokens.empty() &&
918 (Line->Tokens.back().Tok->isOneOf(tok::identifier, tok::kw_operator,
919 tok::kw_new, tok::kw_delete) ||
920 Line->Tokens.back().Tok->closesScope() ||
921 Line->Tokens.back().Tok->isSimpleTypeSpecifier())) {
925 assert(FormatTok->is(tok::l_square));
926 FormatToken &LSquare = *FormatTok;
927 if (!tryToParseLambdaIntroducer())
930 while (FormatTok->isNot(tok::l_brace)) {
931 if (FormatTok->isSimpleTypeSpecifier()) {
935 switch (FormatTok->Tok.getKind()) {
947 case tok::identifier:
948 case tok::coloncolon:
949 case tok::kw_mutable:
953 FormatTok->Type = TT_TrailingReturnArrow;
960 LSquare.Type = TT_LambdaLSquare;
965 bool UnwrappedLineParser::tryToParseLambdaIntroducer() {
967 if (FormatTok->is(tok::equal)) {
969 if (FormatTok->is(tok::r_square)) {
973 if (FormatTok->isNot(tok::comma))
976 } else if (FormatTok->is(tok::amp)) {
978 if (FormatTok->is(tok::r_square)) {
982 if (!FormatTok->isOneOf(tok::comma, tok::identifier)) {
985 if (FormatTok->is(tok::comma))
987 } else if (FormatTok->is(tok::r_square)) {
992 if (FormatTok->is(tok::amp))
994 if (!FormatTok->isOneOf(tok::identifier, tok::kw_this))
997 if (FormatTok->is(tok::ellipsis))
999 if (FormatTok->is(tok::comma)) {
1001 } else if (FormatTok->is(tok::r_square)) {
1011 void UnwrappedLineParser::tryToParseJSFunction() {
1014 // Consume function name.
1015 if (FormatTok->is(tok::identifier))
1018 if (FormatTok->isNot(tok::l_paren))
1021 // Parse formal parameter list.
1022 parseBalanced(tok::l_paren, tok::r_paren);
1024 if (FormatTok->is(tok::colon)) {
1025 // Parse a type definition.
1028 // Eat the type declaration. For braced inline object types, balance braces,
1029 // otherwise just parse until finding an l_brace for the function body.
1030 if (FormatTok->is(tok::l_brace)) {
1031 parseBalanced(tok::l_brace, tok::r_brace);
1033 while(FormatTok->isNot(tok::l_brace) && !eof()) {
1042 void UnwrappedLineParser::parseBalanced(tok::TokenKind OpenKind,
1043 tok::TokenKind CloseKind) {
1044 assert(FormatTok->is(OpenKind));
1047 while (Depth > 0 && !eof()) {
1048 // Parse the formal parameter list.
1049 if (FormatTok->is(OpenKind)) {
1051 } else if (FormatTok->is(CloseKind)) {
1058 bool UnwrappedLineParser::tryToParseBracedList() {
1059 if (FormatTok->BlockKind == BK_Unknown)
1060 calculateBraceTypes();
1061 assert(FormatTok->BlockKind != BK_Unknown);
1062 if (FormatTok->BlockKind == BK_Block)
1068 bool UnwrappedLineParser::parseBracedList(bool ContinueOnSemicolons) {
1069 bool HasError = false;
1072 // FIXME: Once we have an expression parser in the UnwrappedLineParser,
1073 // replace this by using parseAssigmentExpression() inside.
1075 if (Style.Language == FormatStyle::LK_JavaScript) {
1076 if (FormatTok->is(Keywords.kw_function)) {
1077 tryToParseJSFunction();
1079 } else if (FormatTok->is(TT_JsFatArrow)) {
1081 // Fat arrows can be followed by simple expressions or by child blocks
1083 if (FormatTok->is(tok::l_brace)){
1089 switch (FormatTok->Tok.getKind()) {
1092 if (FormatTok->is(tok::l_brace)) {
1100 // Assume there are no blocks inside a braced init list apart
1101 // from the ones we explicitly parse out (like lambdas).
1102 FormatTok->BlockKind = BK_BracedInit;
1106 // JavaScript can just have free standing methods and getters/setters in
1107 // object literals. Detect them by a "{" following ")".
1108 if (Style.Language == FormatStyle::LK_JavaScript) {
1110 if (FormatTok->is(tok::l_brace))
1121 if (!ContinueOnSemicolons)
1136 void UnwrappedLineParser::parseParens() {
1137 assert(FormatTok->Tok.is(tok::l_paren) && "'(' expected.");
1140 switch (FormatTok->Tok.getKind()) {
1143 if (Style.Language == FormatStyle::LK_Java && FormatTok->is(tok::l_brace))
1150 // A "}" inside parenthesis is an error if there wasn't a matching "{".
1156 if (!tryToParseBracedList())
1161 if (FormatTok->Tok.is(tok::l_brace))
1164 case tok::identifier:
1165 if (Style.Language == FormatStyle::LK_JavaScript &&
1166 FormatTok->is(Keywords.kw_function))
1167 tryToParseJSFunction();
1178 void UnwrappedLineParser::parseSquare() {
1179 assert(FormatTok->Tok.is(tok::l_square) && "'[' expected.");
1180 if (tryToParseLambda())
1183 switch (FormatTok->Tok.getKind()) {
1191 // A "}" inside parenthesis is an error if there wasn't a matching "{".
1196 case tok::l_brace: {
1197 if (!tryToParseBracedList())
1203 if (FormatTok->Tok.is(tok::l_brace))
1213 void UnwrappedLineParser::parseIfThenElse() {
1214 assert(FormatTok->Tok.is(tok::kw_if) && "'if' expected");
1216 if (FormatTok->Tok.is(tok::l_paren))
1218 bool NeedsUnwrappedLine = false;
1219 if (FormatTok->Tok.is(tok::l_brace)) {
1220 CompoundStatementIndenter Indenter(this, Style, Line->Level);
1221 parseBlock(/*MustBeDeclaration=*/false);
1222 if (Style.BreakBeforeBraces == FormatStyle::BS_Allman ||
1223 Style.BreakBeforeBraces == FormatStyle::BS_GNU) {
1226 NeedsUnwrappedLine = true;
1231 parseStructuralElement();
1234 if (FormatTok->Tok.is(tok::kw_else)) {
1235 if (Style.BreakBeforeBraces == FormatStyle::BS_Stroustrup)
1238 if (FormatTok->Tok.is(tok::l_brace)) {
1239 CompoundStatementIndenter Indenter(this, Style, Line->Level);
1240 parseBlock(/*MustBeDeclaration=*/false);
1242 } else if (FormatTok->Tok.is(tok::kw_if)) {
1247 parseStructuralElement();
1250 } else if (NeedsUnwrappedLine) {
1255 void UnwrappedLineParser::parseTryCatch() {
1256 assert(FormatTok->isOneOf(tok::kw_try, tok::kw___try) && "'try' expected");
1258 bool NeedsUnwrappedLine = false;
1259 if (FormatTok->is(tok::colon)) {
1260 // We are in a function try block, what comes is an initializer list.
1262 while (FormatTok->is(tok::identifier)) {
1264 if (FormatTok->is(tok::l_paren))
1266 if (FormatTok->is(tok::comma))
1270 // Parse try with resource.
1271 if (Style.Language == FormatStyle::LK_Java && FormatTok->is(tok::l_paren)) {
1274 if (FormatTok->is(tok::l_brace)) {
1275 CompoundStatementIndenter Indenter(this, Style, Line->Level);
1276 parseBlock(/*MustBeDeclaration=*/false);
1277 if (Style.BreakBeforeBraces == FormatStyle::BS_Allman ||
1278 Style.BreakBeforeBraces == FormatStyle::BS_GNU ||
1279 Style.BreakBeforeBraces == FormatStyle::BS_Stroustrup) {
1282 NeedsUnwrappedLine = true;
1284 } else if (!FormatTok->is(tok::kw_catch)) {
1285 // The C++ standard requires a compound-statement after a try.
1286 // If there's none, we try to assume there's a structuralElement
1287 // and try to continue.
1290 parseStructuralElement();
1294 if (FormatTok->is(tok::at))
1296 if (!(FormatTok->isOneOf(tok::kw_catch, Keywords.kw___except,
1297 tok::kw___finally) ||
1298 ((Style.Language == FormatStyle::LK_Java ||
1299 Style.Language == FormatStyle::LK_JavaScript) &&
1300 FormatTok->is(Keywords.kw_finally)) ||
1301 (FormatTok->Tok.isObjCAtKeyword(tok::objc_catch) ||
1302 FormatTok->Tok.isObjCAtKeyword(tok::objc_finally))))
1305 while (FormatTok->isNot(tok::l_brace)) {
1306 if (FormatTok->is(tok::l_paren)) {
1310 if (FormatTok->isOneOf(tok::semi, tok::r_brace, tok::eof))
1314 NeedsUnwrappedLine = false;
1315 CompoundStatementIndenter Indenter(this, Style, Line->Level);
1316 parseBlock(/*MustBeDeclaration=*/false);
1317 if (Style.BreakBeforeBraces == FormatStyle::BS_Allman ||
1318 Style.BreakBeforeBraces == FormatStyle::BS_GNU ||
1319 Style.BreakBeforeBraces == FormatStyle::BS_Stroustrup) {
1322 NeedsUnwrappedLine = true;
1325 if (NeedsUnwrappedLine) {
1330 void UnwrappedLineParser::parseNamespace() {
1331 assert(FormatTok->Tok.is(tok::kw_namespace) && "'namespace' expected");
1333 const FormatToken &InitialToken = *FormatTok;
1335 if (FormatTok->Tok.is(tok::identifier))
1337 if (FormatTok->Tok.is(tok::l_brace)) {
1338 if (ShouldBreakBeforeBrace(Style, InitialToken))
1341 bool AddLevel = Style.NamespaceIndentation == FormatStyle::NI_All ||
1342 (Style.NamespaceIndentation == FormatStyle::NI_Inner &&
1343 DeclarationScopeStack.size() > 1);
1344 parseBlock(/*MustBeDeclaration=*/true, AddLevel);
1345 // Munch the semicolon after a namespace. This is more common than one would
1346 // think. Puttin the semicolon into its own line is very ugly.
1347 if (FormatTok->Tok.is(tok::semi))
1351 // FIXME: Add error handling.
1354 void UnwrappedLineParser::parseNew() {
1355 assert(FormatTok->is(tok::kw_new) && "'new' expected");
1357 if (Style.Language != FormatStyle::LK_Java)
1360 // In Java, we can parse everything up to the parens, which aren't optional.
1362 // There should not be a ;, { or } before the new's open paren.
1363 if (FormatTok->isOneOf(tok::semi, tok::l_brace, tok::r_brace))
1366 // Consume the parens.
1367 if (FormatTok->is(tok::l_paren)) {
1370 // If there is a class body of an anonymous class, consume that as child.
1371 if (FormatTok->is(tok::l_brace))
1379 void UnwrappedLineParser::parseForOrWhileLoop() {
1380 assert(FormatTok->isOneOf(tok::kw_for, tok::kw_while, TT_ForEachMacro) &&
1381 "'for', 'while' or foreach macro expected");
1383 if (FormatTok->Tok.is(tok::l_paren))
1385 if (FormatTok->Tok.is(tok::l_brace)) {
1386 CompoundStatementIndenter Indenter(this, Style, Line->Level);
1387 parseBlock(/*MustBeDeclaration=*/false);
1392 parseStructuralElement();
1397 void UnwrappedLineParser::parseDoWhile() {
1398 assert(FormatTok->Tok.is(tok::kw_do) && "'do' expected");
1400 if (FormatTok->Tok.is(tok::l_brace)) {
1401 CompoundStatementIndenter Indenter(this, Style, Line->Level);
1402 parseBlock(/*MustBeDeclaration=*/false);
1403 if (Style.BreakBeforeBraces == FormatStyle::BS_GNU)
1408 parseStructuralElement();
1412 // FIXME: Add error handling.
1413 if (!FormatTok->Tok.is(tok::kw_while)) {
1419 parseStructuralElement();
1422 void UnwrappedLineParser::parseLabel() {
1424 unsigned OldLineLevel = Line->Level;
1425 if (Line->Level > 1 || (!Line->InPPDirective && Line->Level > 0))
1427 if (CommentsBeforeNextToken.empty() && FormatTok->Tok.is(tok::l_brace)) {
1428 CompoundStatementIndenter Indenter(this, Style, Line->Level);
1429 parseBlock(/*MustBeDeclaration=*/false);
1430 if (FormatTok->Tok.is(tok::kw_break)) {
1431 // "break;" after "}" on its own line only for BS_Allman and BS_GNU
1432 if (Style.BreakBeforeBraces == FormatStyle::BS_Allman ||
1433 Style.BreakBeforeBraces == FormatStyle::BS_GNU) {
1436 parseStructuralElement();
1440 if (FormatTok->is(tok::semi))
1444 Line->Level = OldLineLevel;
1447 void UnwrappedLineParser::parseCaseLabel() {
1448 assert(FormatTok->Tok.is(tok::kw_case) && "'case' expected");
1449 // FIXME: fix handling of complex expressions here.
1452 } while (!eof() && !FormatTok->Tok.is(tok::colon));
1456 void UnwrappedLineParser::parseSwitch() {
1457 assert(FormatTok->Tok.is(tok::kw_switch) && "'switch' expected");
1459 if (FormatTok->Tok.is(tok::l_paren))
1461 if (FormatTok->Tok.is(tok::l_brace)) {
1462 CompoundStatementIndenter Indenter(this, Style, Line->Level);
1463 parseBlock(/*MustBeDeclaration=*/false);
1468 parseStructuralElement();
1473 void UnwrappedLineParser::parseAccessSpecifier() {
1475 // Understand Qt's slots.
1476 if (FormatTok->isOneOf(Keywords.kw_slots, Keywords.kw_qslots))
1478 // Otherwise, we don't know what it is, and we'd better keep the next token.
1479 if (FormatTok->Tok.is(tok::colon))
1484 void UnwrappedLineParser::parseEnum() {
1485 // Won't be 'enum' for NS_ENUMs.
1486 if (FormatTok->Tok.is(tok::kw_enum))
1489 // Eat up enum class ...
1490 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))
1503 // Just a declaration or something is wrong.
1504 if (FormatTok->isNot(tok::l_brace))
1506 FormatTok->BlockKind = BK_Block;
1508 if (Style.Language == FormatStyle::LK_Java) {
1509 // Java enums are different.
1510 parseJavaEnumBody();
1515 bool HasError = !parseBracedList(/*ContinueOnSemicolons=*/true);
1517 if (FormatTok->is(tok::semi))
1522 // We fall through to parsing a structural element afterwards, so that in
1524 // "} n, m;" will end up in one unwrapped line.
1527 void UnwrappedLineParser::parseJavaEnumBody() {
1528 // Determine whether the enum is simple, i.e. does not have a semicolon or
1529 // constants with class bodies. Simple enums can be formatted like braced
1530 // lists, contracted to a single line, etc.
1531 unsigned StoredPosition = Tokens->getPosition();
1532 bool IsSimple = true;
1533 FormatToken *Tok = Tokens->getNextToken();
1535 if (Tok->is(tok::r_brace))
1537 if (Tok->isOneOf(tok::l_brace, tok::semi)) {
1541 // FIXME: This will also mark enums with braces in the arguments to enum
1542 // constants as "not simple". This is probably fine in practice, though.
1543 Tok = Tokens->getNextToken();
1545 FormatTok = Tokens->setPosition(StoredPosition);
1553 // Parse the body of a more complex enum.
1554 // First add a line for everything up to the "{".
1559 // Parse the enum constants.
1561 if (FormatTok->is(tok::l_brace)) {
1562 // Parse the constant's class body.
1563 parseBlock(/*MustBeDeclaration=*/true, /*AddLevel=*/true,
1564 /*MunchSemi=*/false);
1565 } else if (FormatTok->is(tok::l_paren)) {
1567 } else if (FormatTok->is(tok::comma)) {
1570 } else if (FormatTok->is(tok::semi)) {
1574 } else if (FormatTok->is(tok::r_brace)) {
1582 // Parse the class body after the enum's ";" if any.
1583 parseLevel(/*HasOpeningBrace=*/true);
1589 void UnwrappedLineParser::parseRecord() {
1590 const FormatToken &InitialToken = *FormatTok;
1594 // The actual identifier can be a nested name specifier, and in macros
1595 // it is often token-pasted.
1596 while (FormatTok->isOneOf(tok::identifier, tok::coloncolon, tok::hashhash,
1597 tok::kw___attribute, tok::kw___declspec,
1599 ((Style.Language == FormatStyle::LK_Java ||
1600 Style.Language == FormatStyle::LK_JavaScript) &&
1601 FormatTok->isOneOf(tok::period, tok::comma))) {
1602 bool IsNonMacroIdentifier =
1603 FormatTok->is(tok::identifier) &&
1604 FormatTok->TokenText != FormatTok->TokenText.upper();
1606 // We can have macros or attributes in between 'class' and the class name.
1607 if (!IsNonMacroIdentifier && FormatTok->Tok.is(tok::l_paren))
1611 // Note that parsing away template declarations here leads to incorrectly
1612 // accepting function declarations as record declarations.
1613 // In general, we cannot solve this problem. Consider:
1614 // class A<int> B() {}
1615 // which can be a function definition or a class definition when B() is a
1616 // macro. If we find enough real-world cases where this is a problem, we
1617 // can parse for the 'template' keyword in the beginning of the statement,
1618 // and thus rule out the record production in case there is no template
1619 // (this would still leave us with an ambiguity between template function
1620 // and class declarations).
1621 if (FormatTok->isOneOf(tok::colon, tok::less)) {
1623 if (FormatTok->is(tok::l_brace)) {
1624 calculateBraceTypes(/*ExpectClassBody=*/true);
1625 if (!tryToParseBracedList())
1628 if (FormatTok->Tok.is(tok::semi))
1633 if (FormatTok->Tok.is(tok::l_brace)) {
1634 if (ShouldBreakBeforeBrace(Style, InitialToken))
1637 parseBlock(/*MustBeDeclaration=*/true, /*AddLevel=*/true,
1638 /*MunchSemi=*/false);
1640 // We fall through to parsing a structural element afterwards, so
1642 // will end up in one unwrapped line.
1643 // This does not apply for Java and JavaScript.
1644 if (Style.Language == FormatStyle::LK_Java ||
1645 Style.Language == FormatStyle::LK_JavaScript)
1649 void UnwrappedLineParser::parseObjCProtocolList() {
1650 assert(FormatTok->Tok.is(tok::less) && "'<' expected.");
1653 while (!eof() && FormatTok->Tok.isNot(tok::greater));
1654 nextToken(); // Skip '>'.
1657 void UnwrappedLineParser::parseObjCUntilAtEnd() {
1659 if (FormatTok->Tok.isObjCAtKeyword(tok::objc_end)) {
1664 if (FormatTok->is(tok::l_brace)) {
1665 parseBlock(/*MustBeDeclaration=*/false);
1666 // In ObjC interfaces, nothing should be following the "}".
1668 } else if (FormatTok->is(tok::r_brace)) {
1669 // Ignore stray "}". parseStructuralElement doesn't consume them.
1673 parseStructuralElement();
1678 void UnwrappedLineParser::parseObjCInterfaceOrImplementation() {
1680 nextToken(); // interface name
1682 // @interface can be followed by either a base class, or a category.
1683 if (FormatTok->Tok.is(tok::colon)) {
1685 nextToken(); // base class name
1686 } else if (FormatTok->Tok.is(tok::l_paren))
1687 // Skip category, if present.
1690 if (FormatTok->Tok.is(tok::less))
1691 parseObjCProtocolList();
1693 if (FormatTok->Tok.is(tok::l_brace)) {
1694 if (Style.BreakBeforeBraces == FormatStyle::BS_Allman ||
1695 Style.BreakBeforeBraces == FormatStyle::BS_GNU)
1697 parseBlock(/*MustBeDeclaration=*/true);
1700 // With instance variables, this puts '}' on its own line. Without instance
1701 // variables, this ends the @interface line.
1704 parseObjCUntilAtEnd();
1707 void UnwrappedLineParser::parseObjCProtocol() {
1709 nextToken(); // protocol name
1711 if (FormatTok->Tok.is(tok::less))
1712 parseObjCProtocolList();
1714 // Check for protocol declaration.
1715 if (FormatTok->Tok.is(tok::semi)) {
1717 return addUnwrappedLine();
1721 parseObjCUntilAtEnd();
1724 void UnwrappedLineParser::parseJavaScriptEs6ImportExport() {
1725 assert(FormatTok->isOneOf(Keywords.kw_import, tok::kw_export));
1728 // Consume the "default" in "export default class/function".
1729 if (FormatTok->is(tok::kw_default))
1732 // Consume "function" and "default function", so that these get parsed as
1733 // free-standing JS functions, i.e. do not require a trailing semicolon.
1734 if (FormatTok->is(Keywords.kw_function)) {
1739 if (FormatTok->isOneOf(tok::kw_const, tok::kw_class, Keywords.kw_var))
1740 return; // Fall through to parsing the corresponding structure.
1742 if (FormatTok->is(tok::l_brace)) {
1743 FormatTok->BlockKind = BK_Block;
1747 while (!eof() && FormatTok->isNot(tok::semi) &&
1748 FormatTok->isNot(tok::l_brace)) {
1753 LLVM_ATTRIBUTE_UNUSED static void printDebugInfo(const UnwrappedLine &Line,
1754 StringRef Prefix = "") {
1755 llvm::dbgs() << Prefix << "Line(" << Line.Level << ")"
1756 << (Line.InPPDirective ? " MACRO" : "") << ": ";
1757 for (std::list<UnwrappedLineNode>::const_iterator I = Line.Tokens.begin(),
1758 E = Line.Tokens.end();
1760 llvm::dbgs() << I->Tok->Tok.getName() << "[" << I->Tok->Type << "] ";
1762 for (std::list<UnwrappedLineNode>::const_iterator I = Line.Tokens.begin(),
1763 E = Line.Tokens.end();
1765 const UnwrappedLineNode &Node = *I;
1766 for (SmallVectorImpl<UnwrappedLine>::const_iterator
1767 I = Node.Children.begin(),
1768 E = Node.Children.end();
1770 printDebugInfo(*I, "\nChild: ");
1773 llvm::dbgs() << "\n";
1776 void UnwrappedLineParser::addUnwrappedLine() {
1777 if (Line->Tokens.empty())
1780 if (CurrentLines == &Lines)
1781 printDebugInfo(*Line);
1783 CurrentLines->push_back(*Line);
1784 Line->Tokens.clear();
1785 if (CurrentLines == &Lines && !PreprocessorDirectives.empty()) {
1786 for (SmallVectorImpl<UnwrappedLine>::iterator
1787 I = PreprocessorDirectives.begin(),
1788 E = PreprocessorDirectives.end();
1790 CurrentLines->push_back(*I);
1792 PreprocessorDirectives.clear();
1796 bool UnwrappedLineParser::eof() const { return FormatTok->Tok.is(tok::eof); }
1798 bool UnwrappedLineParser::isOnNewLine(const FormatToken &FormatTok) {
1799 return (Line->InPPDirective || FormatTok.HasUnescapedNewline) &&
1800 FormatTok.NewlinesBefore > 0;
1803 void UnwrappedLineParser::flushComments(bool NewlineBeforeNext) {
1804 bool JustComments = Line->Tokens.empty();
1805 for (SmallVectorImpl<FormatToken *>::const_iterator
1806 I = CommentsBeforeNextToken.begin(),
1807 E = CommentsBeforeNextToken.end();
1809 if (isOnNewLine(**I) && JustComments)
1813 if (NewlineBeforeNext && JustComments)
1815 CommentsBeforeNextToken.clear();
1818 void UnwrappedLineParser::nextToken() {
1821 flushComments(isOnNewLine(*FormatTok));
1822 pushToken(FormatTok);
1826 void UnwrappedLineParser::readToken() {
1827 bool CommentsInCurrentLine = true;
1829 FormatTok = Tokens->getNextToken();
1831 while (!Line->InPPDirective && FormatTok->Tok.is(tok::hash) &&
1832 (FormatTok->HasUnescapedNewline || FormatTok->IsFirst)) {
1833 // If there is an unfinished unwrapped line, we flush the preprocessor
1834 // directives only after that unwrapped line was finished later.
1835 bool SwitchToPreprocessorLines = !Line->Tokens.empty();
1836 ScopedLineState BlockState(*this, SwitchToPreprocessorLines);
1837 // Comments stored before the preprocessor directive need to be output
1838 // before the preprocessor directive, at the same level as the
1839 // preprocessor directive, as we consider them to apply to the directive.
1840 flushComments(isOnNewLine(*FormatTok));
1843 while (FormatTok->Type == TT_ConflictStart ||
1844 FormatTok->Type == TT_ConflictEnd ||
1845 FormatTok->Type == TT_ConflictAlternative) {
1846 if (FormatTok->Type == TT_ConflictStart) {
1847 conditionalCompilationStart(/*Unreachable=*/false);
1848 } else if (FormatTok->Type == TT_ConflictAlternative) {
1849 conditionalCompilationAlternative();
1850 } else if (FormatTok->Type == TT_ConflictEnd) {
1851 conditionalCompilationEnd();
1853 FormatTok = Tokens->getNextToken();
1854 FormatTok->MustBreakBefore = true;
1857 if (!PPStack.empty() && (PPStack.back() == PP_Unreachable) &&
1858 !Line->InPPDirective) {
1862 if (!FormatTok->Tok.is(tok::comment))
1864 if (isOnNewLine(*FormatTok) || FormatTok->IsFirst) {
1865 CommentsInCurrentLine = false;
1867 if (CommentsInCurrentLine) {
1868 pushToken(FormatTok);
1870 CommentsBeforeNextToken.push_back(FormatTok);
1875 void UnwrappedLineParser::pushToken(FormatToken *Tok) {
1876 Line->Tokens.push_back(UnwrappedLineNode(Tok));
1877 if (MustBreakBeforeNextToken) {
1878 Line->Tokens.back().Tok->MustBreakBefore = true;
1879 MustBreakBeforeNextToken = false;
1883 } // end namespace format
1884 } // end namespace clang