diff --git a/clang/lib/Format/AffectedRangeManager.cpp b/clang/lib/Format/AffectedRangeManager.cpp --- a/clang/lib/Format/AffectedRangeManager.cpp +++ b/clang/lib/Format/AffectedRangeManager.cpp @@ -60,10 +60,12 @@ bool AffectedRangeManager::affectsCharSourceRange( const CharSourceRange &Range) { - for (const CharSourceRange &R : Ranges) + for (const CharSourceRange &R : Ranges) { if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(), R.getBegin()) && - !SourceMgr.isBeforeInTranslationUnit(R.getEnd(), Range.getBegin())) + !SourceMgr.isBeforeInTranslationUnit(R.getEnd(), Range.getBegin())) { return true; + } + } return false; } diff --git a/clang/lib/Format/BreakableToken.cpp b/clang/lib/Format/BreakableToken.cpp --- a/clang/lib/Format/BreakableToken.cpp +++ b/clang/lib/Format/BreakableToken.cpp @@ -95,8 +95,9 @@ StringRef::size_type SpaceOffset = Text.find_first_of(Blanks, MaxSplitBytes); if (SpaceOffset != StringRef::npos && SpaceOffset + 1 < Text.size() && - Text[SpaceOffset + 1] == '{') + Text[SpaceOffset + 1] == '{') { MaxSplitBytes = SpaceOffset + 1; + } } StringRef::size_type SpaceOffset = Text.find_last_of(Blanks, MaxSplitBytes); @@ -141,9 +142,10 @@ // Make sure that we don't break at leading whitespace that // reaches past MaxSplit. StringRef::size_type FirstNonWhitespace = Text.find_first_not_of(Blanks); - if (FirstNonWhitespace == StringRef::npos) + if (FirstNonWhitespace == StringRef::npos) { // If the comment is only whitespace, we cannot split. return BreakableToken::Split(StringRef::npos, 0); + } SpaceOffset = Text.find_first_of( Blanks, std::max(MaxSplitBytes, FirstNonWhitespace)); } @@ -396,8 +398,9 @@ // ** blah blah blah // */ if (Lines.size() >= 2 && Content[1].startswith("**") && - static_cast(ContentColumn[1]) == StartColumn) + static_cast(ContentColumn[1]) == StartColumn) { DecorationColumn = StartColumn; + } Decoration = "* "; if (Lines.size() == 1 && !FirstInLine) { @@ -451,9 +454,10 @@ if (DecorationSize) ContentColumn[i] = DecorationColumn + DecorationSize; Content[i] = Content[i].substr(DecorationSize); - if (!Decoration.startswith(Content[i])) + if (!Decoration.startswith(Content[i])) { IndentAtLineBreak = std::min(IndentAtLineBreak, std::max(0, ContentColumn[i])); + } } IndentAtLineBreak = std::max(IndentAtLineBreak, Decoration.size()); @@ -478,10 +482,11 @@ LLVM_DEBUG({ llvm::dbgs() << "IndentAtLineBreak " << IndentAtLineBreak << "\n"; llvm::dbgs() << "DelimitersOnNewline " << DelimitersOnNewline << "\n"; - for (size_t i = 0; i < Lines.size(); ++i) + for (size_t i = 0; i < Lines.size(); ++i) { llvm::dbgs() << i << " |" << Content[i] << "| " << "CC=" << ContentColumn[i] << "| " << "IN=" << (Content[i].data() - Lines[i].data()) << "\n"; + } }); } @@ -586,8 +591,9 @@ StringRef FirstWord = ContentWithNoDecoration.substr( 0, ContentWithNoDecoration.find_first_of(Blanks)); if (ContentIndentingJavadocAnnotations.find(FirstWord) != - ContentIndentingJavadocAnnotations.end()) + ContentIndentingJavadocAnnotations.end()) { return Style.ContinuationIndentWidth; + } return 0; } @@ -633,8 +639,9 @@ if (LineIndex) { unsigned PreviousContentIndent = getContentIndent(LineIndex - 1); if (PreviousContentIndent && Trimmed != StringRef::npos && - Trimmed != PreviousContentIndent) + Trimmed != PreviousContentIndent) { return Split(StringRef::npos, 0); + } } return Split(0, Trimmed != StringRef::npos ? Trimmed : 0); @@ -676,9 +683,10 @@ // Note: this works because getCommentSplit is careful never to split at // the beginning of a line. size_t BreakLength = Lines[0].substr(1).find_first_not_of(Blanks); - if (BreakLength != StringRef::npos) + if (BreakLength != StringRef::npos) { insertBreak(LineIndex, 0, Split(1, BreakLength), /*ContentIndent=*/0, Whitespaces); + } } return; } @@ -783,8 +791,9 @@ encoding::getCodePointNumBytes(FirstCommentChar, Encoding); if (encoding::columnWidth( Lines[i].substr(IndentPrefix.size(), FirstCharByteSize), - Encoding) != 1) + Encoding) != 1) { return false; + } // In C-like comments, add a space before #. For example this is useful // to preserve the relative indentation when commenting out code with // #includes. diff --git a/clang/lib/Format/ContinuationIndenter.cpp b/clang/lib/Format/ContinuationIndenter.cpp --- a/clang/lib/Format/ContinuationIndenter.cpp +++ b/clang/lib/Format/ContinuationIndenter.cpp @@ -123,8 +123,9 @@ const FormatStyle &Style) { const FormatToken &Previous = *Current.Previous; if (Current.is(TT_CtorInitializerComma) && - Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma) + Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma) { return true; + } if (Style.Language == FormatStyle::LK_Proto && Current.is(TT_SelectorName)) return true; return Previous.is(tok::comma) && !Current.isTrailingComment() && @@ -150,8 +151,9 @@ // For example, the delimiter of R"deli(cont)deli" is deli. static llvm::Optional getRawStringDelimiter(StringRef TokenText) { if (TokenText.size() < 5 // The smallest raw string possible is 'R"()"'. - || !TokenText.startswith("R\"") || !TokenText.endswith("\"")) + || !TokenText.startswith("R\"") || !TokenText.endswith("\"")) { return None; + } // A raw string starts with 'R"(' and delimiter is ascii and has // size at most 16 by the standard, so the first '(' must be among the first @@ -246,8 +248,9 @@ // preprocessor indent. if (Style.IndentPPDirectives == FormatStyle::PPDIS_AfterHash && (Line->Type == LT_PreprocessorDirective || - Line->Type == LT_ImportStatement)) + Line->Type == LT_ImportStatement)) { State.Column = 0; + } State.Line = Line; State.NextToken = Line->First; State.Stack.push_back(ParenState(/*Tok=*/nullptr, FirstIndent, FirstIndent, @@ -279,15 +282,17 @@ const auto &CurrentState = State.Stack.back(); assert(&Previous == Current.Previous); if (!Current.CanBreakBefore && !(CurrentState.BreakBeforeClosingBrace && - Current.closesBlockOrBlockTypeList(Style))) + Current.closesBlockOrBlockTypeList(Style))) { return false; + } // The opening "{" of a braced list has to be on the same line as the first // element if it is nested in another braced init list or function call. if (!Current.MustBreakBefore && Previous.is(tok::l_brace) && Previous.isNot(TT_DictLiteral) && Previous.is(BK_BracedInit) && Previous.Previous && - Previous.Previous->isOneOf(tok::l_brace, tok::l_paren, tok::comma)) + Previous.Previous->isOneOf(tok::l_brace, tok::l_paren, tok::comma)) { return false; + } // This prevents breaks like: // ... // SomeParameter, OtherParameter).DoSomething( @@ -295,8 +300,9 @@ // As they hide "DoSomething" and are generally bad for readability. if (Previous.opensScope() && Previous.isNot(tok::l_brace) && State.LowestLevelOnLine < State.StartOfLineLevel && - State.LowestLevelOnLine < Current.NestingLevel) + State.LowestLevelOnLine < Current.NestingLevel) { return false; + } if (Current.isMemberAccess() && CurrentState.ContainsUnwrappedBuilder) return false; @@ -304,8 +310,9 @@ // statement. if (Previous.is(tok::l_brace) && State.Stack.size() > 1 && State.Stack[State.Stack.size() - 2].NestedBlockInlined && - State.Stack[State.Stack.size() - 2].HasMultipleNestedBlocks) + State.Stack[State.Stack.size() - 2].HasMultipleNestedBlocks) { return false; + } // Don't break after very short return types (e.g. "void") as that is often // unexpected. @@ -317,8 +324,9 @@ // If binary operators are moved to the next line (including commas for some // styles of constructor initializers), that's always ok. if (!Current.isOneOf(TT_BinaryOperator, tok::comma) && - CurrentState.NoLineBreakInOperand) + CurrentState.NoLineBreakInOperand) { return false; + } if (Previous.is(tok::l_square) && Previous.is(TT_ObjCMethodExpr)) return false; @@ -338,20 +346,23 @@ if (Current.MustBreakBefore || Current.is(TT_InlineASMColon)) return true; if (CurrentState.BreakBeforeClosingBrace && - Current.closesBlockOrBlockTypeList(Style)) + Current.closesBlockOrBlockTypeList(Style)) { return true; + } if (CurrentState.BreakBeforeClosingParen && Current.is(tok::r_paren)) return true; if (Style.Language == FormatStyle::LK_ObjC && Style.ObjCBreakBeforeNestedBlockParam && Current.ObjCSelectorNameParts > 1 && - Current.startsSequence(TT_SelectorName, tok::colon, tok::caret)) + Current.startsSequence(TT_SelectorName, tok::colon, tok::caret)) { return true; + } // Avoid producing inconsistent states by requiring breaks where they are not // permitted for C# generic type constraints. if (CurrentState.IsCSharpGenericTypeConstraint && - Previous.isNot(TT_CSharpGenericTypeConstraintComma)) + Previous.isNot(TT_CSharpGenericTypeConstraintComma)) { return false; + } if ((startsNextParameter(Current, Style) || Previous.is(tok::semi) || (Previous.is(TT_TemplateCloser) && Current.is(TT_StartOfName) && Style.isCpp() && @@ -365,22 +376,25 @@ (!Style.BreakBeforeTernaryOperators && Previous.is(TT_ConditionalExpr))) && CurrentState.BreakBeforeParameter && !Current.isTrailingComment() && - !Current.isOneOf(tok::r_paren, tok::r_brace)) + !Current.isOneOf(tok::r_paren, tok::r_brace)) { return true; + } if (CurrentState.IsChainedConditional && ((Style.BreakBeforeTernaryOperators && Current.is(TT_ConditionalExpr) && Current.is(tok::colon)) || (!Style.BreakBeforeTernaryOperators && Previous.is(TT_ConditionalExpr) && - Previous.is(tok::colon)))) + Previous.is(tok::colon)))) { return true; + } if (((Previous.is(TT_DictLiteral) && Previous.is(tok::l_brace)) || (Previous.is(TT_ArrayInitializerLSquare) && Previous.ParameterCount > 1) || opensProtoMessageField(Previous, Style)) && Style.ColumnLimit > 0 && getLengthToMatchingParen(Previous, State.Stack) + State.Column - 1 > - getColumnLimit(State)) + getColumnLimit(State)) { return true; + } const FormatToken &BreakConstructorInitializersToken = Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon @@ -392,24 +406,28 @@ CurrentState.BreakBeforeParameter) && (Style.AllowShortFunctionsOnASingleLine != FormatStyle::SFS_All || Style.BreakConstructorInitializers != FormatStyle::BCIS_BeforeColon || - Style.ColumnLimit != 0)) + Style.ColumnLimit != 0)) { return true; + } if (Current.is(TT_ObjCMethodExpr) && !Previous.is(TT_SelectorName) && - State.Line->startsWith(TT_ObjCMethodSpecifier)) + State.Line->startsWith(TT_ObjCMethodSpecifier)) { return true; + } if (Current.is(TT_SelectorName) && !Previous.is(tok::at) && CurrentState.ObjCSelectorNameFound && CurrentState.BreakBeforeParameter && (Style.ObjCBreakBeforeNestedBlockParam || - !Current.startsSequence(TT_SelectorName, tok::colon, tok::caret))) + !Current.startsSequence(TT_SelectorName, tok::colon, tok::caret))) { return true; + } unsigned NewLineColumn = getNewLineColumn(State); if (Current.isMemberAccess() && Style.ColumnLimit != 0 && State.Column + getLengthToNextOperator(Current) > Style.ColumnLimit && (State.Column > NewLineColumn || - Current.NestingLevel < State.StartOfLineLevel)) + Current.NestingLevel < State.StartOfLineLevel)) { return true; + } if (startsSegmentOfBuilderTypeCall(Current) && (CurrentState.CallContinuation != 0 || @@ -420,14 +438,16 @@ // }.bind(...)); // FIXME: We should find a more generic solution to this problem. !(State.Column <= NewLineColumn && Style.isJavaScript()) && - !(Previous.closesScopeAfterBlock() && State.Column <= NewLineColumn)) + !(Previous.closesScopeAfterBlock() && State.Column <= NewLineColumn)) { return true; + } // If the template declaration spans multiple lines, force wrap before the // function/class declaration if (Previous.ClosesTemplateDeclaration && CurrentState.BreakBeforeParameter && - Current.CanBreakBefore) + Current.CanBreakBefore) { return true; + } if (!State.Line->First->is(tok::kw_enum) && State.Column <= NewLineColumn) return false; @@ -438,8 +458,9 @@ !Previous.isOneOf(tok::kw_return, tok::lessless, tok::at, Keywords.kw_dollar) && !Previous.isOneOf(TT_InlineASMColon, TT_ConditionalExpr) && - nextIsMultilineString(State)) + nextIsMultilineString(State)) { return true; + } // Using CanBreakBefore here and below takes care of the decision whether the // current style uses wrapping before or after operators for the given @@ -477,8 +498,9 @@ // Same as above, but for the first "<<" operator. if (Current.is(tok::lessless) && Current.isNot(TT_OverloadedOperator) && - CurrentState.BreakBeforeParameter && CurrentState.FirstLessLess == 0) + CurrentState.BreakBeforeParameter && CurrentState.FirstLessLess == 0) { return true; + } if (Current.NestingLevel == 0 && !Current.isTrailingComment()) { // Always break after "template <...>"(*) and leading annotations. This is @@ -508,11 +530,13 @@ return Style.AlwaysBreakTemplateDeclarations != FormatStyle::BTDS_No; } if (Previous.is(TT_FunctionAnnotationRParen) && - State.Line->Type != LT_PreprocessorDirective) + State.Line->Type != LT_PreprocessorDirective) { return true; + } if (Previous.is(TT_LeadingJavaAnnotation) && Current.isNot(tok::l_paren) && - Current.isNot(TT_LeadingJavaAnnotation)) + Current.isNot(TT_LeadingJavaAnnotation)) { return true; + } } if (Style.isJavaScript() && Previous.is(tok::r_paren) && @@ -534,21 +558,25 @@ // name. !Style.isJavaScript()) || (Current.is(tok::kw_operator) && !Previous.is(tok::coloncolon))) && - !Previous.is(tok::kw_template) && CurrentState.BreakBeforeParameter) + !Previous.is(tok::kw_template) && CurrentState.BreakBeforeParameter) { return true; + } // The following could be precomputed as they do not depend on the state. // However, as they should take effect only if the UnwrappedLine does not fit // into the ColumnLimit, they are checked here in the ContinuationIndenter. if (Style.ColumnLimit != 0 && Previous.is(BK_Block) && - Previous.is(tok::l_brace) && !Current.isOneOf(tok::r_brace, tok::comment)) + Previous.is(tok::l_brace) && + !Current.isOneOf(tok::r_brace, tok::comment)) { return true; + } if (Current.is(tok::lessless) && ((Previous.is(tok::identifier) && Previous.TokenText == "endl") || (Previous.Tok.isLiteral() && (Previous.TokenText.endswith("\\n\"") || - Previous.TokenText == "\'\\n\'")))) + Previous.TokenText == "\'\\n\'")))) { return true; + } if (Previous.is(TT_BlockComment) && Previous.IsMultiline) return true; @@ -639,18 +667,21 @@ PPColumnCorrection = -1; } - if (!DryRun) + if (!DryRun) { Whitespaces.replaceWhitespace(Current, /*Newlines=*/0, Spaces, State.Column + Spaces + PPColumnCorrection); + } // If "BreakBeforeInheritanceComma" mode, don't break within the inheritance // declaration unless there is multiple inheritance. if (Style.BreakInheritanceList == FormatStyle::BILS_BeforeComma && - Current.is(TT_InheritanceColon)) + Current.is(TT_InheritanceColon)) { CurrentState.NoLineBreak = true; + } if (Style.BreakInheritanceList == FormatStyle::BILS_AfterColon && - Previous.is(TT_InheritanceColon)) + Previous.is(TT_InheritanceColon)) { CurrentState.NoLineBreak = true; + } if (Current.is(TT_SelectorName) && !CurrentState.ObjCSelectorNameFound) { unsigned MinIndent = std::max( @@ -684,8 +715,9 @@ // caaaaaaaaaaaall( // caaaaaaaaaaaaaaaaaaaaaaall(aaaaaaaaaaaaaa, aaaaaaaaa)))); Current.FakeLParens.size() > 0 && - Current.FakeLParens.back() > prec::Unknown) + Current.FakeLParens.back() > prec::Unknown) { CurrentState.NoLineBreak = true; + } if (Previous.is(TT_TemplateString) && Previous.opensScope()) CurrentState.NoLineBreak = true; @@ -699,14 +731,15 @@ if (CurrentState.AvoidBinPacking && startsNextParameter(Current, Style)) CurrentState.NoLineBreak = true; if (startsSegmentOfBuilderTypeCall(Current) && - State.Column > getNewLineColumn(State)) + State.Column > getNewLineColumn(State)) { CurrentState.ContainsUnwrappedBuilder = true; + } if (Current.is(TT_LambdaArrow) && Style.Language == FormatStyle::LK_Java) CurrentState.NoLineBreak = true; if (Current.isMemberAccess() && Previous.is(tok::r_paren) && (Previous.MatchingParen && - (Previous.TotalLength - Previous.MatchingParen->TotalLength > 10))) + (Previous.TotalLength - Previous.MatchingParen->TotalLength > 10))) { // If there is a function call with long parameters, break before trailing // calls. This prevents things like: // EXPECT_CALL(SomeLongParameter).Times( @@ -714,6 +747,7 @@ // We don't want to do this for short parameters as they can just be // indexes. CurrentState.NoLineBreak = true; + } // Don't allow the RHS of an operator to be split over multiple lines unless // there is a line-break right after the operator. @@ -740,8 +774,9 @@ if ((!BreakBeforeOperator && !(HasTwoOperands && Style.AlignOperands != FormatStyle::OAS_DontAlign)) || - (!CurrentState.LastOperatorWrapped && BreakBeforeOperator)) + (!CurrentState.LastOperatorWrapped && BreakBeforeOperator)) { CurrentState.NoLineBreakInOperand = true; + } } State.Column += Spaces; @@ -787,8 +822,9 @@ if (Previous.MatchingParen) { const FormatToken *Next = Previous.MatchingParen->getNextNonComment(); if (Next && Next->isMemberAccess() && State.Stack.size() > 1 && - State.Stack[State.Stack.size() - 2].CallContinuation == 0) + State.Stack[State.Stack.size() - 2].CallContinuation == 0) { CurrentState.LastSpace = State.Column; + } } } } @@ -821,8 +857,9 @@ // to avoid unnecessary line breaks that just work around this penalty. if (NextNonComment->is(tok::lessless) && CurrentState.FirstLessLess == 0 && (State.Column <= Style.ColumnLimit / 3 || - CurrentState.BreakBeforeParameter)) + CurrentState.BreakBeforeParameter)) { Penalty += Style.PenaltyBreakFirstLessLess; + } State.Column = getNewLineColumn(State); @@ -838,9 +875,10 @@ // member(value), // looooooooooooooooong_member( // looooooooooong_call(param_1, param_2, param_3)) - if (State.Column > State.FirstIndent) + if (State.Column > State.FirstIndent) { Penalty += Style.PenaltyIndentedWhitespace * (State.Column - State.FirstIndent); + } // Indent nested blocks relative to this column, unless in a very specific // JavaScript special case where: @@ -855,8 +893,9 @@ if (!Current.is(TT_LambdaArrow) && (!Style.isJavaScript() || Current.NestingLevel != 0 || !PreviousNonComment || !PreviousNonComment->is(tok::equal) || - !Current.isOneOf(Keywords.kw_async, Keywords.kw_function))) + !Current.isOneOf(Keywords.kw_async, Keywords.kw_function))) { CurrentState.NestedBlockIndent = State.Column; + } if (NextNonComment->isMemberAccess()) { if (CurrentState.CallContinuation == 0) @@ -889,25 +928,29 @@ // }]; // Thus, we set LastSpace of the next higher NestingLevel, to which we move // when we consume all of the "}"'s FakeRParens at the "{". - if (State.Stack.size() > 1) + if (State.Stack.size() > 1) { State.Stack[State.Stack.size() - 2].LastSpace = std::max(CurrentState.LastSpace, CurrentState.Indent) + Style.ContinuationIndentWidth; + } } if ((PreviousNonComment && PreviousNonComment->isOneOf(tok::comma, tok::semi) && !CurrentState.AvoidBinPacking) || - Previous.is(TT_BinaryOperator)) + Previous.is(TT_BinaryOperator)) { CurrentState.BreakBeforeParameter = false; + } if (PreviousNonComment && (PreviousNonComment->isOneOf(TT_TemplateCloser, TT_JavaAnnotation) || PreviousNonComment->ClosesRequiresClause) && - Current.NestingLevel == 0) + Current.NestingLevel == 0) { CurrentState.BreakBeforeParameter = false; + } if (NextNonComment->is(tok::question) || - (PreviousNonComment && PreviousNonComment->is(tok::question))) + (PreviousNonComment && PreviousNonComment->is(tok::question))) { CurrentState.BreakBeforeParameter = true; + } if (Current.is(TT_BinaryOperator) && Current.CanBreakBefore) CurrentState.BreakBeforeParameter = false; @@ -932,11 +975,12 @@ if (!Current.isTrailingComment()) CurrentState.LastSpace = State.Column; - if (Current.is(tok::lessless)) + if (Current.is(tok::lessless)) { // If we are breaking before a "<<", we always want to indent relative to // RHS. This is necessary only for "<<", as we special-case it and don't // always indent relative to the RHS. CurrentState.LastSpace += 3; // 3 -> width of "<< ". + } State.StartOfLineLevel = Current.NestingLevel; State.LowestLevelOnLine = Current.NestingLevel; @@ -965,19 +1009,22 @@ !PreviousNonComment->isOneOf( TT_BinaryOperator, TT_FunctionAnnotationRParen, TT_JavaAnnotation, TT_LeadingJavaAnnotation) && - Current.isNot(TT_BinaryOperator) && !PreviousNonComment->opensScope()) + Current.isNot(TT_BinaryOperator) && !PreviousNonComment->opensScope()) { CurrentState.BreakBeforeParameter = true; + } // If we break after { or the [ of an array initializer, we should also break // before the corresponding } or ]. if (PreviousNonComment && (PreviousNonComment->isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) || - opensProtoMessageField(*PreviousNonComment, Style))) + opensProtoMessageField(*PreviousNonComment, Style))) { CurrentState.BreakBeforeClosingBrace = true; + } - if (PreviousNonComment && PreviousNonComment->is(tok::l_paren)) + if (PreviousNonComment && PreviousNonComment->is(tok::l_paren)) { CurrentState.BreakBeforeClosingParen = Style.AlignAfterOpenBracket == FormatStyle::BAS_BlockIndent; + } if (CurrentState.AvoidBinPacking) { // If we are breaking after '(', '{', '<', or this is the break after a ':' @@ -995,15 +1042,17 @@ !State.Line->MustBeDeclaration) || (Style.PackConstructorInitializers != FormatStyle::PCIS_NextLine && PreviousIsBreakingCtorInitializerColon) || - Previous.is(TT_DictLiteral)) + Previous.is(TT_DictLiteral)) { CurrentState.BreakBeforeParameter = true; + } // If we are breaking after a ':' to start a member initializer list, // and we allow all arguments on the next line, we should not break // before the next parameter. if (PreviousIsBreakingCtorInitializerColon && - Style.PackConstructorInitializers == FormatStyle::PCIS_NextLine) + Style.PackConstructorInitializers == FormatStyle::PCIS_NextLine) { CurrentState.BreakBeforeParameter = false; + } } return Penalty; @@ -1017,8 +1066,9 @@ const auto &CurrentState = State.Stack.back(); if (CurrentState.IsCSharpGenericTypeConstraint && - Current.isNot(TT_CSharpGenericTypeConstraint)) + Current.isNot(TT_CSharpGenericTypeConstraint)) { return CurrentState.ColonPos + 2; + } const FormatToken &Previous = *Current.Previous; // If we are continuing an expression, we want to use the continuation indent. @@ -1032,14 +1082,16 @@ // Java specific bits. if (Style.Language == FormatStyle::LK_Java && - Current.isOneOf(Keywords.kw_implements, Keywords.kw_extends)) + Current.isOneOf(Keywords.kw_implements, Keywords.kw_extends)) { return std::max(CurrentState.LastSpace, CurrentState.Indent + Style.ContinuationIndentWidth); + } if (Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths && - State.Line->First->is(tok::kw_enum)) + State.Line->First->is(tok::kw_enum)) { return (Style.IndentWidth * State.Line->First->IndentLevel) + Style.IndentWidth; + } if (NextNonComment->is(tok::l_brace) && NextNonComment->is(BK_Block)) return Current.NestingLevel == 0 ? State.FirstIndent : CurrentState.Indent; @@ -1071,22 +1123,26 @@ // } if (Current.is(tok::r_paren) && State.Stack.size() > 1 && (!Current.Next || - Current.Next->isOneOf(tok::semi, tok::kw_const, tok::l_brace))) + Current.Next->isOneOf(tok::semi, tok::kw_const, tok::l_brace))) { return State.Stack[State.Stack.size() - 2].LastSpace; + } if (Style.AlignAfterOpenBracket == FormatStyle::BAS_BlockIndent && - Current.is(tok::r_paren) && State.Stack.size() > 1) + Current.is(tok::r_paren) && State.Stack.size() > 1) { return State.Stack[State.Stack.size() - 2].LastSpace; + } if (NextNonComment->is(TT_TemplateString) && NextNonComment->closesScope()) return State.Stack[State.Stack.size() - 2].LastSpace; if (Current.is(tok::identifier) && Current.Next && (Current.Next->is(TT_DictLiteral) || ((Style.Language == FormatStyle::LK_Proto || Style.Language == FormatStyle::LK_TextProto) && - Current.Next->isOneOf(tok::less, tok::l_brace)))) + Current.Next->isOneOf(tok::less, tok::l_brace)))) { return CurrentState.Indent; + } if (NextNonComment->is(TT_ObjCStringLiteral) && - State.StartOfStringLiteral != 0) + State.StartOfStringLiteral != 0) { return State.StartOfStringLiteral - 1; + } if (NextNonComment->isStringLiteral() && State.StartOfStringLiteral != 0) return State.StartOfStringLiteral; if (NextNonComment->is(tok::lessless) && CurrentState.FirstLessLess != 0) @@ -1139,14 +1195,16 @@ TT_AttributeParen, TT_AttributeSquare, TT_FunctionAnnotationRParen, TT_JavaAnnotation, TT_LeadingJavaAnnotation))) || (!Style.IndentWrappedFunctionNames && - NextNonComment->isOneOf(tok::kw_operator, TT_FunctionDeclarationName))) + NextNonComment->isOneOf(tok::kw_operator, TT_FunctionDeclarationName))) { return std::max(CurrentState.LastSpace, CurrentState.Indent); + } if (NextNonComment->is(TT_SelectorName)) { if (!CurrentState.ObjCSelectorNameFound) { unsigned MinIndent = CurrentState.Indent; - if (shouldIndentWrappedSelectorName(Style, State.Line->Type)) + if (shouldIndentWrappedSelectorName(Style, State.Line->Type)) { MinIndent = std::max(MinIndent, State.FirstIndent + Style.ContinuationIndentWidth); + } // If LongestObjCSelectorName is 0, we are indenting the first // part of an ObjC selector (or a selector component which is // not colon-aligned due to block formatting). @@ -1170,54 +1228,65 @@ if (NextNonComment->is(tok::colon) && NextNonComment->is(TT_ObjCMethodExpr)) return CurrentState.ColonPos; if (NextNonComment->is(TT_ArraySubscriptLSquare)) { - if (CurrentState.StartOfArraySubscripts != 0) + if (CurrentState.StartOfArraySubscripts != 0) { return CurrentState.StartOfArraySubscripts; - else if (Style.isCSharp()) // C# allows `["key"] = value` inside object - // initializers. + } else if (Style.isCSharp()) { // C# allows `["key"] = value` inside object + // initializers. return CurrentState.Indent; + } return ContinuationIndent; } // This ensure that we correctly format ObjC methods calls without inputs, // i.e. where the last element isn't selector like: [callee method]; if (NextNonComment->is(tok::identifier) && NextNonComment->FakeRParens == 0 && - NextNonComment->Next && NextNonComment->Next->is(TT_ObjCMethodExpr)) + NextNonComment->Next && NextNonComment->Next->is(TT_ObjCMethodExpr)) { return CurrentState.Indent; + } if (NextNonComment->isOneOf(TT_StartOfName, TT_PointerOrReference) || - Previous.isOneOf(tok::coloncolon, tok::equal, TT_JsTypeColon)) + Previous.isOneOf(tok::coloncolon, tok::equal, TT_JsTypeColon)) { return ContinuationIndent; + } if (PreviousNonComment && PreviousNonComment->is(tok::colon) && - PreviousNonComment->isOneOf(TT_ObjCMethodExpr, TT_DictLiteral)) + PreviousNonComment->isOneOf(TT_ObjCMethodExpr, TT_DictLiteral)) { return ContinuationIndent; + } if (NextNonComment->is(TT_CtorInitializerComma)) return CurrentState.Indent; if (PreviousNonComment && PreviousNonComment->is(TT_CtorInitializerColon) && - Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon) + Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon) { return CurrentState.Indent; + } if (PreviousNonComment && PreviousNonComment->is(TT_InheritanceColon) && - Style.BreakInheritanceList == FormatStyle::BILS_AfterColon) + Style.BreakInheritanceList == FormatStyle::BILS_AfterColon) { return CurrentState.Indent; + } if (NextNonComment->isOneOf(TT_CtorInitializerColon, TT_InheritanceColon, - TT_InheritanceComma)) + TT_InheritanceComma)) { return State.FirstIndent + Style.ConstructorInitializerIndentWidth; + } if (Previous.is(tok::r_paren) && !Current.isBinaryOperator() && - !Current.isOneOf(tok::colon, tok::comment)) + !Current.isOneOf(tok::colon, tok::comment)) { return ContinuationIndent; + } if (Current.is(TT_ProtoExtensionLSquare)) return CurrentState.Indent; - if (Current.isBinaryOperator() && CurrentState.UnindentOperator) + if (Current.isBinaryOperator() && CurrentState.UnindentOperator) { return CurrentState.Indent - Current.Tok.getLength() - Current.SpacesRequiredBefore; + } if (Current.isOneOf(tok::comment, TT_BlockComment, TT_LineComment) && - NextNonComment->isBinaryOperator() && CurrentState.UnindentOperator) + NextNonComment->isBinaryOperator() && CurrentState.UnindentOperator) { return CurrentState.Indent - NextNonComment->Tok.getLength() - NextNonComment->SpacesRequiredBefore; + } if (CurrentState.Indent == State.FirstIndent && PreviousNonComment && - !PreviousNonComment->isOneOf(tok::r_brace, TT_CtorInitializerComma)) + !PreviousNonComment->isOneOf(tok::r_brace, TT_CtorInitializerComma)) { // Ensure that we fall back to the continuation indent width instead of // just flushing continuations left. return CurrentState.Indent + Style.ContinuationIndentWidth; + } return CurrentState.Indent; } @@ -1254,11 +1323,13 @@ if (Current.is(TT_BinaryOperator) && Current.isNot(tok::lessless)) CurrentState.LastOperatorWrapped = Newline; if (Current.is(TT_ConditionalExpr) && Current.Previous && - !Current.Previous->is(TT_ConditionalExpr)) + !Current.Previous->is(TT_ConditionalExpr)) { CurrentState.LastOperatorWrapped = Newline; + } if (Current.is(TT_ArraySubscriptLSquare) && - CurrentState.StartOfArraySubscripts == 0) + CurrentState.StartOfArraySubscripts == 0) { CurrentState.StartOfArraySubscripts = State.Column; + } auto IsWrappedConditional = [](const FormatToken &Tok) { if (!(Tok.is(TT_ConditionalExpr) && Tok.is(tok::question))) @@ -1281,9 +1352,10 @@ CurrentState.QuestionColumn = State.Column; } if (!Current.opensScope() && !Current.closesScope() && - !Current.is(TT_PointerOrReference)) + !Current.is(TT_PointerOrReference)) { State.LowestLevelOnLine = std::min(State.LowestLevelOnLine, Current.NestingLevel); + } if (Current.isMemberAccess()) CurrentState.StartOfFunctionCall = !Current.NextOperator ? 0 : State.Column; if (Current.is(TT_SelectorName)) @@ -1316,9 +1388,10 @@ if (Style.PackConstructorInitializers > FormatStyle::PCIS_BinPack) CurrentState.AvoidBinPacking = true; } - if (Current.is(TT_InheritanceColon)) + if (Current.is(TT_InheritanceColon)) { CurrentState.Indent = State.FirstIndent + Style.ConstructorInitializerIndentWidth; + } if (Current.isOneOf(TT_BinaryOperator, TT_ConditionalExpr) && Newline) CurrentState.NestedBlockIndent = State.Column + Current.ColumnWidth + 1; if (Current.isOneOf(TT_LambdaLSquare, TT_LambdaArrow)) @@ -1362,13 +1435,14 @@ if (Current.is(TT_ObjCStringLiteral) && State.StartOfStringLiteral == 0) State.StartOfStringLiteral = State.Column + 1; - if (Current.is(TT_CSharpStringLiteral) && State.StartOfStringLiteral == 0) + if (Current.is(TT_CSharpStringLiteral) && State.StartOfStringLiteral == 0) { State.StartOfStringLiteral = State.Column + 1; - else if (Current.isStringLiteral() && State.StartOfStringLiteral == 0) + } else if (Current.isStringLiteral() && State.StartOfStringLiteral == 0) { State.StartOfStringLiteral = State.Column; - else if (!Current.isOneOf(tok::comment, tok::identifier, tok::hash) && - !Current.isStringLiteral()) + } else if (!Current.isOneOf(tok::comment, tok::identifier, tok::hash) && + !Current.isStringLiteral()) { State.StartOfStringLiteral = 0; + } State.Column += Current.ColumnWidth; State.NextToken = State.NextToken->Next; @@ -1461,8 +1535,9 @@ if (PrecedenceLevel > prec::Unknown) NewParenState.LastSpace = std::max(NewParenState.LastSpace, State.Column); if (PrecedenceLevel != prec::Conditional && !Current.is(TT_UnaryOperator) && - Style.AlignAfterOpenBracket != FormatStyle::BAS_DontAlign) + Style.AlignAfterOpenBracket != FormatStyle::BAS_DontAlign) { NewParenState.StartOfFunctionCall = State.Column; + } // Indent conditional expressions, unless they are chained "else-if" // conditionals. Never indent expression where the 'operator' is ',', ';' or @@ -1515,8 +1590,9 @@ // Don't allow '<' or '(' in C# generic type constraints to start new scopes. if (Current.isOneOf(tok::less, tok::l_paren) && - CurrentState.IsCSharpGenericTypeConstraint) + CurrentState.IsCSharpGenericTypeConstraint) { return; + } if (Current.MatchingParen && Current.is(BK_Block)) { moveStateToNewBlock(State); @@ -1596,8 +1672,9 @@ // If this '[' opens an ObjC call, determine whether all parameters fit // into one line and put one per line if they don't. if (getLengthToMatchingParen(Current, State.Stack) + State.Column > - getColumnLimit(State)) + getColumnLimit(State)) { BreakBeforeParameter = true; + } } else { // For ColumnLimit = 0, we have to figure out whether there is or has to // be a line break within this call. @@ -1660,8 +1737,9 @@ (Current.isOneOf(tok::r_paren, tok::r_square, TT_TemplateString) || (Current.is(tok::r_brace) && State.NextToken != State.Line->First) || State.NextToken->is(TT_TemplateCloser) || - (Current.is(tok::greater) && Current.is(TT_DictLiteral)))) + (Current.is(tok::greater) && Current.is(TT_DictLiteral)))) { State.Stack.pop_back(); + } auto &CurrentState = State.Stack.back(); @@ -1684,8 +1762,9 @@ getLengthToMatchingParen(CurrentScopeOpener, State.Stack) + CurrentScopeOpener.TotalLength - Current.TotalLength - 1; if (State.Column + Current.ColumnWidth + NecessarySpaceInLine <= - Style.ColumnLimit) + Style.ColumnLimit) { CurrentState.BreakBeforeParameter = false; + } } } @@ -1972,9 +2051,10 @@ if (!Delimiter) return None; auto RawStringStyle = RawStringFormats.getDelimiterStyle(*Delimiter); - if (!RawStringStyle && Delimiter->empty()) + if (!RawStringStyle && Delimiter->empty()) { RawStringStyle = RawStringFormats.getEnclosingFunctionStyle( getEnclosingFunctionName(Current)); + } if (!RawStringStyle) return None; RawStringStyle->ColumnLimit = getColumnLimit(State); @@ -1991,8 +2071,9 @@ // don't support. if (Style.Language == FormatStyle::LK_Java || Style.isJavaScript() || Style.isCSharp() || Style.isJson() || !Style.BreakStringLiterals || - !AllowBreak) + !AllowBreak) { return nullptr; + } // Don't break string literals inside preprocessor directives (except for // #define directives, as their contents are stored in separate lines and @@ -2039,8 +2120,9 @@ // If a comment token switches formatting, like // /* clang-format on */, we don't want to break it further, // but we may still want to adjust its indentation. - switchesFormatting(Current)) + switchesFormatting(Current)) { return nullptr; + } return std::make_unique( Current, StartColumn, Current.OriginalColumn, !Current.Previous, State.Line->InPPDirective, Encoding, Style, Whitespaces.useCRLF()); @@ -2049,15 +2131,17 @@ Current.Previous->isNot(TT_ImplicitStringLiteral))) { bool RegularComments = [&]() { for (const FormatToken *T = &Current; T && T->is(TT_LineComment); - T = T->Next) + T = T->Next) { if (!(T->TokenText.startswith("//") || T->TokenText.startswith("#"))) return false; + } return true; }(); if (!Style.ReflowComments || CommentPragmasRegex.match(Current.TokenText.substr(2)) || - switchesFormatting(Current) || !RegularComments) + switchesFormatting(Current) || !RegularComments) { return nullptr; + } return std::make_unique( Current, StartColumn, /*InPPDirective=*/false, Encoding, Style); } @@ -2146,11 +2230,12 @@ if (Split.first == StringRef::npos) { // No break opportunity - update the penalty and continue with the next // logical line. - if (LineIndex < EndIndex - 1) + if (LineIndex < EndIndex - 1) { // The last line's penalty is handled in addNextStateToQueue() or when // calling replaceWhitespaceAfterLastLine below. Penalty += Style.PenaltyExcessCharacter * (ContentStartColumn + RemainingTokenColumns - ColumnLimit); + } LLVM_DEBUG(llvm::dbgs() << " No break opportunity.\n"); break; } @@ -2226,9 +2311,10 @@ // The current line fits after compressing the whitespace - reflow // the next line into it if possible. TryReflow = true; - if (!DryRun) + if (!DryRun) { Token->compressWhitespace(LineIndex, TailOffset, Split, Whitespaces); + } // When we continue on the same line, leave one space between content. ContentStartColumn += ToSplitColumns + 1; Penalty += ExcessCharactersPenalty; @@ -2272,9 +2358,10 @@ LLVM_DEBUG(llvm::dbgs() << " Breaking at: " << TailOffset + Split.first << ", " << Split.second << "\n"); - if (!DryRun) + if (!DryRun) { Token->insertBreak(LineIndex, TailOffset, Split, ContentIndent, Whitespaces); + } Penalty += NewBreakPenalty; TailOffset += Split.first + Split.second; @@ -2286,10 +2373,11 @@ // line. if (LineIndex + 1 != EndIndex) { unsigned NextLineIndex = LineIndex + 1; - if (NewBreakBefore) + if (NewBreakBefore) { // After breaking a line, try to reflow the next line into the current // one once RemainingTokenColumns fits. TryReflow = true; + } if (TryReflow) { // We decided that we want to try reflowing the next line into the // current one. @@ -2407,9 +2495,10 @@ Penalty += Style.PenaltyExcessCharacter * (ContentStartColumn + RemainingTokenColumns - ColumnLimit); - if (!DryRun) + if (!DryRun) { Token->replaceWhitespaceAfterLastLine(TailOffset, SplitAfterLastLine, Whitespaces); + } ContentStartColumn = Token->getContentStartColumn(Token->getLineCount() - 1, /*Break=*/true); RemainingTokenColumns = Token->getRemainingLength( @@ -2457,12 +2546,14 @@ if (Current.IsMultiline) return true; if (Current.getNextNonComment() && - Current.getNextNonComment()->isStringLiteral()) + Current.getNextNonComment()->isStringLiteral()) { return true; // Implicit concatenation. + } if (Style.ColumnLimit != 0 && Style.BreakStringLiterals && State.Column + Current.ColumnWidth + Current.UnbreakableTailLength > - Style.ColumnLimit) + Style.ColumnLimit) { return true; // String will be split. + } return false; } diff --git a/clang/lib/Format/DefinitionBlockSeparator.cpp b/clang/lib/Format/DefinitionBlockSeparator.cpp --- a/clang/lib/Format/DefinitionBlockSeparator.cpp +++ b/clang/lib/Format/DefinitionBlockSeparator.cpp @@ -45,8 +45,9 @@ auto LikelyDefinition = [&](const AnnotatedLine *Line, bool ExcludeEnum = false) { if ((Line->MightBeFunctionDecl && Line->mightBeFunctionDefinition()) || - Line->startsWithNamespace()) + Line->startsWithNamespace()) { return true; + } int BracketLevel = 0; for (const FormatToken *CurrentToken = Line->First; CurrentToken; CurrentToken = CurrentToken->Next) { @@ -54,8 +55,9 @@ if ((CurrentToken->isOneOf(tok::kw_class, tok::kw_struct, tok::kw_union) || (Style.isJavaScript() && - CurrentToken->is(ExtraKeywords.kw_function)))) + CurrentToken->is(ExtraKeywords.kw_function)))) { return true; + } if (!ExcludeEnum && CurrentToken->is(tok::kw_enum)) return true; } @@ -92,8 +94,9 @@ return; if (IsAccessSpecifierToken(TargetToken) || (OpeningLineIndex > 0 && - IsAccessSpecifierToken(Lines[OpeningLineIndex - 1]->First))) + IsAccessSpecifierToken(Lines[OpeningLineIndex - 1]->First))) { return; + } if (!TargetLine->Affected) return; Whitespaces.replaceWhitespace(*TargetToken, NewlineToInsert, @@ -156,8 +159,9 @@ if (NextLine->MightBeFunctionDecl && NextLine->mightBeFunctionDefinition() && NextLine->First->NewlinesBefore == 1 && - OperateLine->First->is(TT_FunctionLikeOrFreestandingMacro)) + OperateLine->First->is(TT_FunctionLikeOrFreestandingMacro)) { return true; + } } if ((Style.isCSharp() && OperateLine->First->is(TT_AttributeSquare))) @@ -194,8 +198,9 @@ // misrecognition. if (OpeningLineIndex > 0 && Lines[OpeningLineIndex]->First->is(tok::l_brace) && - Lines[OpeningLineIndex - 1]->Last->isNot(tok::l_brace)) + Lines[OpeningLineIndex - 1]->Last->isNot(tok::l_brace)) { --OpeningLineIndex; + } OpeningLine = Lines[OpeningLineIndex]; // Closing a function definition. if (LikelyDefinition(OpeningLine)) { @@ -209,8 +214,9 @@ // Avoid duplicated replacement. if (TargetToken->isNot(tok::l_brace)) InsertReplacement(NewlineCount); - } else if (IsNeverStyle) + } else if (IsNeverStyle) { InsertReplacement(OpeningLineIndex != 0); + } } } @@ -226,8 +232,9 @@ if (!TargetToken->closesScope() && !IsPPConditional(OpeningLineIndex)) { // Check whether current line may precede a definition line. while (OpeningLineIndex + 1 < Lines.size() && - MayPrecedeDefinition(/*Direction=*/0)) + MayPrecedeDefinition(/*Direction=*/0)) { ++OpeningLineIndex; + } TargetLine = Lines[OpeningLineIndex]; if (!LikelyDefinition(TargetLine)) { OpeningLineIndex = I + 1; @@ -235,16 +242,18 @@ TargetToken = TargetLine->First; InsertReplacement(NewlineCount); } - } else if (IsNeverStyle) + } else if (IsNeverStyle) { InsertReplacement(/*NewlineToInsert=*/1); + } } } - for (const auto &R : Whitespaces.generateReplacements()) + for (const auto &R : Whitespaces.generateReplacements()) { // The add method returns an Error instance which simulates program exit // code through overloading boolean operator, thus false here indicates // success. if (Result.add(R)) return; + } } } // namespace format } // namespace clang diff --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp --- a/clang/lib/Format/Format.cpp +++ b/clang/lib/Format/Format.cpp @@ -675,12 +675,14 @@ // former for backwards compatibility. if (Style.AlwaysBreakAfterDefinitionReturnType != FormatStyle::DRTBS_None && Style.AlwaysBreakAfterReturnType == FormatStyle::RTBS_None) { - if (Style.AlwaysBreakAfterDefinitionReturnType == FormatStyle::DRTBS_All) + if (Style.AlwaysBreakAfterDefinitionReturnType == + FormatStyle::DRTBS_All) { Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_AllDefinitions; - else if (Style.AlwaysBreakAfterDefinitionReturnType == - FormatStyle::DRTBS_TopLevel) + } else if (Style.AlwaysBreakAfterDefinitionReturnType == + FormatStyle::DRTBS_TopLevel) { Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevelDefinitions; + } } IO.mapOptional("AlwaysBreakBeforeMultilineStrings", @@ -704,8 +706,9 @@ // BreakInheritance was not, initialize the latter from the // former for backwards compatibility. if (BreakBeforeInheritanceComma && - Style.BreakInheritanceList == FormatStyle::BILS_BeforeColon) + Style.BreakInheritanceList == FormatStyle::BILS_BeforeColon) { Style.BreakInheritanceList = FormatStyle::BILS_BeforeComma; + } IO.mapOptional("BreakBeforeTernaryOperators", Style.BreakBeforeTernaryOperators); @@ -719,8 +722,9 @@ // BreakConstructorInitializers was not, initialize the latter from the // former for backwards compatibility. if (BreakConstructorInitializersBeforeComma && - Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeColon) + Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeColon) { Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; + } IO.mapOptional("BreakAfterJavaFieldAnnotations", Style.BreakAfterJavaFieldAnnotations); @@ -1944,8 +1948,9 @@ (Style.JavaScriptQuotes == FormatStyle::JSQS_Single && !Input.startswith("\"")) || (Style.JavaScriptQuotes == FormatStyle::JSQS_Double && - !Input.startswith("\'"))) + !Input.startswith("\'"))) { continue; + } // Change start and end quote. bool IsSingle = Style.JavaScriptQuotes == FormatStyle::JSQS_Single; @@ -2052,8 +2057,9 @@ if (Tok->is(tok::coloncolon) && Tok->Previous->is(TT_TemplateOpener)) return true; if (Tok->is(TT_TemplateCloser) && - Tok->Previous->is(TT_TemplateCloser)) + Tok->Previous->is(TT_TemplateCloser)) { return true; + } } } } @@ -2069,11 +2075,15 @@ continue; // Don't treat space in `void foo() &&` as evidence. if (const auto *Prev = Tok->getPreviousNonComment()) { - if (Prev->is(tok::r_paren) && Prev->MatchingParen) - if (const auto *Func = Prev->MatchingParen->getPreviousNonComment()) + if (Prev->is(tok::r_paren) && Prev->MatchingParen) { + if (const auto *Func = + Prev->MatchingParen->getPreviousNonComment()) { if (Func->isOneOf(TT_FunctionDeclarationName, TT_StartOfName, - TT_OverloadedOperator)) + TT_OverloadedOperator)) { continue; + } + } + } } bool SpaceBefore = Tok->hasWhitespaceBefore(); bool SpaceAfter = Tok->Next->hasWhitespaceBefore(); @@ -2109,10 +2119,11 @@ : FormatStyle::PAS_Right; Style.ReferenceAlignment = FormatStyle::RAS_Pointer; } - if (Style.Standard == FormatStyle::LS_Auto) + if (Style.Standard == FormatStyle::LS_Auto) { Style.Standard = hasCpp03IncompatibleFormat(AnnotatedLines) ? FormatStyle::LS_Latest : FormatStyle::LS_Cpp03; + } BinPackInconclusiveFunctions = HasBinPackedFunction || !HasOnePerLineFunction; } @@ -2165,8 +2176,9 @@ continue; if (!(FormatTok->is(tok::r_square) && Matching->is(TT_ArrayInitializerLSquare)) && - !(FormatTok->is(tok::r_brace) && Matching->is(TT_DictLiteral))) + !(FormatTok->is(tok::r_brace) && Matching->is(TT_DictLiteral))) { continue; + } FormatToken *Prev = FormatTok->getPreviousNonComment(); if (Prev->is(tok::comma) || Prev->is(tok::semi)) continue; @@ -2286,8 +2298,9 @@ if (AnnotatedLines[CurrentLine]->startsWithNamespace()) { if (!checkEmptyNamespace(AnnotatedLines, CurrentLine, NewLine, - DeletedLines)) + DeletedLines)) { return false; + } CurrentLine = NewLine; continue; } @@ -2308,8 +2321,9 @@ // Check if the empty namespace is actually affected by changed ranges. if (!AffectedRangeMgr.affectsCharSourceRange(CharSourceRange::getCharRange( AnnotatedLines[InitLine]->First->Tok.getLocation(), - AnnotatedLines[CurrentLine]->Last->Tok.getEndLoc()))) + AnnotatedLines[CurrentLine]->Last->Tok.getEndLoc()))) { return false; + } for (unsigned i = InitLine; i <= CurrentLine; ++i) DeletedLines.insert(i); @@ -2325,10 +2339,12 @@ void cleanupPair(FormatToken *Start, LeftKind LK, RightKind RK, bool DeleteLeft) { auto NextNotDeleted = [this](const FormatToken &Tok) -> FormatToken * { - for (auto *Res = Tok.Next; Res; Res = Res->Next) + for (auto *Res = Tok.Next; Res; Res = Res->Next) { if (!Res->is(tok::comment) && - DeletedTokens.find(Res) == DeletedTokens.end()) + DeletedTokens.find(Res) == DeletedTokens.end()) { return Res; + } + } return nullptr; }; for (auto *Left = Start; Left;) { @@ -2511,8 +2527,9 @@ for (auto Line : AnnotatedLines) { if (Line->First && (Line->First->TokenText.startswith("#") || Line->First->TokenText == "__pragma" || - Line->First->TokenText == "_Pragma")) + Line->First->TokenText == "_Pragma")) { continue; + } for (const FormatToken *FormatTok = Line->First; FormatTok; FormatTok = FormatTok->Next) { if ((FormatTok->Previous && FormatTok->Previous->is(tok::at) && @@ -2568,10 +2585,12 @@ // Determines whether 'Ranges' intersects with ('Start', 'End'). static bool affectsRange(ArrayRef Ranges, unsigned Start, unsigned End) { - for (auto Range : Ranges) + for (auto Range : Ranges) { if (Range.getOffset() < End && - Range.getOffset() + Range.getLength() > Start) + Range.getOffset() + Range.getLength() > Start) { return true; + } + } return false; } @@ -2647,7 +2666,7 @@ SmallVector Indices = llvm::to_vector<16>(llvm::seq(0, Includes.size())); - if (Style.SortIncludes == FormatStyle::SI_CaseInsensitive) + if (Style.SortIncludes == FormatStyle::SI_CaseInsensitive) { llvm::stable_sort(Indices, [&](unsigned LHSI, unsigned RHSI) { const auto LHSFilenameLower = Includes[LHSI].Filename.lower(); const auto RHSFilenameLower = Includes[RHSI].Filename.lower(); @@ -2656,20 +2675,22 @@ std::tie(Includes[RHSI].Priority, RHSFilenameLower, Includes[RHSI].Filename); }); - else + } else { llvm::stable_sort(Indices, [&](unsigned LHSI, unsigned RHSI) { return std::tie(Includes[LHSI].Priority, Includes[LHSI].Filename) < std::tie(Includes[RHSI].Priority, Includes[RHSI].Filename); }); + } // The index of the include on which the cursor will be put after // sorting/deduplicating. unsigned CursorIndex; // The offset from cursor to the end of line. unsigned CursorToEOLOffset; - if (Cursor) + if (Cursor) { std::tie(CursorIndex, CursorToEOLOffset) = FindCursorIndex(Includes, Indices, *Cursor); + } // Deduplicate #includes. Indices.erase(std::unique(Indices.begin(), Indices.end(), @@ -2688,8 +2709,9 @@ // blocks. This we handle below by generating the updated #include blocks and // comparing it to the original. if (Indices.size() == Includes.size() && llvm::is_sorted(Indices) && - Style.IncludeStyle.IncludeBlocks == tooling::IncludeStyle::IBS_Preserve) + Style.IncludeStyle.IncludeBlocks == tooling::IncludeStyle::IBS_Preserve) { return; + } std::string result; for (unsigned Index : Indices) { @@ -2697,8 +2719,9 @@ result += "\n"; if (Style.IncludeStyle.IncludeBlocks == tooling::IncludeStyle::IBS_Regroup && - CurrentCategory != Includes[Index].Category) + CurrentCategory != Includes[Index].Category) { result += "\n"; + } } result += Includes[Index].Text; if (Cursor && CursorIndex == Index) @@ -2712,8 +2735,9 @@ // If the #includes are out of order, we generate a single replacement fixing // the entire range of blocks. Otherwise, no replacement is generated. if (replaceCRLF(result) == replaceCRLF(std::string(Code.substr( - IncludesBeginOffset, IncludesBlockSize)))) + IncludesBeginOffset, IncludesBlockSize)))) { return; + } auto Err = Replaces.add(tooling::Replacement( FileName, Includes.front().Offset, IncludesBlockSize, result)); @@ -2782,11 +2806,13 @@ if (Trimmed.contains(RawStringTermination)) FormattingOff = false; - if (Trimmed == "// clang-format off" || Trimmed == "/* clang-format off */") + if (Trimmed == "// clang-format off" || + Trimmed == "/* clang-format off */") { FormattingOff = true; - else if (Trimmed == "// clang-format on" || - Trimmed == "/* clang-format on */") + } else if (Trimmed == "// clang-format on" || + Trimmed == "/* clang-format on */") { FormattingOff = false; + } const bool EmptyLineSkipped = Trimmed.empty() && @@ -2907,8 +2933,9 @@ if (!result.empty()) { result += "\n"; if (CurrentIsStatic != Imports[Index].IsStatic || - CurrentImportGroup != JavaImportGroups[Index]) + CurrentImportGroup != JavaImportGroups[Index]) { result += "\n"; + } } for (StringRef CommentLine : Imports[Index].AssociatedCommentLines) { result += CommentLine; @@ -2922,8 +2949,9 @@ // If the imports are out of order, we generate a single replacement fixing // the entire block. Otherwise, no replacement is generated. if (replaceCRLF(result) == replaceCRLF(std::string(Code.substr( - Imports.front().Offset, ImportsBlockSize)))) + Imports.front().Offset, ImportsBlockSize)))) { return; + } auto Err = Replaces.add(tooling::Replacement(FileName, Imports.front().Offset, ImportsBlockSize, result)); @@ -3012,8 +3040,9 @@ if (isLikelyXml(Code)) return Replaces; if (Style.Language == FormatStyle::LanguageKind::LK_JavaScript && - isMpegTS(Code)) + isMpegTS(Code)) { return Replaces; + } if (Style.Language == FormatStyle::LanguageKind::LK_JavaScript) return sortJavaScriptImports(Style, Code, Ranges, FileName); if (Style.Language == FormatStyle::LanguageKind::LK_Java) @@ -3227,46 +3256,54 @@ }); } - if (Style.InsertBraces) + if (Style.InsertBraces) { Passes.emplace_back([&](const Environment &Env) { return BracesInserter(Env, Expanded).process(); }); + } - if (Style.RemoveBracesLLVM) + if (Style.RemoveBracesLLVM) { Passes.emplace_back([&](const Environment &Env) { return BracesRemover(Env, Expanded).process(); }); + } - if (Style.FixNamespaceComments) + if (Style.FixNamespaceComments) { Passes.emplace_back([&](const Environment &Env) { return NamespaceEndCommentsFixer(Env, Expanded).process(); }); + } - if (Style.SortUsingDeclarations) + if (Style.SortUsingDeclarations) { Passes.emplace_back([&](const Environment &Env) { return UsingDeclarationsSorter(Env, Expanded).process(); }); + } } - if (Style.SeparateDefinitionBlocks != FormatStyle::SDS_Leave) + if (Style.SeparateDefinitionBlocks != FormatStyle::SDS_Leave) { Passes.emplace_back([&](const Environment &Env) { return DefinitionBlockSeparator(Env, Expanded).process(); }); + } - if (Style.isJavaScript() && Style.JavaScriptQuotes != FormatStyle::JSQS_Leave) + if (Style.isJavaScript() && + Style.JavaScriptQuotes != FormatStyle::JSQS_Leave) { Passes.emplace_back([&](const Environment &Env) { return JavaScriptRequoter(Env, Expanded).process(); }); + } Passes.emplace_back([&](const Environment &Env) { return Formatter(Env, Expanded, Status).process(); }); if (Style.isJavaScript() && - Style.InsertTrailingCommas == FormatStyle::TCS_Wrapped) + Style.InsertTrailingCommas == FormatStyle::TCS_Wrapped) { Passes.emplace_back([&](const Environment &Env) { return TrailingCommaInserter(Env, Expanded).process(); }); + } auto Env = Environment::make(Code, FileName, Ranges, FirstStartColumn, NextStartColumn, LastStartColumn); @@ -3409,18 +3446,21 @@ return FormatStyle::LK_Java; if (FileName.endswith_insensitive(".js") || FileName.endswith_insensitive(".mjs") || - FileName.endswith_insensitive(".ts")) + FileName.endswith_insensitive(".ts")) { return FormatStyle::LK_JavaScript; // (module) JavaScript or TypeScript. + } if (FileName.endswith(".m") || FileName.endswith(".mm")) return FormatStyle::LK_ObjC; if (FileName.endswith_insensitive(".proto") || - FileName.endswith_insensitive(".protodevel")) + FileName.endswith_insensitive(".protodevel")) { return FormatStyle::LK_Proto; + } if (FileName.endswith_insensitive(".textpb") || FileName.endswith_insensitive(".pb.txt") || FileName.endswith_insensitive(".textproto") || - FileName.endswith_insensitive(".asciipb")) + FileName.endswith_insensitive(".asciipb")) { return FormatStyle::LK_TextProto; + } if (FileName.endswith_insensitive(".td")) return FormatStyle::LK_TableGen; if (FileName.endswith_insensitive(".cs")) @@ -3484,13 +3524,15 @@ StringRef Source = ""; if (std::error_code ec = parseConfiguration(llvm::MemoryBufferRef(StyleName, Source), &Style, - AllowUnknownOptions)) + AllowUnknownOptions)) { return make_string_error("Error parsing -style: " + ec.message()); - if (Style.InheritsParentConfig) + } + if (Style.InheritsParentConfig) { ChildFormatTextToApply.emplace_back( llvm::MemoryBuffer::getMemBuffer(StyleName, Source, false)); - else + } else { return Style; + } } // User provided clang-format file using -style=file:path/to/format/file. @@ -3499,9 +3541,10 @@ auto ConfigFile = StyleName.substr(5); llvm::ErrorOr> Text = loadAndParseConfigFile(ConfigFile, FS, &Style, AllowUnknownOptions); - if (auto EC = Text.getError()) + if (auto EC = Text.getError()) { return make_string_error("Error reading " + ConfigFile + ": " + EC.message()); + } LLVM_DEBUG(llvm::dbgs() << "Using configuration file " << ConfigFile << "\n"); @@ -3555,8 +3598,9 @@ auto Status = FS->status(Directory); if (!Status || - Status->getType() != llvm::sys::fs::file_type::directory_file) + Status->getType() != llvm::sys::fs::file_type::directory_file) { continue; + } for (const auto &F : FilesToLookFor) { SmallString<128> ConfigFile(Directory); @@ -3608,10 +3652,11 @@ } } } - if (!UnsuitableConfigFiles.empty()) + if (!UnsuitableConfigFiles.empty()) { return make_string_error("Configuration file(s) do(es) not support " + getLanguageName(Style.Language) + ": " + UnsuitableConfigFiles); + } if (!ChildFormatTextToApply.empty()) { LLVM_DEBUG(llvm::dbgs() diff --git a/clang/lib/Format/FormatToken.cpp b/clang/lib/Format/FormatToken.cpp --- a/clang/lib/Format/FormatToken.cpp +++ b/clang/lib/Format/FormatToken.cpp @@ -106,8 +106,9 @@ State.NextToken->Previous->getPreviousNonComment(); if (!LBrace || !LBrace->isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) || LBrace->is(BK_Block) || LBrace->is(TT_DictLiteral) || - LBrace->Next->is(TT_DesignatedInitializerPeriod)) + LBrace->Next->is(TT_DesignatedInitializerPeriod)) { return 0; + } // Calculate the number of code points we have to format this list. As the // first token is already placed, we have to subtract it. @@ -172,15 +173,17 @@ void CommaSeparatedList::precomputeFormattingInfos(const FormatToken *Token) { // FIXME: At some point we might want to do this for other lists, too. if (!Token->MatchingParen || - !Token->isOneOf(tok::l_brace, TT_ArrayInitializerLSquare)) + !Token->isOneOf(tok::l_brace, TT_ArrayInitializerLSquare)) { return; + } // In C++11 braced list style, we should not format in columns unless they // have many items (20 or more) or we allow bin-packing of function call // arguments. if (Style.Cpp11BracedListStyle && !Style.BinPackArguments && - Commas.size() < 19) + Commas.size() < 19) { return; + } // Limit column layout for JavaScript array initializers to 20 or more items // for now to introduce it carefully. We can become more aggressive if this @@ -238,8 +241,9 @@ // Consume trailing comments so the are included in EndOfLineItemLength. if (ItemEnd->Next && !ItemEnd->Next->HasUnescapedNewline && - ItemEnd->Next->isTrailingComment()) + ItemEnd->Next->isTrailingComment()) { ItemEnd = ItemEnd->Next; + } } EndOfLineItemLength.push_back(CodePointsBetween(ItemBegin, ItemEnd)); // If there is a trailing comma in the list, the next item will start at the @@ -300,8 +304,9 @@ if (Format.ColumnSizes[i] - MinSizeInColumn[i] > 10) return true; return false; - }()) + }()) { continue; + } // Ignore layouts that are bound to violate the column limit. if (Format.TotalWidth > Style.ColumnLimit && Columns > 1) diff --git a/clang/lib/Format/FormatTokenLexer.cpp b/clang/lib/Format/FormatTokenLexer.cpp --- a/clang/lib/Format/FormatTokenLexer.cpp +++ b/clang/lib/Format/FormatTokenLexer.cpp @@ -85,10 +85,11 @@ if (Style.Language == FormatStyle::LK_TextProto) tryParsePythonComment(); tryMergePreviousTokens(); - if (Style.isCSharp()) + if (Style.isCSharp()) { // This needs to come after tokens have been merged so that C# // string literals are correctly identified. handleCSharpVerbatimAndInterpolatedStrings(); + } if (Tokens.back()->NewlinesBefore > 0 || Tokens.back()->IsMultiline) FirstInLineIndex = Tokens.size() - 1; } while (Tokens.back()->isNot(tok::eof)); @@ -335,8 +336,9 @@ auto &NullishCoalescing = *(Tokens.end() - 2); auto &Equal = *(Tokens.end() - 1); if (NullishCoalescing->getType() != TT_NullCoalescingOperator || - !Equal->is(tok::equal)) + !Equal->is(tok::equal)) { return false; + } NullishCoalescing->Tok.setKind(tok::equal); // no '??=' in clang tokens. NullishCoalescing->TokenText = StringRef(NullishCoalescing->TokenText.begin(), @@ -577,8 +579,9 @@ // Deal with multiline strings. if (!(CSharpStringLiteral->TokenText.startswith(R"(@")") || - CSharpStringLiteral->TokenText.startswith(R"($@")"))) + CSharpStringLiteral->TokenText.startswith(R"($@")"))) { return; + } const char *StrBegin = Lex->getBufferLocation() - CSharpStringLiteral->TokenText.size(); @@ -792,13 +795,14 @@ LineStart = Buffer.substr(LineOffset, FirstSpace - LineOffset); TokenType Type = TT_Unknown; - if (LineStart == "<<<<<<<" || LineStart == ">>>>") + if (LineStart == "<<<<<<<" || LineStart == ">>>>") { Type = TT_ConflictStart; - else if (LineStart == "|||||||" || LineStart == "=======" || - LineStart == "====") + } else if (LineStart == "|||||||" || LineStart == "=======" || + LineStart == "====") { Type = TT_ConflictAlternative; - else if (LineStart == ">>>>>>>" || LineStart == "<<<<") + } else if (LineStart == ">>>>>>>" || LineStart == "<<<<") { Type = TT_ConflictEnd; + } if (Type != TT_Unknown) { FormatToken *Next = Tokens.back(); @@ -945,12 +949,13 @@ while (FormatTok->TokenText.size() > 1 && FormatTok->TokenText[0] == '\\') { unsigned SkippedWhitespace = 0; if (FormatTok->TokenText.size() > 2 && - (FormatTok->TokenText[1] == '\r' && FormatTok->TokenText[2] == '\n')) + (FormatTok->TokenText[1] == '\r' && FormatTok->TokenText[2] == '\n')) { SkippedWhitespace = 3; - else if (FormatTok->TokenText[1] == '\n') + } else if (FormatTok->TokenText[1] == '\n') { SkippedWhitespace = 2; - else + } else { break; + } ++FormatTok->NewlinesBefore; WhitespaceLength += SkippedWhitespace; @@ -1063,18 +1068,21 @@ if ((Style.isJavaScript() || Style.Language == FormatStyle::LK_Proto || Style.Language == FormatStyle::LK_TextProto) && - Tok.is(tok::char_constant)) + Tok.is(tok::char_constant)) { Tok.Tok.setKind(tok::string_literal); + } if (Tok.is(tok::comment) && (Tok.TokenText == "// clang-format on" || - Tok.TokenText == "/* clang-format on */")) + Tok.TokenText == "/* clang-format on */")) { FormattingDisabled = false; + } Tok.Finalized = FormattingDisabled; if (Tok.is(tok::comment) && (Tok.TokenText == "// clang-format off" || - Tok.TokenText == "/* clang-format off */")) + Tok.TokenText == "/* clang-format off */")) { FormattingDisabled = true; + } } void FormatTokenLexer::resetLexer(unsigned Offset) { diff --git a/clang/lib/Format/QualifierAlignmentFixer.cpp b/clang/lib/Format/QualifierAlignmentFixer.cpp --- a/clang/lib/Format/QualifierAlignmentFixer.cpp +++ b/clang/lib/Format/QualifierAlignmentFixer.cpp @@ -94,9 +94,10 @@ if (!OriginalCode.equals(Fix.getReplacementText())) { auto Err = NonNoOpFixes.add(Fix); - if (Err) + if (Err) { llvm::errs() << "Error adding replacements : " << llvm::toString(std::move(Err)) << "\n"; + } } } return {NonNoOpFixes, 0}; @@ -108,9 +109,10 @@ auto Replacement = tooling::Replacement(SourceMgr, Range, NewText); auto Err = Fixes.add(Replacement); - if (Err) + if (Err) { llvm::errs() << "Error while rearranging Qualifier : " << llvm::toString(std::move(Err)) << "\n"; + } } static void removeToken(const SourceManager &SourceMgr, @@ -238,8 +240,9 @@ // Move to the end of any template class members e.g. // `Foo::iterator`. if (EndTemplate->startsSequence(TT_TemplateCloser, tok::coloncolon, - tok::identifier)) + tok::identifier)) { EndTemplate = EndTemplate->Next->Next; + } } if (EndTemplate && EndTemplate->Next && !EndTemplate->Next->isOneOf(tok::equal, tok::l_paren)) { @@ -263,8 +266,9 @@ // Move to the end of any template class members e.g. // `Foo::iterator`. if (Next && Next->startsSequence(TT_TemplateCloser, tok::coloncolon, - tok::identifier)) + tok::identifier)) { return Tok; + } assert(Next && "Missing template opener"); Next = Next->Next; } @@ -324,12 +328,14 @@ } if (Tok->is(TT_TemplateOpener) && Tok->Next && (Tok->Next->is(tok::identifier) || Tok->Next->isSimpleTypeSpecifier()) && - Tok->Next->Next && Tok->Next->Next->is(QualifierType)) + Tok->Next->Next && Tok->Next->Next->is(QualifierType)) { rotateTokens(SourceMgr, Fixes, Tok->Next, Tok->Next->Next, /*Left=*/true); + } if (Tok->startsSequence(tok::identifier) && Tok->Next) { if (Tok->Previous && - Tok->Previous->isOneOf(tok::star, tok::ampamp, tok::amp)) + Tok->Previous->isOneOf(tok::star, tok::ampamp, tok::amp)) { return Tok; + } const FormatToken *Next = Tok->Next; // The case `std::Foo const` -> `const std::Foo &&` while (Next && Next->isOneOf(tok::identifier, tok::coloncolon)) @@ -422,12 +428,13 @@ Tok = Tok->Next) { if (Tok->is(tok::comment)) continue; - if (RightAlign) + if (RightAlign) { Tok = analyzeRight(SourceMgr, Keywords, Fixes, Tok, Qualifier, QualifierToken); - else + } else { Tok = analyzeLeft(SourceMgr, Keywords, Fixes, Tok, Qualifier, QualifierToken); + } } } return {Fixes, 0}; @@ -458,11 +465,12 @@ if (QualifierToken != tok::kw_typeof && QualifierToken != tok::identifier) Qualifiers.push_back(QualifierToken); - if (left) + if (left) { // Reverse the order for left aligned items. LeftOrder.insert(LeftOrder.begin(), s); - else + } else { RightOrder.push_back(s); + } } } @@ -479,9 +487,10 @@ return false; if (!Tok->is(tok::identifier)) return false; - if (Tok->TokenText.upper() == Tok->TokenText.str()) + if (Tok->TokenText.upper() == Tok->TokenText.str()) { // T,K,U,V likely could be template arguments return (Tok->TokenText.size() != 1); + } return false; } diff --git a/clang/lib/Format/SortJavaScriptImports.cpp b/clang/lib/Format/SortJavaScriptImports.cpp --- a/clang/lib/Format/SortJavaScriptImports.cpp +++ b/clang/lib/Format/SortJavaScriptImports.cpp @@ -107,12 +107,13 @@ if (LHS.Category != RHS.Category) return LHS.Category < RHS.Category; if (LHS.Category == JsModuleReference::ReferenceCategory::SIDE_EFFECT || - LHS.Category == JsModuleReference::ReferenceCategory::ALIAS) + LHS.Category == JsModuleReference::ReferenceCategory::ALIAS) { // Side effect imports and aliases might be ordering sensitive. Consider // them equal so that they maintain their relative order in the stable sort // below. This retains transitivity because LHS.Category == RHS.Category // here. return false; + } // Empty URLs sort *last* (for export {...};). if (LHS.URL.empty() != RHS.URL.empty()) return LHS.URL.empty() < RHS.URL.empty(); @@ -171,8 +172,9 @@ // in a single group. if (!Reference.IsExport && (Reference.IsExport != References[I + 1].IsExport || - Reference.Category != References[I + 1].Category)) + Reference.Category != References[I + 1].Category)) { ReferencesText += "\n"; + } } } llvm::StringRef PreviousText = getSourceText(InsertionPoint); @@ -193,8 +195,10 @@ // Separate references from the main code body of the file. if (FirstNonImportLine && FirstNonImportLine->First->NewlinesBefore < 2 && !(FirstNonImportLine->First->is(tok::comment) && - FirstNonImportLine->First->TokenText.trim() == "// clang-format on")) + FirstNonImportLine->First->TokenText.trim() == + "// clang-format on")) { ReferencesText += "\n"; + } LLVM_DEBUG(llvm::dbgs() << "Replacing imports:\n" << PreviousText << "\nwith:\n" @@ -389,11 +393,12 @@ Current = Current->Next; } skipComments(); - if (Start.isInvalid() || References.empty()) + if (Start.isInvalid() || References.empty()) { // After the first file level comment, consider line comments to be part // of the import that immediately follows them by using the previously // set Start. Start = Line->First->Tok.getLocation(); + } if (!Current) { // Only comments on this line. Could be the first non-import line. FirstNonImportLine = Line; @@ -462,13 +467,14 @@ // URL = TokenText without the quotes. Reference.URL = Current->TokenText.substr(1, Current->TokenText.size() - 2); - if (Reference.URL.startswith("..")) + if (Reference.URL.startswith("..")) { Reference.Category = JsModuleReference::ReferenceCategory::RELATIVE_PARENT; - else if (Reference.URL.startswith(".")) + } else if (Reference.URL.startswith(".")) { Reference.Category = JsModuleReference::ReferenceCategory::RELATIVE; - else + } else { Reference.Category = JsModuleReference::ReferenceCategory::ABSOLUTE; + } } return true; } diff --git a/clang/lib/Format/TokenAnnotator.cpp b/clang/lib/Format/TokenAnnotator.cpp --- a/clang/lib/Format/TokenAnnotator.cpp +++ b/clang/lib/Format/TokenAnnotator.cpp @@ -54,8 +54,9 @@ // Skip <...> if present. if (Left->Previous && Left->Previous->is(tok::greater) && Left->Previous->MatchingParen && - Left->Previous->MatchingParen->is(TT_TemplateOpener)) + Left->Previous->MatchingParen->is(TT_TemplateOpener)) { Left = Left->Previous->MatchingParen; + } // Check for `[...]`. return Left->Previous && Left->Previous->is(tok::r_square) && @@ -98,8 +99,10 @@ return false; if (Previous.Previous->is(tok::r_paren) && Contexts.size() > 1 && (!Previous.Previous->MatchingParen || - !Previous.Previous->MatchingParen->is(TT_OverloadedOperatorLParen))) + !Previous.Previous->MatchingParen->is( + TT_OverloadedOperatorLParen))) { return false; + } } FormatToken *Left = CurrentToken->Previous; @@ -117,8 +120,9 @@ Contexts.back().ContextType = Context::TemplateArgument; if (Style.Language == FormatStyle::LK_Java && - CurrentToken->is(tok::question)) + CurrentToken->is(tok::question)) { next(); + } while (CurrentToken) { if (CurrentToken->is(tok::greater)) { @@ -133,8 +137,9 @@ (isKeywordWithCondition(*Line.First) || CurrentToken->getStartOfNonWhitespace() == CurrentToken->Next->getStartOfNonWhitespace().getLocWithOffset( - -1))) + -1))) { return false; + } Left->MatchingParen = CurrentToken; CurrentToken->MatchingParen = Left; // In TT_Proto, we must distignuish between: @@ -144,10 +149,11 @@ // In TT_TextProto, map does not occur. if (Style.Language == FormatStyle::LK_TextProto || (Style.Language == FormatStyle::LK_Proto && Left->Previous && - Left->Previous->isOneOf(TT_SelectorName, TT_DictLiteral))) + Left->Previous->isOneOf(TT_SelectorName, TT_DictLiteral))) { CurrentToken->setType(TT_DictLiteral); - else + } else { CurrentToken->setType(TT_TemplateCloser); + } next(); return true; } @@ -159,8 +165,9 @@ if (CurrentToken->isOneOf(tok::r_paren, tok::r_square, tok::r_brace) || (CurrentToken->isOneOf(tok::colon, tok::question) && InExprContext && !Style.isCSharp() && Style.Language != FormatStyle::LK_Proto && - Style.Language != FormatStyle::LK_TextProto)) + Style.Language != FormatStyle::LK_TextProto)) { return false; + } // If a && or || is found and interpreted as a binary operator, this set // of angles is likely part of something like "a < b && c > d". If the // angles are inside an expression, the ||/&& might also be a binary @@ -170,15 +177,17 @@ if (CurrentToken->Previous->isOneOf(tok::pipepipe, tok::ampamp) && CurrentToken->Previous->is(TT_BinaryOperator) && Contexts[Contexts.size() - 2].IsExpression && - !Line.startsWith(tok::kw_template)) + !Line.startsWith(tok::kw_template)) { return false; + } updateParameterCount(Left, CurrentToken); if (Style.Language == FormatStyle::LK_Proto) { if (FormatToken *Previous = CurrentToken->getPreviousNonComment()) { if (CurrentToken->is(tok::colon) || (CurrentToken->isOneOf(tok::l_brace, tok::less) && - Previous->isNot(tok::colon))) + Previous->isNot(tok::colon))) { Previous->setType(TT_SelectorName); + } } } if (!consumeToken()) @@ -232,8 +241,9 @@ if (FormatToken *MaybeSel = OpeningParen.Previous) { // @selector( starts a selector. if (MaybeSel->isObjCAtKeyword(tok::objc_selector) && MaybeSel->Previous && - MaybeSel->Previous->is(tok::at)) + MaybeSel->Previous->is(tok::at)) { StartsObjCMethodExpr = true; + } } if (OpeningParen.is(TT_OverloadedOperatorLParen)) { @@ -356,8 +366,9 @@ if (CurrentToken->Previous->is(TT_PointerOrReference) && CurrentToken->Previous->Previous->isOneOf(tok::l_paren, - tok::coloncolon)) + tok::coloncolon)) { ProbablyFunctionType = true; + } if (CurrentToken->is(tok::comma)) MightBeFunctionType = false; if (CurrentToken->Previous->is(TT_BinaryOperator)) @@ -366,10 +377,12 @@ if (OpeningParen.isNot(TT_CppCastLParen) && MightBeFunctionType && ProbablyFunctionType && CurrentToken->Next && (CurrentToken->Next->is(tok::l_paren) || - (CurrentToken->Next->is(tok::l_square) && Line.MustBeDeclaration))) + (CurrentToken->Next->is(tok::l_square) && + Line.MustBeDeclaration))) { OpeningParen.setType(OpeningParen.Next->is(tok::caret) ? TT_ObjCBlockLParen : TT_FunctionTypeLParen); + } OpeningParen.MatchingParen = CurrentToken; CurrentToken->MatchingParen = &OpeningParen; @@ -379,10 +392,12 @@ // function bodies, e.g.: // auto my_lambda = MACRO((Type *type, int i) { .. body .. }); for (FormatToken *Tok = &OpeningParen; Tok != CurrentToken; - Tok = Tok->Next) + Tok = Tok->Next) { if (Tok->is(TT_BinaryOperator) && - Tok->isOneOf(tok::star, tok::amp, tok::ampamp)) + Tok->isOneOf(tok::star, tok::amp, tok::ampamp)) { Tok->setType(TT_PointerOrReference); + } + } } if (StartsObjCMethodExpr) { @@ -398,14 +413,17 @@ if (OpeningParen.is(TT_TypeDeclarationParen)) CurrentToken->setType(TT_TypeDeclarationParen); if (OpeningParen.Previous && - OpeningParen.Previous->is(TT_JavaAnnotation)) + OpeningParen.Previous->is(TT_JavaAnnotation)) { CurrentToken->setType(TT_JavaAnnotation); + } if (OpeningParen.Previous && - OpeningParen.Previous->is(TT_LeadingJavaAnnotation)) + OpeningParen.Previous->is(TT_LeadingJavaAnnotation)) { CurrentToken->setType(TT_LeadingJavaAnnotation); + } if (OpeningParen.Previous && - OpeningParen.Previous->is(TT_AttributeSquare)) + OpeningParen.Previous->is(TT_AttributeSquare)) { CurrentToken->setType(TT_AttributeSquare); + } if (!HasMultipleLines) OpeningParen.setPackingKind(PPK_Inconclusive); @@ -424,16 +442,18 @@ OpeningParen.setType(TT_Unknown); if (CurrentToken->is(tok::comma) && CurrentToken->Next && !CurrentToken->Next->HasUnescapedNewline && - !CurrentToken->Next->isTrailingComment()) + !CurrentToken->Next->isTrailingComment()) { HasMultipleParametersOnALine = true; + } bool ProbablyFunctionTypeLParen = (CurrentToken->is(tok::l_paren) && CurrentToken->Next && CurrentToken->Next->isOneOf(tok::star, tok::amp, tok::caret)); if ((CurrentToken->Previous->isOneOf(tok::kw_const, tok::kw_auto) || CurrentToken->Previous->isSimpleTypeSpecifier()) && !(CurrentToken->is(tok::l_brace) || - (CurrentToken->is(tok::l_paren) && !ProbablyFunctionTypeLParen))) + (CurrentToken->is(tok::l_paren) && !ProbablyFunctionTypeLParen))) { Contexts.back().IsExpression = false; + } if (CurrentToken->isOneOf(tok::semi, tok::colon)) { MightBeObjCForRangeLoop = false; if (PossibleObjCForInToken) { @@ -498,13 +518,15 @@ // Limit this to being an access modifier that follows. if (AttrTok->isOneOf(tok::kw_public, tok::kw_private, tok::kw_protected, tok::comment, tok::kw_class, tok::kw_static, - tok::l_square, Keywords.kw_internal)) + tok::l_square, Keywords.kw_internal)) { return true; + } // incase its a [XXX] retval func(.... if (AttrTok->Next && - AttrTok->Next->startsSequence(tok::identifier, tok::l_paren)) + AttrTok->Next->startsSequence(tok::identifier, tok::l_paren)) { return true; + } return false; } @@ -530,8 +552,9 @@ // [[foo(:)]]. if (AttrTok->is(tok::colon) || AttrTok->startsSequence(tok::identifier, tok::identifier) || - AttrTok->startsSequence(tok::r_paren, tok::identifier)) + AttrTok->startsSequence(tok::r_paren, tok::identifier)) { return false; + } if (AttrTok->is(tok::ellipsis)) return true; AttrTok = AttrTok->Next; @@ -670,13 +693,13 @@ if (CurrentToken->is(tok::r_square)) { if (IsCpp11AttributeSpecifier) CurrentToken->setType(TT_AttributeSquare); - if (IsCSharpAttributeSpecifier) + if (IsCSharpAttributeSpecifier) { CurrentToken->setType(TT_AttributeSquare); - else if (((CurrentToken->Next && - CurrentToken->Next->is(tok::l_paren)) || - (CurrentToken->Previous && - CurrentToken->Previous->Previous == Left)) && - Left->is(TT_ObjCMethodExpr)) { + } else if (((CurrentToken->Next && + CurrentToken->Next->is(tok::l_paren)) || + (CurrentToken->Previous && + CurrentToken->Previous->Previous == Left)) && + Left->is(TT_ObjCMethodExpr)) { // An ObjC method call is rarely followed by an open parenthesis. It // also can't be composed of just one token, unless it's a macro that // will be expanded to more tokens. @@ -690,8 +713,9 @@ // before the r_square is tagged as a selector name component. if (!ColonFound && CurrentToken->Previous && CurrentToken->Previous->is(TT_Unknown) && - canBeObjCSelectorComponent(*CurrentToken->Previous)) + canBeObjCSelectorComponent(*CurrentToken->Previous)) { CurrentToken->Previous->setType(TT_SelectorName); + } // determineStarAmpUsage() thinks that '*' '[' is allocating an // array of pointers, but if '[' starts a selector then '*' is a // binary operator. @@ -700,8 +724,9 @@ } // An arrow after an ObjC method expression is not a lambda arrow. if (CurrentToken->getType() == TT_ObjCMethodExpr && - CurrentToken->Next && CurrentToken->Next->is(TT_LambdaArrow)) + CurrentToken->Next && CurrentToken->Next->is(TT_LambdaArrow)) { CurrentToken->Next->overwriteFixedType(TT_Unknown); + } Left->MatchingParen = CurrentToken; CurrentToken->MatchingParen = Left; // FirstObjCSelectorName is set when a colon is found. This does @@ -741,15 +766,17 @@ Left->setType(TT_ObjCMethodExpr); StartsObjCMethodExpr = true; Contexts.back().ColonIsObjCMethodExpr = true; - if (Parent && Parent->is(tok::r_paren)) + if (Parent && Parent->is(tok::r_paren)) { // FIXME(bug 36976): ObjC return types shouldn't use TT_CastRParen. Parent->setType(TT_CastRParen); + } } ColonFound = true; } if (CurrentToken->is(tok::comma) && Left->is(TT_ObjCMethodExpr) && - !ColonFound) + !ColonFound) { Left->setType(TT_ArrayInitializerLSquare); + } FormatToken *Tok = CurrentToken; if (!consumeToken()) return false; @@ -790,8 +817,9 @@ if (OpeningBrace.is(BK_BracedInit)) Contexts.back().IsExpression = true; if (Style.isJavaScript() && OpeningBrace.Previous && - OpeningBrace.Previous->is(TT_JsTypeColon)) + OpeningBrace.Previous->is(TT_JsTypeColon)) { Contexts.back().IsExpression = false; + } unsigned CommaCount = 0; while (CurrentToken) { @@ -801,8 +829,9 @@ CurrentToken->MatchingParen = &OpeningBrace; if (Style.AlignArrayOfStructures != FormatStyle::AIAS_None) { if (OpeningBrace.ParentBracket == tok::l_brace && - couldBeInStructArrayInitializer() && CommaCount > 0) + couldBeInStructArrayInitializer() && CommaCount > 0) { Contexts.back().ContextType = Context::StructArrayInitializer; + } } next(); return true; @@ -820,8 +849,9 @@ Style.Language == FormatStyle::LK_TextProto) { OpeningBrace.setType(TT_DictLiteral); if (Previous->Tok.getIdentifierInfo() || - Previous->is(tok::string_literal)) + Previous->is(tok::string_literal)) { Previous->setType(TT_SelectorName); + } } if (CurrentToken->is(tok::colon) && OpeningBrace.is(TT_Unknown)) OpeningBrace.setType(TT_DictLiteral); @@ -948,12 +978,13 @@ Contexts.back().LongestObjCSelectorName == 0 || UnknownIdentifierInMethodDeclaration) { Tok->Previous->setType(TT_SelectorName); - if (!Contexts.back().FirstObjCSelectorName) + if (!Contexts.back().FirstObjCSelectorName) { Contexts.back().FirstObjCSelectorName = Tok->Previous; - else if (Tok->Previous->ColumnWidth > - Contexts.back().LongestObjCSelectorName) + } else if (Tok->Previous->ColumnWidth > + Contexts.back().LongestObjCSelectorName) { Contexts.back().LongestObjCSelectorName = Tok->Previous->ColumnWidth; + } Tok->Previous->ParameterIndex = Contexts.back().FirstObjCSelectorName->ObjCSelectorNameParts; ++Contexts.back().FirstObjCSelectorName->ObjCSelectorNameParts; @@ -968,17 +999,18 @@ FormatToken *Prev = Tok->getPreviousNonComment(); if (!Prev) break; - if (Prev->isOneOf(tok::r_paren, tok::kw_noexcept)) + if (Prev->isOneOf(tok::r_paren, tok::kw_noexcept)) { Tok->setType(TT_CtorInitializerColon); - else if (Prev->is(tok::kw_try)) { + } else if (Prev->is(tok::kw_try)) { // Member initializer list within function try block. FormatToken *PrevPrev = Prev->getPreviousNonComment(); if (!PrevPrev) break; if (PrevPrev && PrevPrev->isOneOf(tok::r_paren, tok::kw_noexcept)) Tok->setType(TT_CtorInitializerColon); - } else + } else { Tok->setType(TT_InheritanceColon); + } } else if (canBeObjCSelectorComponent(*Tok->Previous) && Tok->Next && (Tok->Next->isOneOf(tok::r_paren, tok::comma) || (canBeObjCSelectorComponent(*Tok->Next) && Tok->Next->Next && @@ -999,8 +1031,9 @@ break; case tok::kw_if: if (CurrentToken && - CurrentToken->isOneOf(tok::kw_constexpr, tok::identifier)) + CurrentToken->isOneOf(tok::kw_constexpr, tok::identifier)) { next(); + } LLVM_FALLTHROUGH; case tok::kw_while: if (CurrentToken && CurrentToken->is(tok::l_paren)) { @@ -1013,8 +1046,9 @@ if (Style.isJavaScript()) { // x.for and {for: ...} if ((Tok->Previous && Tok->Previous->is(tok::period)) || - (Tok->Next && Tok->Next->is(tok::colon))) + (Tok->Next && Tok->Next->is(tok::colon))) { break; + } // JS' for await ( ... if (CurrentToken && CurrentToken->is(Keywords.kw_await)) next(); @@ -1046,9 +1080,11 @@ if (Line.MustBeDeclaration && Contexts.size() == 1 && !Contexts.back().IsExpression && !Line.startsWith(TT_ObjCProperty) && !Tok->isOneOf(TT_TypeDeclarationParen, TT_RequiresExpressionLParen) && - (!Tok->Previous || !Tok->Previous->isOneOf(tok::kw___attribute, - TT_LeadingJavaAnnotation))) + (!Tok->Previous || + !Tok->Previous->isOneOf(tok::kw___attribute, + TT_LeadingJavaAnnotation))) { Line.MightBeFunctionDecl = true; + } break; case tok::l_square: if (!parseSquare()) @@ -1102,20 +1138,23 @@ break; case tok::kw_operator: if (Style.Language == FormatStyle::LK_TextProto || - Style.Language == FormatStyle::LK_Proto) + Style.Language == FormatStyle::LK_Proto) { break; + } while (CurrentToken && !CurrentToken->isOneOf(tok::l_paren, tok::semi, tok::r_paren)) { if (CurrentToken->isOneOf(tok::star, tok::amp)) CurrentToken->setType(TT_PointerOrReference); consumeToken(); if (CurrentToken && CurrentToken->is(tok::comma) && - CurrentToken->Previous->isNot(tok::kw_operator)) + CurrentToken->Previous->isNot(tok::kw_operator)) { break; + } if (CurrentToken && CurrentToken->Previous->isOneOf( TT_BinaryOperator, TT_UnaryOperator, tok::comma, - tok::star, tok::arrow, tok::amp, tok::ampamp)) + tok::star, tok::arrow, tok::amp, tok::ampamp)) { CurrentToken->Previous->setType(TT_OverloadedOperator); + } } if (CurrentToken && CurrentToken->is(tok::l_paren)) CurrentToken->setType(TT_OverloadedOperatorLParen); @@ -1136,8 +1175,9 @@ // Declarations cannot be conditional expressions, this can only be part // of a type declaration. if (Line.MustBeDeclaration && !Contexts.back().IsExpression && - Style.isJavaScript()) + Style.isJavaScript()) { break; + } if (Style.isCSharp()) { // `Type?)`, `Type?>`, `Type? name;` and `Type? name =` can only be // nullable types. @@ -1176,8 +1216,9 @@ break; case tok::identifier: if (Tok->isOneOf(Keywords.kw___has_include, - Keywords.kw___has_include_next)) + Keywords.kw___has_include_next)) { parseHasInclude(); + } if (Style.isCSharp() && Tok->is(Keywords.kw_where) && Tok->Next && Tok->Next->isNot(tok::l_paren)) { Tok->setType(TT_CSharpGenericTypeConstraint); @@ -1186,8 +1227,9 @@ break; case tok::arrow: if (Tok->isNot(TT_LambdaArrow) && Tok->Previous && - Tok->Previous->is(tok::kw_noexcept)) + Tok->Previous->is(tok::kw_noexcept)) { Tok->setType(TT_TrailingReturnArrow); + } break; default: break; @@ -1231,8 +1273,9 @@ // Mark tokens up to the trailing line comments as implicit string // literals. if (CurrentToken->isNot(tok::comment) && - !CurrentToken->TokenText.startswith("//")) + !CurrentToken->TokenText.startswith("//")) { CurrentToken->setType(TT_ImplicitStringLiteral); + } next(); } } @@ -1252,7 +1295,8 @@ void parsePragma() { next(); // Consume "pragma". if (CurrentToken && - CurrentToken->isOneOf(Keywords.kw_mark, Keywords.kw_option, Keywords.kw_region)) { + CurrentToken->isOneOf(Keywords.kw_mark, Keywords.kw_option, + Keywords.kw_region)) { bool IsMark = CurrentToken->is(Keywords.kw_mark); next(); next(); // Consume first token (so we fix leading whitespace). @@ -1326,11 +1370,12 @@ while (CurrentToken) { FormatToken *Tok = CurrentToken; next(); - if (Tok->is(tok::l_paren)) + if (Tok->is(tok::l_paren)) { parseParens(); - else if (Tok->isOneOf(Keywords.kw___has_include, - Keywords.kw___has_include_next)) + } else if (Tok->isOneOf(Keywords.kw___has_include, + Keywords.kw___has_include_next)) { parseHasInclude(); + } } return Type; } @@ -1396,8 +1441,9 @@ // an import in this sense. if (Line.First->is(tok::kw_export) && CurrentToken->is(Keywords.kw_from) && CurrentToken->Next && - CurrentToken->Next->isStringLiteral()) + CurrentToken->Next->isStringLiteral()) { ImportStatement = true; + } if (isClosureImportStatement(*CurrentToken)) ImportStatement = true; } @@ -1410,9 +1456,10 @@ return LT_ImportStatement; if (Line.startsWith(TT_ObjCMethodSpecifier)) { - if (Contexts.back().FirstObjCSelectorName) + if (Contexts.back().FirstObjCSelectorName) { Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName = Contexts.back().LongestObjCSelectorName; + } return LT_ObjCMethodDecl; } @@ -1455,8 +1502,9 @@ TT_RecordLBrace, TT_StructLBrace, TT_UnionLBrace, TT_RequiresClause, TT_RequiresClauseInARequiresExpression, TT_RequiresExpression, TT_RequiresExpressionLParen, TT_RequiresExpressionLBrace, - TT_CompoundRequirementLBrace, TT_BracedListLBrace)) + TT_CompoundRequirementLBrace, TT_BracedListLBrace)) { CurrentToken->setType(TT_Unknown); + } CurrentToken->Role.reset(); CurrentToken->MatchingParen = nullptr; CurrentToken->FakeLParens.clear(); @@ -1570,8 +1618,9 @@ return false; if (Tok->isOneOf(tok::kw_class, tok::kw_enum, tok::kw_concept, - tok::kw_struct, tok::kw_using)) + tok::kw_struct, tok::kw_using)) { return false; + } return true; } @@ -1580,8 +1629,10 @@ // using `export type ...`. if (Style.isJavaScript() && (Line.startsWith(Keywords.kw_type, tok::identifier) || - Line.startsWith(tok::kw_export, Keywords.kw_type, tok::identifier))) + Line.startsWith(tok::kw_export, Keywords.kw_type, + tok::identifier))) { return false; + } return !Current.Previous || Current.Previous->isNot(tok::kw_operator); }; @@ -1602,8 +1653,9 @@ break; if (Previous->isOneOf(TT_BinaryOperator, TT_UnaryOperator) && Previous->isOneOf(tok::star, tok::amp, tok::ampamp) && - Previous->Previous && Previous->Previous->isNot(tok::equal)) + Previous->Previous && Previous->Previous->isNot(tok::equal)) { Previous->setType(TT_PointerOrReference); + } } } } else if (Current.is(tok::lessless) && @@ -1624,11 +1676,13 @@ } else if (Current.isOneOf(tok::r_paren, tok::greater, tok::comma)) { for (FormatToken *Previous = Current.Previous; Previous && Previous->isOneOf(tok::star, tok::amp); - Previous = Previous->Previous) + Previous = Previous->Previous) { Previous->setType(TT_PointerOrReference); + } if (Line.MustBeDeclaration && - Contexts.front().ContextType != Context::CtorInitializer) + Contexts.front().ContextType != Context::CtorInitializer) { Contexts.back().IsExpression = false; + } } else if (Current.is(tok::kw_new)) { Contexts.back().CanBeExpression = false; } else if (Current.is(tok::semi) || @@ -1695,8 +1749,9 @@ FormatToken *PriorLeadingIdentifier = LeadingIdentifier->Previous; // Skip back past explicit decoration if (PriorLeadingIdentifier && - PriorLeadingIdentifier->is(tok::kw_explicit)) + PriorLeadingIdentifier->is(tok::kw_explicit)) { PriorLeadingIdentifier = PriorLeadingIdentifier->Previous; + } return PriorLeadingIdentifier && (PriorLeadingIdentifier->is(TT_TemplateCloser) || @@ -1709,9 +1764,10 @@ } void determineTokenType(FormatToken &Current) { - if (!Current.is(TT_Unknown)) + if (!Current.is(TT_Unknown)) { // The token type is already known. return; + } if ((Style.isJavaScript() || Style.isCSharp()) && Current.is(tok::exclaim)) { @@ -1798,15 +1854,17 @@ Style.Language != FormatStyle::LK_TextProto)) { Current.setType(TT_BinaryOperator); } else if (Current.is(tok::comment)) { - if (Current.TokenText.startswith("/*")) - if (Current.TokenText.endswith("*/")) + if (Current.TokenText.startswith("/*")) { + if (Current.TokenText.endswith("*/")) { Current.setType(TT_BlockComment); - else + } else { // The lexer has for some reason determined a comment here. But we // cannot really handle it, if it isn't properly terminated. Current.Tok.setKind(tok::unknown); - else + } + } else { Current.setType(TT_LineComment); + } } else if (Current.is(tok::l_paren)) { if (lParenStartsCppCast(Current)) Current.setType(TT_CppCastLParen); @@ -1817,19 +1875,22 @@ !Current.Next->isBinaryOperator() && !Current.Next->isOneOf(tok::semi, tok::colon, tok::l_brace, tok::comma, tok::period, tok::arrow, - tok::coloncolon)) + tok::coloncolon)) { if (FormatToken *AfterParen = Current.MatchingParen->Next) { // Make sure this isn't the return type of an Obj-C block declaration if (AfterParen->isNot(tok::caret)) { - if (FormatToken *BeforeParen = Current.MatchingParen->Previous) + if (FormatToken *BeforeParen = Current.MatchingParen->Previous) { if (BeforeParen->is(tok::identifier) && !BeforeParen->is(TT_TypenameMacro) && BeforeParen->TokenText == BeforeParen->TokenText.upper() && (!BeforeParen->Previous || - BeforeParen->Previous->ClosesTemplateDeclaration)) + BeforeParen->Previous->ClosesTemplateDeclaration)) { Current.setType(TT_FunctionAnnotationRParen); + } + } } } + } } else if (Current.is(tok::at) && Current.Next && !Style.isJavaScript() && Style.Language != FormatStyle::LK_Java) { // In Java & JavaScript, "@..." is a decorator or annotation. In ObjC, it @@ -1849,12 +1910,13 @@ } else if (Current.is(tok::period)) { FormatToken *PreviousNoComment = Current.getPreviousNonComment(); if (PreviousNoComment && - PreviousNoComment->isOneOf(tok::comma, tok::l_brace)) + PreviousNoComment->isOneOf(tok::comma, tok::l_brace)) { Current.setType(TT_DesignatedInitializerPeriod); - else if (Style.Language == FormatStyle::LK_Java && Current.Previous && - Current.Previous->isOneOf(TT_JavaAnnotation, - TT_LeadingJavaAnnotation)) + } else if (Style.Language == FormatStyle::LK_Java && Current.Previous && + Current.Previous->isOneOf(TT_JavaAnnotation, + TT_LeadingJavaAnnotation)) { Current.setType(Current.Previous->getType()); + } } else if (canBeObjCSelectorComponent(Current) && // FIXME(bug 36976): ObjC return types shouldn't use // TT_CastRParen. @@ -1904,8 +1966,9 @@ return false; if (Tok.Previous->isOneOf(TT_LeadingJavaAnnotation, Keywords.kw_instanceof, - Keywords.kw_as)) + Keywords.kw_as)) { return false; + } if (Style.isJavaScript() && Tok.Previous->is(Keywords.kw_in)) return false; @@ -1927,15 +1990,17 @@ PreviousNotConst->Previous && PreviousNotConst->Previous->is(tok::hash); - if (PreviousNotConst->is(TT_TemplateCloser)) + if (PreviousNotConst->is(TT_TemplateCloser)) { return PreviousNotConst && PreviousNotConst->MatchingParen && PreviousNotConst->MatchingParen->Previous && PreviousNotConst->MatchingParen->Previous->isNot(tok::period) && PreviousNotConst->MatchingParen->Previous->isNot(tok::kw_template); + } if (PreviousNotConst->is(tok::r_paren) && - PreviousNotConst->is(TT_TypeDeclarationParen)) + PreviousNotConst->is(TT_TypeDeclarationParen)) { return true; + } // If is a preprocess keyword like #define. if (IsPPKeyword) @@ -1967,11 +2032,13 @@ if (LeftOfParens && LeftOfParens->is(TT_TemplateCloser) && LeftOfParens->MatchingParen) { auto *Prev = LeftOfParens->MatchingParen->getPreviousNonComment(); - if (Prev && Prev->isOneOf(tok::kw_const_cast, tok::kw_dynamic_cast, - tok::kw_reinterpret_cast, tok::kw_static_cast)) + if (Prev && + Prev->isOneOf(tok::kw_const_cast, tok::kw_dynamic_cast, + tok::kw_reinterpret_cast, tok::kw_static_cast)) { // FIXME: Maybe we should handle identifiers ending with "_cast", // e.g. any_cast? return true; + } } return false; } @@ -1980,8 +2047,9 @@ bool rParenEndsCast(const FormatToken &Tok) { // C-style casts are only used in C++, C# and Java. if (!Style.isCSharp() && !Style.isCpp() && - Style.Language != FormatStyle::LK_Java) + Style.Language != FormatStyle::LK_Java) { return false; + } // Empty parens aren't casts and there are no casts at the end of the line. if (Tok.Previous == Tok.MatchingParen || !Tok.Next || !Tok.MatchingParen) @@ -1994,8 +2062,9 @@ if (LeftOfParens->is(tok::r_paren) && LeftOfParens->isNot(TT_CastRParen)) { if (!LeftOfParens->MatchingParen || - !LeftOfParens->MatchingParen->Previous) + !LeftOfParens->MatchingParen->Previous) { return false; + } LeftOfParens = LeftOfParens->MatchingParen->Previous; } @@ -2022,21 +2091,24 @@ // as a (void *foo) cast. // void operator delete(void *foo) ATTRIB; if (LeftOfParens->Tok.getIdentifierInfo() && LeftOfParens->Previous && - LeftOfParens->Previous->is(tok::kw_operator)) + LeftOfParens->Previous->is(tok::kw_operator)) { return false; + } // If there is an identifier (or with a few exceptions a keyword) right // before the parentheses, this is unlikely to be a cast. if (LeftOfParens->Tok.getIdentifierInfo() && !LeftOfParens->isOneOf(Keywords.kw_in, tok::kw_return, tok::kw_case, - tok::kw_delete)) + tok::kw_delete)) { return false; + } // Certain other tokens right before the parentheses are also signals that // this cannot be a cast. if (LeftOfParens->isOneOf(tok::at, tok::r_square, TT_OverloadedOperator, - TT_TemplateCloser, tok::ellipsis)) + TT_TemplateCloser, tok::ellipsis)) { return false; + } } if (Tok.Next->is(tok::question)) @@ -2051,8 +2123,9 @@ if (Tok.Next->isOneOf(tok::kw_noexcept, tok::kw_volatile, tok::kw_const, tok::kw_requires, tok::kw_throw, tok::arrow, Keywords.kw_override, Keywords.kw_final) || - isCpp11AttributeSpecifier(*Tok.Next)) + isCpp11AttributeSpecifier(*Tok.Next)) { return false; + } // As Java has no function types, a "(" after the ")" likely means that this // is a cast. @@ -2062,8 +2135,9 @@ // If a (non-string) literal follows, this is likely a cast. if (Tok.Next->isNot(tok::string_literal) && (Tok.Next->Tok.isLiteral() || - Tok.Next->isOneOf(tok::kw_sizeof, tok::kw_alignof))) + Tok.Next->isOneOf(tok::kw_sizeof, tok::kw_alignof))) { return true; + } // Heuristically try to determine whether the parentheses contain a type. auto IsQualifiedPointerOrReference = [](FormatToken *T) { @@ -2112,9 +2186,10 @@ // Certain token types inside the parentheses mean that this can't be a // cast. for (const FormatToken *Token = Tok.MatchingParen->Next; Token != &Tok; - Token = Token->Next) + Token = Token->Next) { if (Token->is(TT_BinaryOperator)) return false; + } // If the following token is an identifier or 'this', this is a cast. All // cases where this can be something else are handled above. @@ -2124,8 +2199,9 @@ // Look for a cast `( x ) (`. if (Tok.Next->is(tok::l_paren) && Tok.Previous && Tok.Previous->Previous) { if (Tok.Previous->is(tok::identifier) && - Tok.Previous->Previous->is(tok::l_paren)) + Tok.Previous->Previous->is(tok::l_paren)) { return true; + } } if (!Tok.Next->Next) @@ -2137,13 +2213,15 @@ bool NextIsUnary = Tok.Next->isUnaryOperator() || Tok.Next->isOneOf(tok::amp, tok::star); if (!NextIsUnary || Tok.Next->is(tok::plus) || - !Tok.Next->Next->isOneOf(tok::identifier, tok::numeric_constant)) + !Tok.Next->Next->isOneOf(tok::identifier, tok::numeric_constant)) { return false; + } // Search for unexpected tokens. for (FormatToken *Prev = Tok.Previous; Prev != Tok.MatchingParen; - Prev = Prev->Previous) + Prev = Prev->Previous) { if (!Prev->isOneOf(tok::kw_const, tok::identifier, tok::coloncolon)) return false; + } return true; } @@ -2163,8 +2241,9 @@ TT_ConditionalExpr, tok::l_paren, tok::comma, tok::colon, tok::semi, tok::equal, tok::question, tok::l_square, tok::l_brace, tok::kw_case, tok::kw_co_await, tok::kw_co_return, tok::kw_co_yield, - tok::kw_delete, tok::kw_return, tok::kw_throw)) + tok::kw_delete, tok::kw_return, tok::kw_throw)) { return true; + } // We put sizeof here instead of only in determineStarAmpUsage. In the cases // where the unary `+` operator is overloaded, it is reasonable to write @@ -2205,8 +2284,9 @@ if (!NextToken || NextToken->isOneOf(tok::arrow, tok::equal, tok::kw_noexcept) || NextToken->canBePointerOrReferenceQualifier() || - (NextToken->is(tok::l_brace) && !NextToken->getNextNonComment())) + (NextToken->is(tok::l_brace) && !NextToken->getNextNonComment())) { return TT_PointerOrReference; + } if (PrevToken->is(tok::coloncolon)) return TT_PointerOrReference; @@ -2226,16 +2306,18 @@ if (PrevToken->Tok.isLiteral() || PrevToken->isOneOf(tok::r_paren, tok::r_square, tok::kw_true, - tok::kw_false, tok::r_brace)) + tok::kw_false, tok::r_brace)) { return TT_BinaryOperator; + } const FormatToken *NextNonParen = NextToken; while (NextNonParen && NextNonParen->is(tok::l_paren)) NextNonParen = NextNonParen->getNextNonComment(); if (NextNonParen && (NextNonParen->Tok.isLiteral() || NextNonParen->isOneOf(tok::kw_true, tok::kw_false) || - NextNonParen->isUnaryOperator())) + NextNonParen->isUnaryOperator())) { return TT_BinaryOperator; + } // If we know we're in a template argument, there are no named declarations. // Thus, having an identifier on the right-hand side indicates a binary @@ -2321,8 +2403,9 @@ // expression. while (Current && (Current->is(tok::kw_return) || (Current->is(tok::colon) && - Current->isOneOf(TT_ObjCMethodExpr, TT_DictLiteral)))) + Current->isOneOf(TT_ObjCMethodExpr, TT_DictLiteral)))) { next(); + } if (!Current || Precedence > PrecedenceArrowAndPeriod) return; @@ -2364,8 +2447,9 @@ (Current->MatchingParen || Current->is(TT_TemplateString))) || (CurrentPrecedence != -1 && CurrentPrecedence < Precedence) || (CurrentPrecedence == prec::Conditional && - Precedence == prec::Assignment && Current->is(tok::colon))) + Precedence == prec::Assignment && Current->is(tok::colon))) { break; + } // Consume scopes: (), [], <> and {} // In addition to that we handle require clauses as scope, so that the @@ -2430,8 +2514,9 @@ (NextNonComment->isOneOf(TT_DictLiteral, TT_JsTypeColon) || ((Style.Language == FormatStyle::LK_Proto || Style.Language == FormatStyle::LK_TextProto) && - NextNonComment->is(tok::less)))) + NextNonComment->is(tok::less)))) { return prec::Assignment; + } if (Current->is(TT_JsComputedPropertyName)) return prec::Assignment; if (Current->is(TT_LambdaArrow)) @@ -2440,24 +2525,28 @@ return prec::Assignment; if (Current->isOneOf(tok::semi, TT_InlineASMColon, TT_SelectorName) || (Current->is(tok::comment) && NextNonComment && - NextNonComment->is(TT_SelectorName))) + NextNonComment->is(TT_SelectorName))) { return 0; + } if (Current->is(TT_RangeBasedForLoopColon)) return prec::Comma; if ((Style.Language == FormatStyle::LK_Java || Style.isJavaScript()) && - Current->is(Keywords.kw_instanceof)) + Current->is(Keywords.kw_instanceof)) { return prec::Relational; + } if (Style.isJavaScript() && - Current->isOneOf(Keywords.kw_in, Keywords.kw_as)) + Current->isOneOf(Keywords.kw_in, Keywords.kw_as)) { return prec::Relational; + } if (Current->is(TT_BinaryOperator) || Current->is(tok::comma)) return Current->getPrecedence(); if (Current->isOneOf(tok::period, tok::arrow)) return PrecedenceArrowAndPeriod; if ((Style.Language == FormatStyle::LK_Java || Style.isJavaScript()) && Current->isOneOf(Keywords.kw_extends, Keywords.kw_implements, - Keywords.kw_throws)) + Keywords.kw_throws)) { return 0; + } } return -1; } @@ -2485,9 +2574,10 @@ next(); } parse(PrecedenceArrowAndPeriod); - for (FormatToken *Token : llvm::reverse(Tokens)) + for (FormatToken *Token : llvm::reverse(Tokens)) { // The actual precedence doesn't matter. addFakeParenthesis(Token, prec::Unknown); + } } void parseConditionalExpr() { @@ -2511,8 +2601,9 @@ Current = Current->Next; while (Current && (Current->NewlinesBefore == 0 || SkipPastLeadingComments) && - Current->isTrailingComment()) + Current->isTrailingComment()) { Current = Current->Next; + } } const FormatStyle &Style; @@ -2603,8 +2694,9 @@ if (Next->isOneOf(tok::kw_new, tok::kw_delete)) { // For 'new[]' and 'delete[]'. if (Next->Next && - Next->Next->startsSequence(tok::l_square, tok::r_square)) + Next->Next->startsSequence(tok::l_square, tok::r_square)) { Next = Next->Next->Next; + } continue; } if (Next->startsSequence(tok::l_square, tok::r_square)) { @@ -2668,8 +2760,9 @@ return true; // Empty parentheses. // If there is an &/&& after the r_paren, this is likely a function. if (Next->MatchingParen->Next && - Next->MatchingParen->Next->is(TT_PointerOrReference)) + Next->MatchingParen->Next->is(TT_PointerOrReference)) { return true; + } // Check for K&R C function definitions (and C++ function definitions with // unnamed parameters), e.g.: @@ -2682,8 +2775,9 @@ // return !b; // } if (IsCpp && Next->Next && Next->Next->is(tok::identifier) && - !Line.endsWith(tok::semi)) + !Line.endsWith(tok::semi)) { return true; + } for (const FormatToken *Tok = Next->Next; Tok && Tok != Next->MatchingParen; Tok = Tok->Next) { @@ -2694,11 +2788,13 @@ continue; } if (Tok->is(tok::kw_const) || Tok->isSimpleTypeSpecifier() || - Tok->isOneOf(TT_PointerOrReference, TT_StartOfName, tok::ellipsis)) + Tok->isOneOf(TT_PointerOrReference, TT_StartOfName, tok::ellipsis)) { return true; + } if (Tok->isOneOf(tok::l_brace, tok::string_literal, TT_ObjCMethodExpr) || - Tok->Tok.isLiteral()) + Tok->Tok.isLiteral()) { return false; + } } return false; } @@ -2709,8 +2805,9 @@ if ((Style.AlwaysBreakAfterReturnType == FormatStyle::RTBS_TopLevel || Style.AlwaysBreakAfterReturnType == FormatStyle::RTBS_TopLevelDefinitions) && - Line.Level > 0) + Line.Level > 0) { return false; + } switch (Style.AlwaysBreakAfterReturnType) { case FormatStyle::RTBS_None: @@ -2746,11 +2843,12 @@ Current->setType(TT_FunctionDeclarationName); const FormatToken *Prev = Current->Previous; if (Current->is(TT_LineComment)) { - if (Prev->is(BK_BracedInit) && Prev->opensScope()) + if (Prev->is(BK_BracedInit) && Prev->opensScope()) { Current->SpacesRequiredBefore = (Style.Cpp11BracedListStyle && !Style.SpacesInParentheses) ? 0 : 1; - else + } else { Current->SpacesRequiredBefore = Style.SpacesBeforeTrailingComments; + } // If we find a trailing comment, iterate backwards to determine whether // it seems to relate to a specific parameter. If so, break before that @@ -2766,8 +2864,9 @@ break; if (Parameter->Previous && Parameter->Previous->is(tok::comma)) { if (!Parameter->Previous->is(TT_CtorInitializerComma) && - Parameter->HasUnescapedNewline) + Parameter->HasUnescapedNewline) { Parameter->MustBreakBefore = true; + } break; } } @@ -2784,8 +2883,9 @@ Current->MustBreakBefore = Current->MustBreakBefore || mustBreakBefore(Line, *Current); if (!Current->MustBreakBefore && InFunctionDecl && - Current->is(TT_FunctionDeclarationName)) + Current->is(TT_FunctionDeclarationName)) { Current->MustBreakBefore = mustBreakForReturnType(Line); + } } Current->CanBreakBefore = @@ -2799,11 +2899,12 @@ if (Current->MustBreakBefore || Prev->Children.size() > 1 || (Prev->Children.size() == 1 && Prev->Children[0]->First->MustBreakBefore) || - Current->IsMultiline) + Current->IsMultiline) { Current->TotalLength = Prev->TotalLength + Style.ColumnLimit; - else + } else { Current->TotalLength = Prev->TotalLength + Current->ColumnWidth + ChildSize + Current->SpacesRequiredBefore; + } if (Current->is(TT_CtorInitializerColon)) InFunctionDecl = false; @@ -2836,8 +2937,9 @@ Current->Role->precomputeFormattingInfos(Current); if (Current->MatchingParen && Current->MatchingParen->opensBlockOrBlockTypeList(Style) && - IndentLevel > 0) + IndentLevel > 0) { --IndentLevel; + } Current->IndentLevel = IndentLevel; if (Current->opensBlockOrBlockTypeList(Style)) ++IndentLevel; @@ -2924,8 +3026,9 @@ if (Left.is(TT_JsTypeColon)) return 35; if ((Left.is(TT_TemplateString) && Left.TokenText.endswith("${")) || - (Right.is(TT_TemplateString) && Right.TokenText.startswith("}"))) + (Right.is(TT_TemplateString) && Right.TokenText.startswith("}"))) { return 100; + } // Prefer breaking call chains (".foo") over empty "{}", "[]" or "()". if (Left.opensScope() && Right.closesScope()) return 200; @@ -2943,13 +3046,15 @@ return 35; if (!Right.isOneOf(TT_ObjCMethodExpr, TT_LambdaLSquare, TT_ArrayInitializerLSquare, - TT_DesignatedInitializerLSquare, TT_AttributeSquare)) + TT_DesignatedInitializerLSquare, TT_AttributeSquare)) { return 500; + } } if (Left.is(tok::coloncolon) || - (Right.is(tok::period) && Style.Language == FormatStyle::LK_Proto)) + (Right.is(tok::period) && Style.Language == FormatStyle::LK_Proto)) { return 500; + } if (Right.isOneOf(TT_StartOfName, TT_FunctionDeclarationName) || Right.is(tok::kw_operator)) { if (Line.startsWith(tok::kw_for) && Right.PartOfMultiVariableDeclStmt) @@ -2974,8 +3079,9 @@ return 1000; if (Left.isOneOf(TT_RangeBasedForLoopColon, TT_InheritanceColon, - TT_CtorInitializerColon)) + TT_CtorInitializerColon)) { return 2; + } if (Right.isMemberAccess()) { // Breaking before the "./->" of a chained call/member access is reasonably @@ -3032,17 +3138,20 @@ // open paren (we'll prefer breaking after the protocol list's opening // angle bracket, if present). if (Line.Type == LT_ObjCDecl && Left.is(tok::l_paren) && Left.Previous && - Left.Previous->isOneOf(tok::identifier, tok::greater)) + Left.Previous->isOneOf(tok::identifier, tok::greater)) { return 500; + } if (Left.is(tok::l_paren) && Style.PenaltyBreakOpenParenthesis != 0) return Style.PenaltyBreakOpenParenthesis; if (Left.is(tok::l_paren) && InFunctionDecl && - Style.AlignAfterOpenBracket != FormatStyle::BAS_DontAlign) + Style.AlignAfterOpenBracket != FormatStyle::BAS_DontAlign) { return 100; + } if (Left.is(tok::l_paren) && Left.Previous && - (Left.Previous->is(tok::kw_for) || Left.Previous->isIf())) + (Left.Previous->is(tok::kw_for) || Left.Previous->isIf())) { return 1000; + } if (Left.is(tok::equal) && InFunctionDecl) return 110; if (Right.is(tok::r_brace)) @@ -3054,8 +3163,9 @@ // here unless the style does not want us to place all arguments on the // next line. if (Style.AlignAfterOpenBracket == FormatStyle::BAS_DontAlign && - (Left.ParameterCount <= 1 || Style.AllowAllArgumentsOnNextLine)) + (Left.ParameterCount <= 1 || Style.AllowAllArgumentsOnNextLine)) { return 0; + } if (Left.is(tok::l_brace) && !Style.Cpp11BracedListStyle) return 19; return Left.ParameterCount > 1 ? Style.PenaltyBreakBeforeFirstCallParameter @@ -3068,21 +3178,25 @@ return 60; if (Left.isOneOf(tok::plus, tok::comma) && Left.Previous && Left.Previous->isLabelString() && - (Left.NextOperator || Left.OperatorIndex != 0)) + (Left.NextOperator || Left.OperatorIndex != 0)) { return 50; + } if (Right.is(tok::plus) && Left.isLabelString() && - (Right.NextOperator || Right.OperatorIndex != 0)) + (Right.NextOperator || Right.OperatorIndex != 0)) { return 25; + } if (Left.is(tok::comma)) return 1; if (Right.is(tok::lessless) && Left.isLabelString() && - (Right.NextOperator || Right.OperatorIndex != 1)) + (Right.NextOperator || Right.OperatorIndex != 1)) { return 25; + } if (Right.is(tok::lessless)) { // Breaking at a << is really cheap. - if (!Left.is(tok::r_paren) || Right.OperatorIndex > 0) + if (!Left.is(tok::r_paren) || Right.OperatorIndex > 0) { // Slightly prefer to break before the first one in log-like statements. return 2; + } return 1; } if (Left.ClosesTemplateDeclaration) @@ -3106,11 +3220,13 @@ if (Style.SpaceBeforeParens == FormatStyle::SBPO_Always) return true; if (Right.is(TT_OverloadedOperatorLParen) && - Style.SpaceBeforeParensOptions.AfterOverloadedOperator) + Style.SpaceBeforeParensOptions.AfterOverloadedOperator) { return true; + } if (Style.SpaceBeforeParensOptions.BeforeNonEmptyParentheses && - Right.ParameterCount > 0) + Right.ParameterCount > 0) { return true; + } return false; } @@ -3118,23 +3234,26 @@ const FormatToken &Left, const FormatToken &Right) const { if (Left.is(tok::kw_return) && - !Right.isOneOf(tok::semi, tok::r_paren, tok::hashhash)) + !Right.isOneOf(tok::semi, tok::r_paren, tok::hashhash)) { return true; + } if (Style.isJson() && Left.is(tok::string_literal) && Right.is(tok::colon)) return false; if (Left.is(Keywords.kw_assert) && Style.Language == FormatStyle::LK_Java) return true; if (Style.ObjCSpaceAfterProperty && Line.Type == LT_ObjCProperty && - Left.Tok.getObjCKeywordID() == tok::objc_property) + Left.Tok.getObjCKeywordID() == tok::objc_property) { return true; + } if (Right.is(tok::hashhash)) return Left.is(tok::hash); if (Left.isOneOf(tok::hashhash, tok::hash)) return Right.is(tok::hash); if ((Left.is(tok::l_paren) && Right.is(tok::r_paren)) || (Left.is(tok::l_brace) && Left.isNot(BK_Block) && - Right.is(tok::r_brace) && Right.isNot(BK_Block))) + Right.is(tok::r_brace) && Right.isNot(BK_Block))) { return Style.SpaceInEmptyParentheses; + } if (Style.SpacesInConditionalStatement) { const FormatToken *LeftParen = nullptr; if (Left.is(tok::l_paren)) @@ -3142,8 +3261,9 @@ else if (Right.is(tok::r_paren) && Right.MatchingParen) LeftParen = Right.MatchingParen; if (LeftParen && LeftParen->Previous && - isKeywordWithCondition(*LeftParen->Previous)) + isKeywordWithCondition(*LeftParen->Previous)) { return true; + } } // auto{x} auto(x) @@ -3152,18 +3272,21 @@ // operator co_await(x) if (Right.is(tok::l_paren) && Left.is(tok::kw_co_await) && Left.Previous && - Left.Previous->is(tok::kw_operator)) + Left.Previous->is(tok::kw_operator)) { return false; + } // co_await (x), co_yield (x), co_return (x) if (Left.isOneOf(tok::kw_co_await, tok::kw_co_yield, tok::kw_co_return) && - !Right.isOneOf(tok::semi, tok::r_paren)) + !Right.isOneOf(tok::semi, tok::r_paren)) { return true; + } - if (Left.is(tok::l_paren) || Right.is(tok::r_paren)) + if (Left.is(tok::l_paren) || Right.is(tok::r_paren)) { return (Right.is(TT_CastRParen) || (Left.MatchingParen && Left.MatchingParen->is(TT_CastRParen))) ? Style.SpacesInCStyleCastParentheses : Style.SpacesInParentheses; + } if (Right.isOneOf(tok::semi, tok::comma)) return false; if (Right.is(tok::less) && Line.Type == LT_ObjCDecl) { @@ -3179,8 +3302,9 @@ if (Left.is(tok::at) && Right.isOneOf(tok::identifier, tok::string_literal, tok::char_constant, tok::numeric_constant, tok::l_paren, tok::l_brace, - tok::kw_true, tok::kw_false)) + tok::kw_true, tok::kw_false)) { return false; + } if (Left.is(tok::colon)) return !Left.is(TT_ObjCMethodExpr); if (Left.is(tok::coloncolon)) @@ -3196,9 +3320,10 @@ } return false; } - if (Right.is(tok::ellipsis)) + if (Right.is(tok::ellipsis)) { return Left.Tok.isLiteral() || (Left.is(tok::identifier) && Left.Previous && Left.Previous->is(tok::kw_case)); + } if (Left.is(tok::l_square) && Right.is(tok::amp)) return Style.SpacesInSquareBrackets; if (Right.is(TT_PointerOrReference)) { @@ -3215,15 +3340,18 @@ // after pointer qualifiers. if ((Style.SpaceAroundPointerQualifiers == FormatStyle::SAPQ_After || Style.SpaceAroundPointerQualifiers == FormatStyle::SAPQ_Both) && - (Left.is(TT_AttributeParen) || Left.canBePointerOrReferenceQualifier())) + (Left.is(TT_AttributeParen) || + Left.canBePointerOrReferenceQualifier())) { return true; + } if (Left.Tok.isLiteral()) return true; // for (auto a = 0, b = 0; const auto & c : {1, 2, 3}) if (Left.isTypeOrIdentifier() && Right.Next && Right.Next->Next && - Right.Next->Next->is(TT_RangeBasedForLoopColon)) + Right.Next->Next->is(TT_RangeBasedForLoopColon)) { return getTokenPointerOrReferenceAlignment(Right) != FormatStyle::PAS_Left; + } return !Left.isOneOf(TT_PointerOrReference, tok::l_paren) && (getTokenPointerOrReferenceAlignment(Right) != FormatStyle::PAS_Left || @@ -3234,15 +3362,17 @@ if (Right.is(TT_FunctionTypeLParen) && Left.isNot(tok::l_paren) && (!Left.is(TT_PointerOrReference) || (getTokenPointerOrReferenceAlignment(Left) != FormatStyle::PAS_Right && - !Line.IsMultiVariableDeclStmt))) + !Line.IsMultiVariableDeclStmt))) { return true; + } if (Left.is(TT_PointerOrReference)) { // Add a space if the next token is a pointer qualifier and the style // requires spaces before pointer qualifiers. if ((Style.SpaceAroundPointerQualifiers == FormatStyle::SAPQ_Before || Style.SpaceAroundPointerQualifiers == FormatStyle::SAPQ_Both) && - Right.canBePointerOrReferenceQualifier()) + Right.canBePointerOrReferenceQualifier()) { return true; + } // & 1 if (Right.Tok.isLiteral()) return true; @@ -3251,19 +3381,22 @@ return true; // foo() -> const Bar * override/final if (Right.isOneOf(Keywords.kw_override, Keywords.kw_final) && - !Right.is(TT_StartOfName)) + !Right.is(TT_StartOfName)) { return true; + } // & { if (Right.is(tok::l_brace) && Right.is(BK_Block)) return true; // for (auto a = 0, b = 0; const auto& c : {1, 2, 3}) if (Left.Previous && Left.Previous->isTypeOrIdentifier() && Right.Next && - Right.Next->is(TT_RangeBasedForLoopColon)) + Right.Next->is(TT_RangeBasedForLoopColon)) { return getTokenPointerOrReferenceAlignment(Left) != FormatStyle::PAS_Right; + } if (Right.isOneOf(TT_PointerOrReference, TT_ArraySubscriptLSquare, - tok::l_paren)) + tok::l_paren)) { return false; + } if (getTokenPointerOrReferenceAlignment(Left) == FormatStyle::PAS_Right) return false; // FIXME: Setting IsMultiVariableDeclStmt for the whole line is error-prone, @@ -3275,15 +3408,17 @@ if (Line.IsMultiVariableDeclStmt && (Left.NestingLevel == Line.First->NestingLevel || ((Left.NestingLevel == Line.First->NestingLevel + 1) && - startsWithInitStatement(Line)))) + startsWithInitStatement(Line)))) { return false; + } return Left.Previous && !Left.Previous->isOneOf( tok::l_paren, tok::coloncolon, tok::l_square); } // Ensure right pointer alignment with ellipsis e.g. int *...P if (Left.is(tok::ellipsis) && Left.Previous && - Left.Previous->isOneOf(tok::star, tok::amp, tok::ampamp)) + Left.Previous->isOneOf(tok::star, tok::amp, tok::ampamp)) { return Style.PointerAlignment != FormatStyle::PAS_Right; + } if (Right.is(tok::star) && Left.is(tok::l_paren)) return false; @@ -3321,11 +3456,12 @@ if (Previous) { if (Previous->endsSequence(tok::kw_operator)) return Style.PointerAlignment != FormatStyle::PAS_Left; - if (Previous->is(tok::kw_const) || Previous->is(tok::kw_volatile)) + if (Previous->is(tok::kw_const) || Previous->is(tok::kw_volatile)) { return (Style.PointerAlignment != FormatStyle::PAS_Left) || (Style.SpaceAroundPointerQualifiers == FormatStyle::SAPQ_After) || (Style.SpaceAroundPointerQualifiers == FormatStyle::SAPQ_Both); + } } } const auto SpaceRequiredForArrayInitializerLSquare = @@ -3337,13 +3473,14 @@ LSquareTok.endsSequence(tok::l_square, tok::colon, TT_SelectorName)); }; - if (Left.is(tok::l_square)) + if (Left.is(tok::l_square)) { return (Left.is(TT_ArrayInitializerLSquare) && Right.isNot(tok::r_square) && SpaceRequiredForArrayInitializerLSquare(Left, Style)) || (Left.isOneOf(TT_ArraySubscriptLSquare, TT_StructuredBindingLSquare, TT_LambdaLSquare) && Style.SpacesInSquareBrackets && Right.isNot(tok::r_square)); - if (Right.is(tok::r_square)) + } + if (Right.is(tok::r_square)) { return Right.MatchingParen && ((Right.MatchingParen->is(TT_ArrayInitializerLSquare) && SpaceRequiredForArrayInitializerLSquare(*Right.MatchingParen, @@ -3353,23 +3490,27 @@ TT_StructuredBindingLSquare, TT_LambdaLSquare)) || Right.MatchingParen->is(TT_AttributeParen)); + } if (Right.is(tok::l_square) && !Right.isOneOf(TT_ObjCMethodExpr, TT_LambdaLSquare, TT_DesignatedInitializerLSquare, TT_StructuredBindingLSquare, TT_AttributeSquare) && !Left.isOneOf(tok::numeric_constant, TT_DictLiteral) && !(!Left.is(tok::r_square) && Style.SpaceBeforeSquareBrackets && - Right.is(TT_ArraySubscriptLSquare))) + Right.is(TT_ArraySubscriptLSquare))) { return false; + } if (Left.is(tok::l_brace) && Right.is(tok::r_brace)) return !Left.Children.empty(); // No spaces in "{}". if ((Left.is(tok::l_brace) && Left.isNot(BK_Block)) || (Right.is(tok::r_brace) && Right.MatchingParen && - Right.MatchingParen->isNot(BK_Block))) + Right.MatchingParen->isNot(BK_Block))) { return Style.Cpp11BracedListStyle ? Style.SpacesInParentheses : true; - if (Left.is(TT_BlockComment)) + } + if (Left.is(TT_BlockComment)) { // No whitespace in x(/*foo=*/1), except for JavaScript. return Style.isJavaScript() || !Left.TokenText.endswith("=*/"); + } // Space between template and attribute. // e.g. template [[nodiscard]] ... @@ -3379,30 +3520,37 @@ if (Right.is(tok::l_paren)) { if (Left.is(TT_TemplateCloser) && Right.isNot(TT_FunctionTypeLParen)) return spaceRequiredBeforeParens(Right); - if (Left.isOneOf(TT_RequiresClause, TT_RequiresClauseInARequiresExpression)) + if (Left.isOneOf(TT_RequiresClause, + TT_RequiresClauseInARequiresExpression)) { return Style.SpaceBeforeParensOptions.AfterRequiresInClause || spaceRequiredBeforeParens(Right); - if (Left.is(TT_RequiresExpression)) + } + if (Left.is(TT_RequiresExpression)) { return Style.SpaceBeforeParensOptions.AfterRequiresInExpression || spaceRequiredBeforeParens(Right); + } if ((Left.is(tok::r_paren) && Left.is(TT_AttributeParen)) || - (Left.is(tok::r_square) && Left.is(TT_AttributeSquare))) + (Left.is(tok::r_square) && Left.is(TT_AttributeSquare))) { return true; - if (Left.is(TT_ForEachMacro)) + } + if (Left.is(TT_ForEachMacro)) { return Style.SpaceBeforeParensOptions.AfterForeachMacros || spaceRequiredBeforeParens(Right); - if (Left.is(TT_IfMacro)) + } + if (Left.is(TT_IfMacro)) { return Style.SpaceBeforeParensOptions.AfterIfMacros || spaceRequiredBeforeParens(Right); + } if (Line.Type == LT_ObjCDecl) return true; if (Left.is(tok::semi)) return true; if (Left.isOneOf(tok::pp_elif, tok::kw_for, tok::kw_while, tok::kw_switch, tok::kw_case, TT_ForEachMacro, TT_ObjCForIn) || - Left.isIf(Line.Type != LT_PreprocessorDirective)) + Left.isIf(Line.Type != LT_PreprocessorDirective)) { return Style.SpaceBeforeParensOptions.AfterControlStatements || spaceRequiredBeforeParens(Right); + } // TODO add Operator overloading specific Options to // SpaceBeforeParensOptions @@ -3410,50 +3558,58 @@ return spaceRequiredBeforeParens(Right); // Function declaration or definition if (Line.MightBeFunctionDecl && (Left.is(TT_FunctionDeclarationName))) { - if (Line.mightBeFunctionDefinition()) + if (Line.mightBeFunctionDefinition()) { return Style.SpaceBeforeParensOptions.AfterFunctionDefinitionName || spaceRequiredBeforeParens(Right); - else + } else { return Style.SpaceBeforeParensOptions.AfterFunctionDeclarationName || spaceRequiredBeforeParens(Right); + } } // Lambda if (Line.Type != LT_PreprocessorDirective && Left.is(tok::r_square) && - Left.MatchingParen && Left.MatchingParen->is(TT_LambdaLSquare)) + Left.MatchingParen && Left.MatchingParen->is(TT_LambdaLSquare)) { return Style.SpaceBeforeParensOptions.AfterFunctionDefinitionName || spaceRequiredBeforeParens(Right); + } if (!Left.Previous || Left.Previous->isNot(tok::period)) { - if (Left.isOneOf(tok::kw_try, Keywords.kw___except, tok::kw_catch)) + if (Left.isOneOf(tok::kw_try, Keywords.kw___except, tok::kw_catch)) { return Style.SpaceBeforeParensOptions.AfterControlStatements || spaceRequiredBeforeParens(Right); - if (Left.isOneOf(tok::kw_new, tok::kw_delete)) + } + if (Left.isOneOf(tok::kw_new, tok::kw_delete)) { return ((!Line.MightBeFunctionDecl || !Left.Previous) && Style.SpaceBeforeParens != FormatStyle::SBPO_Never) || spaceRequiredBeforeParens(Right); + } if (Left.is(tok::r_square) && Left.MatchingParen && Left.MatchingParen->Previous && - Left.MatchingParen->Previous->is(tok::kw_delete)) + Left.MatchingParen->Previous->is(tok::kw_delete)) { return (Style.SpaceBeforeParens != FormatStyle::SBPO_Never) || spaceRequiredBeforeParens(Right); + } } // Handle builtins like identifiers. if (Line.Type != LT_PreprocessorDirective && - (Left.Tok.getIdentifierInfo() || Left.is(tok::r_paren))) + (Left.Tok.getIdentifierInfo() || Left.is(tok::r_paren))) { return spaceRequiredBeforeParens(Right); + } return false; } if (Left.is(tok::at) && Right.Tok.getObjCKeywordID() != tok::objc_not_keyword) return false; - if (Right.is(TT_UnaryOperator)) + if (Right.is(TT_UnaryOperator)) { return !Left.isOneOf(tok::l_paren, tok::l_square, tok::at) && (Left.isNot(tok::colon) || Left.isNot(TT_ObjCMethodExpr)); + } if ((Left.isOneOf(tok::identifier, tok::greater, tok::r_square, tok::r_paren) || Left.isSimpleTypeSpecifier()) && Right.is(tok::l_brace) && Right.getNextNonComment() && - Right.isNot(BK_Block)) + Right.isNot(BK_Block)) { return false; + } if (Left.is(tok::period) || Right.is(tok::period)) return false; // u#str, U#str, L#str, u8#str @@ -3462,33 +3618,38 @@ (Left.TokenText == "L" || Left.TokenText == "u" || Left.TokenText == "U" || Left.TokenText == "u8" || Left.TokenText == "LR" || Left.TokenText == "uR" || - Left.TokenText == "UR" || Left.TokenText == "u8R")) + Left.TokenText == "UR" || Left.TokenText == "u8R")) { return false; + } if (Left.is(TT_TemplateCloser) && Left.MatchingParen && Left.MatchingParen->Previous && (Left.MatchingParen->Previous->is(tok::period) || - Left.MatchingParen->Previous->is(tok::coloncolon))) + Left.MatchingParen->Previous->is(tok::coloncolon))) { // Java call to generic function with explicit type: // A.>>DoSomething(); // A::>>DoSomething(); // With a Java 8 method reference. return false; + } if (Left.is(TT_TemplateCloser) && Right.is(tok::l_square)) return false; - if (Left.is(tok::l_brace) && Left.endsSequence(TT_DictLiteral, tok::at)) + if (Left.is(tok::l_brace) && Left.endsSequence(TT_DictLiteral, tok::at)) { // Objective-C dictionary literal -> no space after opening brace. return false; + } if (Right.is(tok::r_brace) && Right.MatchingParen && - Right.MatchingParen->endsSequence(TT_DictLiteral, tok::at)) + Right.MatchingParen->endsSequence(TT_DictLiteral, tok::at)) { // Objective-C dictionary literal -> no space before closing brace. return false; + } if (Right.getType() == TT_TrailingAnnotation && Right.isOneOf(tok::amp, tok::ampamp) && Left.isOneOf(tok::kw_const, tok::kw_volatile) && - (!Right.Next || Right.Next->is(tok::semi))) + (!Right.Next || Right.Next->is(tok::semi))) { // Match const and volatile ref-qualifiers without any additional // qualifiers such as // void Fn() const &; return getTokenReferenceAlignment(Right) != FormatStyle::PAS_Left; + } return true; } @@ -3517,18 +3678,21 @@ return true; // Space between `module :` and `import :`. if (Left.isOneOf(Keywords.kw_module, Keywords.kw_import) && - Right.is(TT_ModulePartitionColon)) + Right.is(TT_ModulePartitionColon)) { return true; + } // No space between import foo:bar but keep a space between import :bar; if (Left.is(tok::identifier) && Right.is(TT_ModulePartitionColon)) return false; // No space between :bar; if (Left.is(TT_ModulePartitionColon) && - Right.isOneOf(tok::identifier, tok::kw_private)) + Right.isOneOf(tok::identifier, tok::kw_private)) { return false; + } if (Left.is(tok::ellipsis) && Right.is(tok::identifier) && - Line.First->is(Keywords.kw_import)) + Line.First->is(Keywords.kw_import)) { return false; + } // Space in __attribute__((attr)) ::type. if (Left.is(TT_AttributeParen) && Right.is(tok::coloncolon)) return true; @@ -3536,20 +3700,24 @@ if (Left.is(tok::kw_operator)) return Right.is(tok::coloncolon); if (Right.is(tok::l_brace) && Right.is(BK_BracedInit) && - !Left.opensScope() && Style.SpaceBeforeCpp11BracedList) + !Left.opensScope() && Style.SpaceBeforeCpp11BracedList) { return true; + } if (Left.is(tok::less) && Left.is(TT_OverloadedOperator) && - Right.is(TT_TemplateOpener)) + Right.is(TT_TemplateOpener)) { return true; + } } else if (Style.Language == FormatStyle::LK_Proto || Style.Language == FormatStyle::LK_TextProto) { if (Right.is(tok::period) && Left.isOneOf(Keywords.kw_optional, Keywords.kw_required, - Keywords.kw_repeated, Keywords.kw_extend)) + Keywords.kw_repeated, Keywords.kw_extend)) { return true; + } if (Right.is(tok::l_paren) && - Left.isOneOf(Keywords.kw_returns, Keywords.kw_option)) + Left.isOneOf(Keywords.kw_returns, Keywords.kw_option)) { return true; + } if (Right.isOneOf(tok::l_brace, tok::less) && Left.is(TT_SelectorName)) return true; // Slashes occur in text protocol extension syntax: [type/type] { ... }. @@ -3557,8 +3725,9 @@ return false; if (Left.MatchingParen && Left.MatchingParen->is(TT_ProtoExtensionLSquare) && - Right.isOneOf(tok::l_brace, tok::less)) + Right.isOneOf(tok::l_brace, tok::less)) { return !Style.Cpp11BracedListStyle; + } // A percent is probably part of a formatting specification, such as %lld. if (Left.is(tok::percent)) return false; @@ -3626,11 +3795,13 @@ return true; // space between keywords and paren e.g. "using (" - if (Right.is(tok::l_paren)) + if (Right.is(tok::l_paren)) { if (Left.isOneOf(tok::kw_using, Keywords.kw_async, Keywords.kw_when, - Keywords.kw_lock)) + Keywords.kw_lock)) { return Style.SpaceBeforeParensOptions.AfterControlStatements || spaceRequiredBeforeParens(Right); + } + } // space between method modifier and opening parenthesis of a tuple return // type @@ -3639,15 +3810,17 @@ Keywords.kw_internal, Keywords.kw_abstract, Keywords.kw_sealed, Keywords.kw_override, Keywords.kw_async, Keywords.kw_unsafe) && - Right.is(tok::l_paren)) + Right.is(tok::l_paren)) { return true; + } } else if (Style.isJavaScript()) { if (Left.is(TT_FatArrow)) return true; // for await ( ... if (Right.is(tok::l_paren) && Left.is(Keywords.kw_await) && Left.Previous && - Left.Previous->is(tok::kw_for)) + Left.Previous->is(tok::kw_for)) { return true; + } if (Left.is(Keywords.kw_async) && Right.is(tok::l_paren) && Right.MatchingParen) { const FormatToken *Next = Right.MatchingParen->getNextNonComment(); @@ -3657,21 +3830,25 @@ return true; } if ((Left.is(TT_TemplateString) && Left.TokenText.endswith("${")) || - (Right.is(TT_TemplateString) && Right.TokenText.startswith("}"))) + (Right.is(TT_TemplateString) && Right.TokenText.startswith("}"))) { return false; + } // In tagged template literals ("html`bar baz`"), there is no space between // the tag identifier and the template string. if (Keywords.IsJavaScriptIdentifier(Left, /* AcceptIdentifierName= */ false) && - Right.is(TT_TemplateString)) + Right.is(TT_TemplateString)) { return false; + } if (Right.is(tok::star) && - Left.isOneOf(Keywords.kw_function, Keywords.kw_yield)) + Left.isOneOf(Keywords.kw_function, Keywords.kw_yield)) { return false; + } if (Right.isOneOf(tok::l_brace, tok::l_square) && Left.isOneOf(Keywords.kw_function, Keywords.kw_yield, - Keywords.kw_extends, Keywords.kw_implements)) + Keywords.kw_extends, Keywords.kw_implements)) { return true; + } if (Right.is(tok::l_paren)) { // JS methods can use some keywords as names (e.g. `delete()`). if (Line.MustBeDeclaration && Left.Tok.getIdentifierInfo()) @@ -3679,12 +3856,14 @@ // Valid JS method names can include keywords, e.g. `foo.delete()` or // `bar.instanceof()`. Recognize call positions by preceding period. if (Left.Previous && Left.Previous->is(tok::period) && - Left.Tok.getIdentifierInfo()) + Left.Tok.getIdentifierInfo()) { return false; + } // Additional unary JavaScript operators that need a space after. if (Left.isOneOf(tok::kw_throw, Keywords.kw_await, Keywords.kw_typeof, - tok::kw_void)) + tok::kw_void)) { return true; + } } // `foo as const;` casts into a const type. if (Left.endsSequence(tok::kw_const, Keywords.kw_as)) @@ -3697,17 +3876,21 @@ (Left.is(Keywords.kw_of) && Left.Previous && (Left.Previous->is(tok::identifier) || Left.Previous->isOneOf(tok::r_square, tok::r_brace)))) && - (!Left.Previous || !Left.Previous->is(tok::period))) + (!Left.Previous || !Left.Previous->is(tok::period))) { return true; + } if (Left.isOneOf(tok::kw_for, Keywords.kw_as) && Left.Previous && - Left.Previous->is(tok::period) && Right.is(tok::l_paren)) + Left.Previous->is(tok::period) && Right.is(tok::l_paren)) { return false; + } if (Left.is(Keywords.kw_as) && - Right.isOneOf(tok::l_square, tok::l_brace, tok::l_paren)) + Right.isOneOf(tok::l_square, tok::l_brace, tok::l_paren)) { return true; + } if (Left.is(tok::kw_default) && Left.Previous && - Left.Previous->is(tok::kw_export)) + Left.Previous->is(tok::kw_export)) { return true; + } if (Left.is(Keywords.kw_is) && Right.is(tok::l_brace)) return true; if (Right.isOneOf(TT_JsTypeColon, TT_JsTypeOptionalQuestion)) @@ -3715,53 +3898,61 @@ if (Left.is(TT_JsTypeOperator) || Right.is(TT_JsTypeOperator)) return false; if ((Left.is(tok::l_brace) || Right.is(tok::r_brace)) && - Line.First->isOneOf(Keywords.kw_import, tok::kw_export)) + Line.First->isOneOf(Keywords.kw_import, tok::kw_export)) { return false; + } if (Left.is(tok::ellipsis)) return false; if (Left.is(TT_TemplateCloser) && !Right.isOneOf(tok::equal, tok::l_brace, tok::comma, tok::l_square, - Keywords.kw_implements, Keywords.kw_extends)) + Keywords.kw_implements, Keywords.kw_extends)) { // Type assertions ('expr') are not followed by whitespace. Other // locations that should have whitespace following are identified by the // above set of follower tokens. return false; + } if (Right.is(TT_NonNullAssertion)) return false; if (Left.is(TT_NonNullAssertion) && - Right.isOneOf(Keywords.kw_as, Keywords.kw_in)) + Right.isOneOf(Keywords.kw_as, Keywords.kw_in)) { return true; // "x! as string", "x! in y" + } } else if (Style.Language == FormatStyle::LK_Java) { if (Left.is(tok::r_square) && Right.is(tok::l_brace)) return true; - if (Left.is(Keywords.kw_synchronized) && Right.is(tok::l_paren)) + if (Left.is(Keywords.kw_synchronized) && Right.is(tok::l_paren)) { return Style.SpaceBeforeParensOptions.AfterControlStatements || spaceRequiredBeforeParens(Right); + } if ((Left.isOneOf(tok::kw_static, tok::kw_public, tok::kw_private, tok::kw_protected) || Left.isOneOf(Keywords.kw_final, Keywords.kw_abstract, Keywords.kw_native)) && - Right.is(TT_TemplateOpener)) + Right.is(TT_TemplateOpener)) { return true; + } } if (Left.is(TT_ImplicitStringLiteral)) return Right.hasWhitespaceBefore(); if (Line.Type == LT_ObjCMethodDecl) { if (Left.is(TT_ObjCMethodSpecifier)) return true; - if (Left.is(tok::r_paren) && canBeObjCSelectorComponent(Right)) + if (Left.is(tok::r_paren) && canBeObjCSelectorComponent(Right)) { // Don't space between ')' and or ')' and 'new'. 'new' is not a // keyword in Objective-C, and '+ (instancetype)new;' is a standard class // method declaration. return false; + } } if (Line.Type == LT_ObjCProperty && - (Right.is(tok::equal) || Left.is(tok::equal))) + (Right.is(tok::equal) || Left.is(tok::equal))) { return false; + } if (Right.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow) || - Left.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow)) + Left.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow)) { return true; + } if (Left.is(tok::comma) && !Right.is(TT_OverloadedOperatorLParen)) return true; if (Right.is(tok::comma)) @@ -3773,11 +3964,13 @@ if (Right.is(TT_InheritanceColon) && !Style.SpaceBeforeInheritanceColon) return false; if (Right.is(TT_RangeBasedForLoopColon) && - !Style.SpaceBeforeRangeBasedForLoopColon) + !Style.SpaceBeforeRangeBasedForLoopColon) { return false; - if (Left.is(TT_BitFieldColon)) + } + if (Left.is(TT_BitFieldColon)) { return Style.BitFieldColonSpacing == FormatStyle::BFCS_Both || Style.BitFieldColonSpacing == FormatStyle::BFCS_After; + } if (Right.is(tok::colon)) { if (Line.First->isOneOf(tok::kw_default, tok::kw_case)) return Style.SpaceBeforeCaseColon; @@ -3796,17 +3989,19 @@ return false; if (Right.is(TT_CSharpNamedArgumentColon)) return false; - if (Right.is(TT_BitFieldColon)) + if (Right.is(TT_BitFieldColon)) { return Style.BitFieldColonSpacing == FormatStyle::BFCS_Both || Style.BitFieldColonSpacing == FormatStyle::BFCS_Before; + } return true; } // Do not merge "- -" into "--". if ((Left.isOneOf(tok::minus, tok::minusminus) && Right.isOneOf(tok::minus, tok::minusminus)) || (Left.isOneOf(tok::plus, tok::plusplus) && - Right.isOneOf(tok::plus, tok::plusplus))) + Right.isOneOf(tok::plus, tok::plusplus))) { return true; + } if (Left.is(TT_UnaryOperator)) { if (!Right.is(tok::l_paren)) { // The alternative operators for ~ and ! are "compl" and "not". @@ -3827,9 +4022,10 @@ // If the next token is a binary operator or a selector name, we have // incorrectly classified the parenthesis as a cast. FIXME: Detect correctly. - if (Left.is(TT_CastRParen)) + if (Left.is(TT_CastRParen)) { return Style.SpaceAfterCStyleCast || Right.isOneOf(TT_BinaryOperator, TT_SelectorName); + } auto ShouldAddSpacesInAngles = [this, &Right]() { if (this->Style.SpacesInAngles == FormatStyle::SIAS_Always) @@ -3841,29 +4037,34 @@ if (Left.is(tok::greater) && Right.is(tok::greater)) { if (Style.Language == FormatStyle::LK_TextProto || - (Style.Language == FormatStyle::LK_Proto && Left.is(TT_DictLiteral))) + (Style.Language == FormatStyle::LK_Proto && Left.is(TT_DictLiteral))) { return !Style.Cpp11BracedListStyle; + } return Right.is(TT_TemplateCloser) && Left.is(TT_TemplateCloser) && ((Style.Standard < FormatStyle::LS_Cpp11) || ShouldAddSpacesInAngles()); } if (Right.isOneOf(tok::arrow, tok::arrowstar, tok::periodstar) || Left.isOneOf(tok::arrow, tok::period, tok::arrowstar, tok::periodstar) || - (Right.is(tok::period) && Right.isNot(TT_DesignatedInitializerPeriod))) + (Right.is(tok::period) && Right.isNot(TT_DesignatedInitializerPeriod))) { return false; + } if (!Style.SpaceBeforeAssignmentOperators && Left.isNot(TT_TemplateCloser) && - Right.getPrecedence() == prec::Assignment) + Right.getPrecedence() == prec::Assignment) { return false; + } if (Style.Language == FormatStyle::LK_Java && Right.is(tok::coloncolon) && - (Left.is(tok::identifier) || Left.is(tok::kw_this))) + (Left.is(tok::identifier) || Left.is(tok::kw_this))) { return false; - if (Right.is(tok::coloncolon) && Left.is(tok::identifier)) + } + if (Right.is(tok::coloncolon) && Left.is(tok::identifier)) { // Generally don't remove existing spaces between an identifier and "::". // The identifier might actually be a macro name such as ALWAYS_INLINE. If // this turns out to be too lenient, add analysis of the identifier itself. return Right.hasWhitespaceBefore(); + } if (Right.is(tok::coloncolon) && - !Left.isOneOf(tok::l_brace, tok::comment, tok::l_paren)) + !Left.isOneOf(tok::l_brace, tok::comment, tok::l_paren)) { // Put a space between < and :: in vector< ::std::string > return (Left.is(TT_TemplateOpener) && ((Style.Standard < FormatStyle::LS_Cpp11) || @@ -3872,26 +4073,33 @@ tok::kw___super, TT_TemplateOpener, TT_TemplateCloser)) || (Left.is(tok::l_paren) && Style.SpacesInParentheses); + } if ((Left.is(TT_TemplateOpener)) != (Right.is(TT_TemplateCloser))) return ShouldAddSpacesInAngles(); // Space before TT_StructuredBindingLSquare. - if (Right.is(TT_StructuredBindingLSquare)) + if (Right.is(TT_StructuredBindingLSquare)) { return !Left.isOneOf(tok::amp, tok::ampamp) || getTokenReferenceAlignment(Left) != FormatStyle::PAS_Right; + } // Space before & or && following a TT_StructuredBindingLSquare. if (Right.Next && Right.Next->is(TT_StructuredBindingLSquare) && - Right.isOneOf(tok::amp, tok::ampamp)) + Right.isOneOf(tok::amp, tok::ampamp)) { return getTokenReferenceAlignment(Right) != FormatStyle::PAS_Left; + } if ((Right.is(TT_BinaryOperator) && !Left.is(tok::l_paren)) || (Left.isOneOf(TT_BinaryOperator, TT_ConditionalExpr) && - !Right.is(tok::r_paren))) + !Right.is(tok::r_paren))) { return true; + } if (Right.is(TT_TemplateOpener) && Left.is(tok::r_paren) && - Left.MatchingParen && Left.MatchingParen->is(TT_OverloadedOperatorLParen)) + Left.MatchingParen && + Left.MatchingParen->is(TT_OverloadedOperatorLParen)) { return false; + } if (Right.is(tok::less) && Left.isNot(tok::l_paren) && - Line.startsWith(tok::hash)) + Line.startsWith(tok::hash)) { return true; + } if (Right.is(TT_TrailingUnaryOperator)) return false; if (Left.is(TT_RegexLiteral)) @@ -3940,51 +4148,59 @@ if (Style.isCSharp()) { if (Left.is(TT_FatArrow) && Right.is(tok::l_brace) && - Style.BraceWrapping.AfterFunction) + Style.BraceWrapping.AfterFunction) { return true; + } if (Right.is(TT_CSharpNamedArgumentColon) || - Left.is(TT_CSharpNamedArgumentColon)) + Left.is(TT_CSharpNamedArgumentColon)) { return false; + } if (Right.is(TT_CSharpGenericTypeConstraint)) return true; if (Right.Next && Right.Next->is(TT_FatArrow) && (Right.is(tok::numeric_constant) || - (Right.is(tok::identifier) && Right.TokenText == "_"))) + (Right.is(tok::identifier) && Right.TokenText == "_"))) { return true; + } // Break after C# [...] and before public/protected/private/internal. if (Left.is(TT_AttributeSquare) && Left.is(tok::r_square) && (Right.isAccessSpecifier(/*ColonRequired=*/false) || - Right.is(Keywords.kw_internal))) + Right.is(Keywords.kw_internal))) { return true; + } // Break between ] and [ but only when there are really 2 attributes. if (Left.is(TT_AttributeSquare) && Right.is(TT_AttributeSquare) && - Left.is(tok::r_square) && Right.is(tok::l_square)) + Left.is(tok::r_square) && Right.is(tok::l_square)) { return true; + } } else if (Style.isJavaScript()) { // FIXME: This might apply to other languages and token kinds. if (Right.is(tok::string_literal) && Left.is(tok::plus) && Left.Previous && - Left.Previous->is(tok::string_literal)) + Left.Previous->is(tok::string_literal)) { return true; + } if (Left.is(TT_DictLiteral) && Left.is(tok::l_brace) && Line.Level == 0 && Left.Previous && Left.Previous->is(tok::equal) && Line.First->isOneOf(tok::identifier, Keywords.kw_import, tok::kw_export, tok::kw_const) && // kw_var/kw_let are pseudo-tokens that are tok::identifier, so match // above. - !Line.First->isOneOf(Keywords.kw_var, Keywords.kw_let)) + !Line.First->isOneOf(Keywords.kw_var, Keywords.kw_let)) { // Object literals on the top level of a file are treated as "enum-style". // Each key/value pair is put on a separate line, instead of bin-packing. return true; + } if (Left.is(tok::l_brace) && Line.Level == 0 && (Line.startsWith(tok::kw_enum) || Line.startsWith(tok::kw_const, tok::kw_enum) || Line.startsWith(tok::kw_export, tok::kw_enum) || - Line.startsWith(tok::kw_export, tok::kw_const, tok::kw_enum))) + Line.startsWith(tok::kw_export, tok::kw_const, tok::kw_enum))) { // JavaScript top-level enum key/value pairs are put on separate lines // instead of bin-packing. return true; + } if (Right.is(tok::r_brace) && Left.is(tok::l_brace) && Left.Previous && Left.Previous->is(TT_FatArrow)) { // JS arrow function (=> {...}). @@ -4005,17 +4221,19 @@ } if (Right.is(tok::r_brace) && Left.is(tok::l_brace) && - !Left.Children.empty()) + !Left.Children.empty()) { // Support AllowShortFunctionsOnASingleLine for JavaScript. return Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_None || Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_Empty || (Left.NestingLevel == 0 && Line.Level == 0 && Style.AllowShortFunctionsOnASingleLine & FormatStyle::SFS_InlineOnly); + } } else if (Style.Language == FormatStyle::LK_Java) { if (Right.is(tok::plus) && Left.is(tok::string_literal) && Right.Next && - Right.Next->is(tok::string_literal)) + Right.Next->is(tok::string_literal)) { return true; + } } else if (Style.Language == FormatStyle::LK_Cpp || Style.Language == FormatStyle::LK_ObjC || Style.Language == FormatStyle::LK_Proto || @@ -4036,8 +4254,9 @@ // [ // ] if (Left.is(TT_ArrayInitializerLSquare) && Left.is(tok::l_square) && - !Right.is(tok::r_square)) + !Right.is(tok::r_square)) { return true; + } // Always break after successive entries. // 1, // 2 @@ -4053,28 +4272,33 @@ const FormatToken *BeforeClosingBrace = nullptr; if ((Left.isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) || (Style.isJavaScript() && Left.is(tok::l_paren))) && - Left.isNot(BK_Block) && Left.MatchingParen) + Left.isNot(BK_Block) && Left.MatchingParen) { BeforeClosingBrace = Left.MatchingParen->Previous; - else if (Right.MatchingParen && - (Right.MatchingParen->isOneOf(tok::l_brace, - TT_ArrayInitializerLSquare) || - (Style.isJavaScript() && Right.MatchingParen->is(tok::l_paren)))) + } else if (Right.MatchingParen && + (Right.MatchingParen->isOneOf(tok::l_brace, + TT_ArrayInitializerLSquare) || + (Style.isJavaScript() && + Right.MatchingParen->is(tok::l_paren)))) { BeforeClosingBrace = &Left; + } if (BeforeClosingBrace && (BeforeClosingBrace->is(tok::comma) || - BeforeClosingBrace->isTrailingComment())) + BeforeClosingBrace->isTrailingComment())) { return true; + } } - if (Right.is(tok::comment)) + if (Right.is(tok::comment)) { return Left.isNot(BK_BracedInit) && Left.isNot(TT_CtorInitializerColon) && (Right.NewlinesBefore > 0 && Right.HasUnescapedNewline); + } if (Left.isTrailingComment()) return true; if (Left.IsUnterminatedLiteral) return true; if (Right.is(tok::lessless) && Right.Next && Left.is(tok::string_literal) && - Right.Next->is(tok::string_literal)) + Right.Next->is(tok::string_literal)) { return true; + } if (Right.is(TT_RequiresClause)) { switch (Style.RequiresClausePosition) { case FormatStyle::RCPS_OwnLine: @@ -4105,29 +4329,36 @@ } if (Style.PackConstructorInitializers == FormatStyle::PCIS_Never) { if (Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeColon && - (Left.is(TT_CtorInitializerComma) || Right.is(TT_CtorInitializerColon))) + (Left.is(TT_CtorInitializerComma) || + Right.is(TT_CtorInitializerColon))) { return true; + } if (Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon && - Left.isOneOf(TT_CtorInitializerColon, TT_CtorInitializerComma)) + Left.isOneOf(TT_CtorInitializerColon, TT_CtorInitializerComma)) { return true; + } } if (Style.PackConstructorInitializers < FormatStyle::PCIS_CurrentLine && Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma && - Right.isOneOf(TT_CtorInitializerComma, TT_CtorInitializerColon)) + Right.isOneOf(TT_CtorInitializerComma, TT_CtorInitializerColon)) { return true; + } // Break only if we have multiple inheritance. if (Style.BreakInheritanceList == FormatStyle::BILS_BeforeComma && - Right.is(TT_InheritanceComma)) + Right.is(TT_InheritanceComma)) { return true; + } if (Style.BreakInheritanceList == FormatStyle::BILS_AfterComma && - Left.is(TT_InheritanceComma)) + Left.is(TT_InheritanceComma)) { return true; - if (Right.is(tok::string_literal) && Right.TokenText.startswith("R\"")) + } + if (Right.is(tok::string_literal) && Right.TokenText.startswith("R\"")) { // Multiline raw string literals are special wrt. line breaks. The author // has made a deliberate choice and might have aligned the contents of the // string literal accordingly. Thus, we try keep existing line breaks. return Right.IsMultiline && Right.NewlinesBefore > 0; + } if ((Left.is(tok::l_brace) || (Left.is(tok::less) && Left.Previous && Left.Previous->is(tok::equal))) && Right.NestingLevel == 1 && Style.Language == FormatStyle::LK_Proto) { @@ -4147,28 +4378,32 @@ if (Style.BraceWrapping.AfterEnum) { if (Line.startsWith(tok::kw_enum) || - Line.startsWith(tok::kw_typedef, tok::kw_enum)) + Line.startsWith(tok::kw_typedef, tok::kw_enum)) { return true; + } // Ensure BraceWrapping for `public enum A {`. if (AccessSpecifier && FirstNonComment->Next && - FirstNonComment->Next->is(tok::kw_enum)) + FirstNonComment->Next->is(tok::kw_enum)) { return true; + } } // Ensure BraceWrapping for `public interface A {`. if (Style.BraceWrapping.AfterClass && ((AccessSpecifier && FirstNonComment->Next && FirstNonComment->Next->is(Keywords.kw_interface)) || - Line.startsWith(Keywords.kw_interface))) + Line.startsWith(Keywords.kw_interface))) { return true; + } return (Line.startsWith(tok::kw_class) && Style.BraceWrapping.AfterClass) || (Line.startsWith(tok::kw_struct) && Style.BraceWrapping.AfterStruct); } if (Left.is(TT_ObjCBlockLBrace) && - Style.AllowShortBlocksOnASingleLine == FormatStyle::SBS_Never) + Style.AllowShortBlocksOnASingleLine == FormatStyle::SBS_Never) { return true; + } // Ensure wrapping after __attribute__((XX)) and @interface etc. if (Left.is(TT_AttributeParen) && Right.is(TT_ObjCDecl)) @@ -4176,26 +4411,30 @@ if (Left.is(TT_LambdaLBrace)) { if (IsFunctionArgument(Left) && - Style.AllowShortLambdasOnASingleLine == FormatStyle::SLS_Inline) + Style.AllowShortLambdasOnASingleLine == FormatStyle::SLS_Inline) { return false; + } if (Style.AllowShortLambdasOnASingleLine == FormatStyle::SLS_None || Style.AllowShortLambdasOnASingleLine == FormatStyle::SLS_Inline || (!Left.Children.empty() && - Style.AllowShortLambdasOnASingleLine == FormatStyle::SLS_Empty)) + Style.AllowShortLambdasOnASingleLine == FormatStyle::SLS_Empty)) { return true; + } } if (Style.BraceWrapping.BeforeLambdaBody && Right.is(TT_LambdaLBrace) && - Left.isOneOf(tok::star, tok::amp, tok::ampamp, TT_TemplateCloser)) + Left.isOneOf(tok::star, tok::amp, tok::ampamp, TT_TemplateCloser)) { return true; + } // Put multiple Java annotation on a new line. if ((Style.Language == FormatStyle::LK_Java || Style.isJavaScript()) && Left.is(TT_LeadingJavaAnnotation) && Right.isNot(TT_LeadingJavaAnnotation) && Right.isNot(tok::l_paren) && - (Line.Last->is(tok::l_brace) || Style.BreakAfterJavaFieldAnnotations)) + (Line.Last->is(tok::l_brace) || Style.BreakAfterJavaFieldAnnotations)) { return true; + } if (Right.is(TT_ProtoExtensionLSquare)) return true; @@ -4318,8 +4557,9 @@ // Language-specific stuff. if (Style.isCSharp()) { if (Left.isOneOf(TT_CSharpNamedArgumentColon, TT_AttributeColon) || - Right.isOneOf(TT_CSharpNamedArgumentColon, TT_AttributeColon)) + Right.isOneOf(TT_CSharpNamedArgumentColon, TT_AttributeColon)) { return false; + } // Only break after commas for generic type constraints. if (Line.First->is(TT_CSharpGenericTypeConstraint)) return Left.is(TT_CSharpGenericTypeConstraintComma); @@ -4328,11 +4568,13 @@ return false; } else if (Style.Language == FormatStyle::LK_Java) { if (Left.isOneOf(Keywords.kw_throws, Keywords.kw_extends, - Keywords.kw_implements)) + Keywords.kw_implements)) { return false; + } if (Right.isOneOf(Keywords.kw_throws, Keywords.kw_extends, - Keywords.kw_implements)) + Keywords.kw_implements)) { return true; + } } else if (Style.isJavaScript()) { const FormatToken *NonComment = Right.getPreviousNonComment(); if (NonComment && @@ -4342,16 +4584,19 @@ tok::kw_static, tok::kw_public, tok::kw_private, tok::kw_protected, Keywords.kw_readonly, Keywords.kw_override, Keywords.kw_abstract, Keywords.kw_get, Keywords.kw_set, Keywords.kw_async, - Keywords.kw_await)) + Keywords.kw_await)) { return false; // Otherwise automatic semicolon insertion would trigger. + } if (Right.NestingLevel == 0 && (Left.Tok.getIdentifierInfo() || Left.isOneOf(tok::r_square, tok::r_paren)) && - Right.isOneOf(tok::l_square, tok::l_paren)) + Right.isOneOf(tok::l_square, tok::l_paren)) { return false; // Otherwise automatic semicolon insertion would trigger. + } if (NonComment && NonComment->is(tok::identifier) && - NonComment->TokenText == "asserts") + NonComment->TokenText == "asserts") { return false; + } if (Left.is(TT_FatArrow) && Right.is(tok::l_brace)) return false; if (Left.is(TT_JsTypeColon)) @@ -4394,13 +4639,15 @@ Right.isOneOf(Keywords.kw_module, tok::kw_namespace, Keywords.kw_function, tok::kw_class, tok::kw_enum, Keywords.kw_interface, Keywords.kw_type, Keywords.kw_var, - Keywords.kw_let, tok::kw_const)) + Keywords.kw_let, tok::kw_const)) { // See grammar for 'declare' statements at: // https://github.com/Microsoft/TypeScript/blob/main/doc/spec-ARCHIVED.md#A.10 return false; + } if (Left.isOneOf(Keywords.kw_module, tok::kw_namespace) && - Right.isOneOf(tok::identifier, tok::string_literal)) + Right.isOneOf(tok::identifier, tok::string_literal)) { return false; // must not break in "module foo { ...}" + } if (Right.is(TT_TemplateString) && Right.closesScope()) return false; // Don't split tagged template literal so there is a break between the tag @@ -4417,17 +4664,19 @@ return false; if (Left.isOneOf(TT_JavaAnnotation, TT_LeadingJavaAnnotation)) return !Right.is(tok::l_paren); - if (Right.is(TT_PointerOrReference)) + if (Right.is(TT_PointerOrReference)) { return Line.IsMultiVariableDeclStmt || (getTokenPointerOrReferenceAlignment(Right) == FormatStyle::PAS_Right && (!Right.Next || Right.Next->isNot(TT_FunctionDeclarationName))); + } if (Right.isOneOf(TT_StartOfName, TT_FunctionDeclarationName) || - Right.is(tok::kw_operator)) + Right.is(tok::kw_operator)) { return true; + } if (Left.is(TT_PointerOrReference)) return false; - if (Right.isTrailingComment()) + if (Right.isTrailingComment()) { // We rely on MustBreakBefore being set correctly here as we should not // change the "binding" behavior of a comment. // The first comment in a braced lists is always interpreted as belonging to @@ -4436,6 +4685,7 @@ return Left.is(BK_BracedInit) || (Left.is(TT_CtorInitializerColon) && Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon); + } if (Left.is(tok::question) && Right.is(tok::colon)) return false; if (Right.is(TT_ConditionalExpr) || Right.is(tok::question)) @@ -4447,12 +4697,14 @@ if (Right.is(TT_InheritanceColon)) return Style.BreakInheritanceList != FormatStyle::BILS_AfterColon; if (Right.is(TT_ObjCMethodExpr) && !Right.is(tok::r_square) && - Left.isNot(TT_SelectorName)) + Left.isNot(TT_SelectorName)) { return true; + } if (Right.is(tok::colon) && - !Right.isOneOf(TT_CtorInitializerColon, TT_InlineASMColon)) + !Right.isOneOf(TT_CtorInitializerColon, TT_InlineASMColon)) { return false; + } if (Left.is(tok::colon) && Left.isOneOf(TT_DictLiteral, TT_ObjCMethodExpr)) { if (Style.Language == FormatStyle::LK_Proto || Style.Language == FormatStyle::LK_TextProto) { @@ -4484,17 +4736,20 @@ // repeated: [ ... ] if (((Right.is(tok::l_brace) || Right.is(tok::less)) && Right.is(TT_DictLiteral)) || - Right.is(TT_ArrayInitializerLSquare)) + Right.is(TT_ArrayInitializerLSquare)) { return false; + } } return true; } if (Right.is(tok::r_square) && Right.MatchingParen && - Right.MatchingParen->is(TT_ProtoExtensionLSquare)) + Right.MatchingParen->is(TT_ProtoExtensionLSquare)) { return false; + } if (Right.is(TT_SelectorName) || (Right.is(tok::identifier) && Right.Next && - Right.Next->is(TT_ObjCMethodExpr))) + Right.Next->is(TT_ObjCMethodExpr))) { return Left.isNot(tok::period); // FIXME: Properly parse ObjC calls. + } if (Left.is(tok::r_paren) && Line.Type == LT_ObjCProperty) return true; if (Right.is(tok::kw_concept)) @@ -4506,8 +4761,9 @@ if (Left.ClosesRequiresClause) return true; if (Right.isOneOf(TT_RangeBasedForLoopColon, TT_OverloadedOperatorLParen, - TT_OverloadedOperator)) + TT_OverloadedOperator)) { return false; + } if (Left.is(TT_RangeBasedForLoopColon)) return true; if (Right.is(TT_RangeBasedForLoopColon)) @@ -4515,36 +4771,44 @@ if (Left.is(TT_TemplateCloser) && Right.is(TT_TemplateOpener)) return true; if ((Left.is(tok::greater) && Right.is(tok::greater)) || - (Left.is(tok::less) && Right.is(tok::less))) + (Left.is(tok::less) && Right.is(tok::less))) { return false; + } if (Right.is(TT_BinaryOperator) && Style.BreakBeforeBinaryOperators != FormatStyle::BOS_None && (Style.BreakBeforeBinaryOperators == FormatStyle::BOS_All || - Right.getPrecedence() != prec::Assignment)) + Right.getPrecedence() != prec::Assignment)) { return true; + } if (Left.isOneOf(TT_TemplateCloser, TT_UnaryOperator) || - Left.is(tok::kw_operator)) + Left.is(tok::kw_operator)) { return false; + } if (Left.is(tok::equal) && !Right.isOneOf(tok::kw_default, tok::kw_delete) && - Line.Type == LT_VirtualFunctionDecl && Left.NestingLevel == 0) + Line.Type == LT_VirtualFunctionDecl && Left.NestingLevel == 0) { return false; + } if (Left.is(tok::equal) && Right.is(tok::l_brace) && - !Style.Cpp11BracedListStyle) + !Style.Cpp11BracedListStyle) { return false; + } if (Left.is(tok::l_paren) && - Left.isOneOf(TT_AttributeParen, TT_TypeDeclarationParen)) + Left.isOneOf(TT_AttributeParen, TT_TypeDeclarationParen)) { return false; + } if (Left.is(tok::l_paren) && Left.Previous && - (Left.Previous->isOneOf(TT_BinaryOperator, TT_CastRParen))) + (Left.Previous->isOneOf(TT_BinaryOperator, TT_CastRParen))) { return false; + } if (Right.is(TT_ImplicitStringLiteral)) return false; if (Right.is(TT_TemplateCloser)) return false; if (Right.is(tok::r_square) && Right.MatchingParen && - Right.MatchingParen->is(TT_LambdaLSquare)) + Right.MatchingParen->is(TT_LambdaLSquare)) { return false; + } // We only break before r_brace if there was a corresponding break before // the l_brace, which is tracked by BreakBeforeClosingBrace. @@ -4554,21 +4818,24 @@ // We only break before r_paren if we're in a block indented context. if (Right.is(tok::r_paren)) { if (Style.AlignAfterOpenBracket != FormatStyle::BAS_BlockIndent || - !Right.MatchingParen) + !Right.MatchingParen) { return false; + } const FormatToken *Previous = Right.MatchingParen->Previous; return !(Previous && (Previous->is(tok::kw_for) || Previous->isIf())); } // Allow breaking after a trailing annotation, e.g. after a method // declaration. - if (Left.is(TT_TrailingAnnotation)) + if (Left.is(TT_TrailingAnnotation)) { return !Right.isOneOf(tok::l_brace, tok::semi, tok::equal, tok::l_paren, tok::less, tok::coloncolon); + } if (Right.is(tok::kw___attribute) || - (Right.is(tok::l_square) && Right.is(TT_AttributeSquare))) + (Right.is(tok::l_square) && Right.is(TT_AttributeSquare))) { return !Left.is(TT_AttributeSquare); + } if (Left.is(tok::identifier) && Right.is(tok::string_literal)) return true; @@ -4581,17 +4848,21 @@ if (Right.is(TT_CtorInitializerColon)) return Style.BreakConstructorInitializers != FormatStyle::BCIS_AfterColon; if (Left.is(TT_CtorInitializerComma) && - Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma) + Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma) { return false; + } if (Right.is(TT_CtorInitializerComma) && - Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma) + Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma) { return true; + } if (Left.is(TT_InheritanceComma) && - Style.BreakInheritanceList == FormatStyle::BILS_BeforeComma) + Style.BreakInheritanceList == FormatStyle::BILS_BeforeComma) { return false; + } if (Right.is(TT_InheritanceComma) && - Style.BreakInheritanceList == FormatStyle::BILS_BeforeComma) + Style.BreakInheritanceList == FormatStyle::BILS_BeforeComma) { return true; + } if (Left.is(TT_ArrayInitializerLSquare)) return true; if (Right.is(tok::kw_typename) && Left.isNot(tok::kw_const)) @@ -4600,11 +4871,13 @@ !Left.isOneOf(tok::arrowstar, tok::lessless) && Style.BreakBeforeBinaryOperators != FormatStyle::BOS_All && (Style.BreakBeforeBinaryOperators == FormatStyle::BOS_None || - Left.getPrecedence() == prec::Assignment)) + Left.getPrecedence() == prec::Assignment)) { return true; + } if ((Left.is(TT_AttributeSquare) && Right.is(tok::l_square)) || - (Left.is(tok::r_square) && Right.is(TT_AttributeSquare))) + (Left.is(tok::r_square) && Right.is(TT_AttributeSquare))) { return false; + } auto ShortLambdaOption = Style.AllowShortLambdasOnASingleLine; if (Style.BraceWrapping.BeforeLambdaBody && Right.is(TT_LambdaLBrace)) { diff --git a/clang/lib/Format/UnwrappedLineFormatter.cpp b/clang/lib/Format/UnwrappedLineFormatter.cpp --- a/clang/lib/Format/UnwrappedLineFormatter.cpp +++ b/clang/lib/Format/UnwrappedLineFormatter.cpp @@ -92,8 +92,9 @@ if (static_cast(LevelIndent) - Offset >= 0) LevelIndent -= Offset; if ((!Line.First->is(tok::comment) || IndentForLevel[Line.Level] == -1) && - !Line.InPPDirective) + !Line.InPPDirective) { IndentForLevel[Line.Level] = LevelIndent; + } } private: @@ -103,25 +104,30 @@ /// characters to the left from their level. int getIndentOffset(const FormatToken &RootToken) { if (Style.Language == FormatStyle::LK_Java || Style.isJavaScript() || - Style.isCSharp()) + Style.isCSharp()) { return 0; + } auto IsAccessModifier = [this, &RootToken]() { - if (RootToken.isAccessSpecifier(Style.isCpp())) + if (RootToken.isAccessSpecifier(Style.isCpp())) { return true; - else if (RootToken.isObjCAccessSpecifier()) + } else if (RootToken.isObjCAccessSpecifier()) { return true; + } // Handle Qt signals. else if ((RootToken.isOneOf(Keywords.kw_signals, Keywords.kw_qsignals) && - RootToken.Next && RootToken.Next->is(tok::colon))) + RootToken.Next && RootToken.Next->is(tok::colon))) { return true; - else if (RootToken.Next && - RootToken.Next->isOneOf(Keywords.kw_slots, Keywords.kw_qslots) && - RootToken.Next->Next && RootToken.Next->Next->is(tok::colon)) + } else if (RootToken.Next && + RootToken.Next->isOneOf(Keywords.kw_slots, + Keywords.kw_qslots) && + RootToken.Next->Next && RootToken.Next->Next->is(tok::colon)) { return true; + } // Handle malformed access specifier e.g. 'private' without trailing ':'. - else if (!RootToken.Next && RootToken.isAccessSpecifier(false)) + else if (!RootToken.Next && RootToken.isAccessSpecifier(false)) { return true; + } return false; }; @@ -205,12 +211,13 @@ const AnnotatedLine *Current = *Next; IndentTracker.nextLine(*Current); unsigned MergedLines = tryFitMultipleLinesInOne(IndentTracker, Next, End); - if (MergedLines > 0 && Style.ColumnLimit == 0) + if (MergedLines > 0 && Style.ColumnLimit == 0) { // Disallow line merging if there is a break at the start of one of the // input lines. for (unsigned i = 0; i < MergedLines; ++i) if (Next[i + 1]->First->NewlinesBefore > 0) MergedLines = 0; + } if (!DryRun) for (unsigned i = 0; i < MergedLines; ++i) join(*Next[0], *Next[i + 1]); @@ -237,8 +244,9 @@ if (NextLine.Type == LT_Invalid || NextLine.First->MustBreakBefore) return 0; if (TheLine->InPPDirective && - (!NextLine.InPPDirective || NextLine.First->HasUnescapedNewline)) + (!NextLine.InPPDirective || NextLine.First->HasUnescapedNewline)) { return 0; + } if (Style.ColumnLimit > 0 && Indent > Style.ColumnLimit) return 0; @@ -254,8 +262,9 @@ if (TheLine->Last->is(TT_FunctionLBrace) && TheLine->First == TheLine->Last && !Style.BraceWrapping.SplitEmptyFunction && - NextLine.First->is(tok::r_brace)) + NextLine.First->is(tok::r_brace)) { return tryMergeSimpleBlock(I, E, Limit); + } const auto *PreviousLine = I != AnnotatedLines.begin() ? I[-1] : nullptr; // Handle empty record blocks where the brace has already been wrapped. @@ -267,22 +276,25 @@ if (Tok && Tok->is(tok::comment)) Tok = Tok->getNextNonComment(); - if (Tok && Tok->getNamespaceToken()) + if (Tok && Tok->getNamespaceToken()) { return !Style.BraceWrapping.SplitEmptyNamespace && EmptyBlock ? tryMergeSimpleBlock(I, E, Limit) : 0; + } if (Tok && Tok->is(tok::kw_typedef)) Tok = Tok->getNextNonComment(); if (Tok && Tok->isOneOf(tok::kw_class, tok::kw_struct, tok::kw_union, - tok::kw_extern, Keywords.kw_interface)) + tok::kw_extern, Keywords.kw_interface)) { return !Style.BraceWrapping.SplitEmptyRecord && EmptyBlock ? tryMergeSimpleBlock(I, E, Limit) : 0; + } if (Tok && Tok->is(tok::kw_template) && - Style.BraceWrapping.SplitEmptyRecord && EmptyBlock) + Style.BraceWrapping.SplitEmptyRecord && EmptyBlock) { return 0; + } } auto ShouldMergeShortFunctions = [this, &I, &NextLine, PreviousLine, @@ -290,8 +302,9 @@ if (Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_All) return true; if (Style.AllowShortFunctionsOnASingleLine >= FormatStyle::SFS_Empty && - NextLine.First->is(tok::r_brace)) + NextLine.First->is(tok::r_brace)) { return true; + } if (Style.AllowShortFunctionsOnASingleLine & FormatStyle::SFS_InlineOnly) { @@ -439,8 +452,9 @@ tok::ObjCKeywordKind kwId = PreviousLine->First->Next->Tok.getObjCKeywordID(); if (kwId == tok::objc_autoreleasepool || - kwId == tok::objc_synchronized) + kwId == tok::objc_synchronized) { return 0; + } } break; @@ -469,8 +483,9 @@ const FormatToken *PreviousPrevious = Previous->getPreviousNonComment(); if (PreviousPrevious && - PreviousPrevious->isOneOf(tok::kw_class, tok::kw_struct)) + PreviousPrevious->isOneOf(tok::kw_class, tok::kw_struct)) { return 0; + } } } } @@ -552,8 +567,9 @@ : 0; } if (TheLine->InPPDirective && - (TheLine->First->HasUnescapedNewline || TheLine->First->IsFirst)) + (TheLine->First->HasUnescapedNewline || TheLine->First->IsFirst)) { return tryMergeSimplePPDirective(I, E, Limit); + } return 0; } @@ -578,16 +594,19 @@ if (Style.BraceWrapping.AfterControlStatement == FormatStyle::BWACS_Always && I[1]->First->is(tok::l_brace) && - Style.AllowShortBlocksOnASingleLine == FormatStyle::SBS_Never) + Style.AllowShortBlocksOnASingleLine == FormatStyle::SBS_Never) { return 0; + } if (I[1]->InPPDirective != (*I)->InPPDirective || - (I[1]->InPPDirective && I[1]->First->HasUnescapedNewline)) + (I[1]->InPPDirective && I[1]->First->HasUnescapedNewline)) { return 0; + } Limit = limitConsideringMacros(I + 1, E, Limit); AnnotatedLine &Line = **I; if (!Line.First->is(tok::kw_do) && !Line.First->is(tok::kw_else) && - !Line.Last->is(tok::kw_else) && Line.Last->isNot(tok::r_paren)) + !Line.Last->is(tok::kw_else) && Line.Last->isNot(tok::r_paren)) { return 0; + } // Only merge `do while` if `do` is the only statement on the line. if (Line.First->is(tok::kw_do) && !Line.Last->is(tok::kw_do)) return 0; @@ -595,14 +614,16 @@ return 0; // Don't merge with loops, ifs, a single semicolon or a line comment. if (I[1]->First->isOneOf(tok::semi, tok::kw_if, tok::kw_for, tok::kw_while, - TT_ForEachMacro, TT_LineComment)) + TT_ForEachMacro, TT_LineComment)) { return 0; + } // Only inline simple if's (no nested if or else), unless specified if (Style.AllowShortIfStatementsOnASingleLine == FormatStyle::SIS_WithoutElse) { if (I + 2 != E && Line.startsWith(tok::kw_if) && - I[2]->First->is(tok::kw_else)) + I[2]->First->is(tok::kw_else)) { return 0; + } } return 1; } @@ -612,8 +633,9 @@ SmallVectorImpl::const_iterator E, unsigned Limit) { if (Limit == 0 || I + 1 == E || - I[1]->First->isOneOf(tok::kw_case, tok::kw_default)) + I[1]->First->isOneOf(tok::kw_case, tok::kw_default)) { return 0; + } if (I[0]->Last->is(tok::l_brace) || I[1]->First->is(tok::l_brace)) return 0; unsigned NumStmts = 0; @@ -631,8 +653,9 @@ break; if (Line->First->isOneOf(tok::kw_if, tok::kw_for, tok::kw_switch, tok::kw_while) || - EndsWithComment) + EndsWithComment) { return 0; + } if (Line->First->is(tok::comment)) { if (Level != Line->Level) return 0; @@ -671,14 +694,16 @@ // FIXME: If an option to allow short exception handling clauses on a single // line is added, change this to not return for @try and friends. if (Style.Language != FormatStyle::LK_Java && - Line.First->isOneOf(tok::at, tok::minus, tok::plus)) + Line.First->isOneOf(tok::at, tok::minus, tok::plus)) { return 0; + } // Check that the current line allows merging. This depends on whether we // are in a control flow statements as well as several style flags. if (Line.First->is(tok::kw_case) || - (Line.First->Next && Line.First->Next->is(tok::kw_else))) + (Line.First->Next && Line.First->Next->is(tok::kw_else))) { return 0; + } // default: in switch statement if (Line.First->is(tok::kw_default)) { const FormatToken *Tok = Line.First->getNextNonComment(); @@ -692,42 +717,48 @@ if (Style.AllowShortBlocksOnASingleLine == FormatStyle::SBS_Never) return 0; if (Style.AllowShortBlocksOnASingleLine == FormatStyle::SBS_Empty && - !I[1]->First->is(tok::r_brace)) + !I[1]->First->is(tok::r_brace)) { return 0; + } // Don't merge when we can't except the case when // the control statement block is empty if (!Style.AllowShortIfStatementsOnASingleLine && Line.First->isOneOf(tok::kw_if, tok::kw_else) && !Style.BraceWrapping.AfterControlStatement && - !I[1]->First->is(tok::r_brace)) + !I[1]->First->is(tok::r_brace)) { return 0; + } if (!Style.AllowShortIfStatementsOnASingleLine && Line.First->isOneOf(tok::kw_if, tok::kw_else) && Style.BraceWrapping.AfterControlStatement == FormatStyle::BWACS_Always && - I + 2 != E && !I[2]->First->is(tok::r_brace)) + I + 2 != E && !I[2]->First->is(tok::r_brace)) { return 0; + } if (!Style.AllowShortLoopsOnASingleLine && Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for, TT_ForEachMacro) && !Style.BraceWrapping.AfterControlStatement && - !I[1]->First->is(tok::r_brace)) + !I[1]->First->is(tok::r_brace)) { return 0; + } if (!Style.AllowShortLoopsOnASingleLine && Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for, TT_ForEachMacro) && Style.BraceWrapping.AfterControlStatement == FormatStyle::BWACS_Always && - I + 2 != E && !I[2]->First->is(tok::r_brace)) + I + 2 != E && !I[2]->First->is(tok::r_brace)) { return 0; + } // FIXME: Consider an option to allow short exception handling clauses on // a single line. // FIXME: This isn't covered by tests. // FIXME: For catch, __except, __finally the first token on the line // is '}', so this isn't correct here. if (Line.First->isOneOf(tok::kw_try, tok::kw___try, tok::kw_catch, - Keywords.kw___except, tok::kw___finally)) + Keywords.kw___except, tok::kw___finally)) { return 0; + } } if (Line.Last->is(tok::l_brace)) { @@ -785,8 +816,9 @@ // } if (Line.First == Line.Last && Line.First->isNot(TT_FunctionLBrace) && Style.BraceWrapping.AfterControlStatement == - FormatStyle::BWACS_MultiLine) + FormatStyle::BWACS_MultiLine) { return 0; + } return 2; } @@ -820,8 +852,9 @@ SmallVectorImpl::const_iterator E, unsigned Limit) { if (I[0]->InPPDirective && I + 1 != E && - !I[1]->First->HasUnescapedNewline && !I[1]->First->is(tok::eof)) + !I[1]->First->HasUnescapedNewline && !I[1]->First->is(tok::eof)) { return Limit < 2 ? 0 : Limit - 2; + } return Limit; } @@ -923,10 +956,11 @@ const FormatToken *LBrace = State.NextToken->getPreviousNonComment(); FormatToken &Previous = *State.NextToken->Previous; if (!LBrace || LBrace->isNot(tok::l_brace) || LBrace->isNot(BK_Block) || - Previous.Children.size() == 0) + Previous.Children.size() == 0) { // The previous token does not open a block. Nothing to do. We don't // assert so that we can simply call this function for all tokens. return true; + } if (NewLine) { const ParenState &P = State.Stack.back(); @@ -937,8 +971,9 @@ if (Style.LambdaBodyIndentation == FormatStyle::LBI_OuterScope && P.NestedBlockIndent == P.LastSpace) { if (State.NextToken->MatchingParen && - State.NextToken->MatchingParen->is(TT_LambdaLBrace)) + State.NextToken->MatchingParen->is(TT_LambdaLBrace)) { State.Stack.pop_back(); + } if (LBrace->is(TT_LambdaLBrace)) AdditionalIndent = 0; } @@ -968,8 +1003,9 @@ // If the child line exceeds the column limit, we wouldn't want to merge it. // We add +2 for the trailing " }". if (Style.ColumnLimit > 0 && - Child->Last->TotalLength + State.Column + 2 > Style.ColumnLimit) + Child->Last->TotalLength + State.Column + 2 > Style.ColumnLimit) { return false; + } if (!DryRun) { Whitespaces->replaceWhitespace( @@ -1141,9 +1177,10 @@ if (Count > 50000) Node->State.IgnoreStackForComparison = true; - if (!Seen.insert(&Node->State).second) + if (!Seen.insert(&Node->State).second) { // State already examined with lower penalty. continue; + } FormatDecision LastFormat = Node->State.NextToken->getDecision(); if (LastFormat == FD_Unformatted || LastFormat == FD_Continue) @@ -1208,10 +1245,11 @@ LLVM_DEBUG({ printLineState(Node->Previous->State); - if (Node->NewLine) + if (Node->NewLine) { llvm::dbgs() << "Penalty for placing " << Node->Previous->State.NextToken->Tok.getName() << " on a new line: " << Penalty << "\n"; + } }); } } @@ -1291,26 +1329,28 @@ (!Style.isJavaScript() || !Style.JavaScriptWrapImports)) || (Style.isCSharp() && TheLine.InPPDirective); // don't split #regions in C# - if (Style.ColumnLimit == 0) + if (Style.ColumnLimit == 0) { NoColumnLimitLineFormatter(Indenter, Whitespaces, Style, this) .formatLine(TheLine, NextStartColumn + Indent, FirstLine ? FirstStartColumn : 0, DryRun); - else if (FitsIntoOneLine) + } else if (FitsIntoOneLine) { Penalty += NoLineBreakFormatter(Indenter, Whitespaces, Style, this) .formatLine(TheLine, NextStartColumn + Indent, FirstLine ? FirstStartColumn : 0, DryRun); - else + } else { Penalty += OptimizingLineFormatter(Indenter, Whitespaces, Style, this) .formatLine(TheLine, NextStartColumn + Indent, FirstLine ? FirstStartColumn : 0, DryRun); + } RangeMinLevel = std::min(RangeMinLevel, TheLine.Level); } else { // If no token in the current line is affected, we still need to format // affected children. - if (TheLine.ChildrenAffected) + if (TheLine.ChildrenAffected) { for (const FormatToken *Tok = TheLine.First; Tok; Tok = Tok->Next) if (!Tok->Children.empty()) format(Tok->Children, DryRun); + } // Adapt following lines on the current indent level to the same level // unless the current \c AnnotatedLine is not at the beginning of a line. @@ -1323,13 +1363,14 @@ StartsNewLine && ((PreviousLine && PreviousLine->Affected) || TheLine.LeadingEmptyLinesAffected); // Format the first token. - if (ReformatLeadingWhitespace) + if (ReformatLeadingWhitespace) { formatFirstToken(TheLine, PreviousLine, PrevPrevLine, Lines, TheLine.First->OriginalColumn, TheLine.First->OriginalColumn); - else + } else { Whitespaces->addUntouchableToken(*TheLine.First, TheLine.InPPDirective); + } // Notify the WhitespaceManager about the unchanged whitespace. for (FormatToken *Tok = TheLine.First->Next; Tok; Tok = Tok->Next) @@ -1365,8 +1406,9 @@ (!RootToken.Next || (RootToken.Next->is(tok::semi) && !RootToken.Next->Next)) && // Do not remove empty lines before namespace closing "}". - !getNamespaceToken(&Line, Lines)) + !getNamespaceToken(&Line, Lines)) { Newlines = std::min(Newlines, 1u); + } // Remove empty lines at the start of nested blocks (lambdas/arrow functions) if (PreviousLine == nullptr && Line.Level > 0) Newlines = std::min(Newlines, 1u); @@ -1381,8 +1423,9 @@ !PreviousLine->startsWithNamespace() && !(PrevPrevLine && PrevPrevLine->startsWithNamespace() && PreviousLine->startsWith(tok::l_brace)) && - !startsExternCBlock(*PreviousLine)) + !startsExternCBlock(*PreviousLine)) { Newlines = 1; + } // Insert or remove empty line before access specifiers. if (PreviousLine && RootToken.isAccessSpecifier()) { @@ -1443,8 +1486,9 @@ if (!Style.isJavaScript() && Style.IndentPPDirectives != FormatStyle::PPDIS_BeforeHash && (Line.Type == LT_PreprocessorDirective || - Line.Type == LT_ImportStatement)) + Line.Type == LT_ImportStatement)) { Indent = 0; + } Whitespaces->replaceWhitespace(RootToken, Newlines, Indent, Indent, /*IsAligned=*/false, diff --git a/clang/lib/Format/UnwrappedLineParser.cpp b/clang/lib/Format/UnwrappedLineParser.cpp --- a/clang/lib/Format/UnwrappedLineParser.cpp +++ b/clang/lib/Format/UnwrappedLineParser.cpp @@ -358,10 +358,11 @@ // If we found an include guard then all preprocessor directives (other than // the guard) are over-indented by one. - if (IncludeGuard == IG_Found) + if (IncludeGuard == IG_Found) { for (auto &Line : Lines) if (Line.InPPDirective && Line.Level > 0) --Line.Level; + } // Create line with eof token. pushToken(FormatTok); @@ -406,8 +407,9 @@ // do not have a chance to be put on a line of their own until this point. // Here we add this newline before end-of-file comments. if (Style.Language == FormatStyle::LK_TextProto && - !CommentsBeforeNextToken.empty()) + !CommentsBeforeNextToken.empty()) { addUnwrappedLine(); + } flushComments(true); addUnwrappedLine(); } @@ -506,18 +508,19 @@ addUnwrappedLine(); break; case tok::l_brace: - if (NextLBracesType != TT_Unknown) + if (NextLBracesType != TT_Unknown) { FormatTok->setFinalizedType(NextLBracesType); - else if (FormatTok->Previous && - FormatTok->Previous->ClosesRequiresClause) { + } else if (FormatTok->Previous && + FormatTok->Previous->ClosesRequiresClause) { // We need the 'default' case here to correctly parse a function // l_brace. ParseDefault(); continue; } if (CanContainBracedList && !FormatTok->is(TT_MacroBlockBegin) && - tryToParseBracedList()) + tryToParseBracedList()) { continue; + } parseBlock(/*MustBeDeclaration=*/false, /*AddLevels=*/1u, /*MunchSemi=*/true, /*KeepBraces=*/true, /*UnindentWhitesmithsBraces=*/false, CanContainBracedList, @@ -529,12 +532,14 @@ case tok::r_brace: if (OpeningBrace) { if (!Style.RemoveBracesLLVM || - !OpeningBrace->isOneOf(TT_ControlStatementLBrace, TT_ElseLBrace)) + !OpeningBrace->isOneOf(TT_ControlStatementLBrace, TT_ElseLBrace)) { return false; + } if (FormatTok->isNot(tok::r_brace) || StatementCount != 1 || HasLabel || IsPrecededByCommentOrPPDirective || - precededByCommentOrPPDirective()) + precededByCommentOrPPDirective()) { return false; + } const FormatToken *Next = Tokens->peekNextToken(); return Next->isNot(tok::comment) || Next->NewlinesBefore > 0; } @@ -565,8 +570,10 @@ break; } if (!SwitchLabelEncountered && - (Style.IndentCaseLabels || (Line->InPPDirective && Line->Level == 1))) + (Style.IndentCaseLabels || + (Line->InPPDirective && Line->Level == 1))) { ++Line->Level; + } SwitchLabelEncountered = true; parseStructuralElement(); break; @@ -610,7 +617,7 @@ switch (Tok->Tok.getKind()) { case tok::l_brace: if (Style.isJavaScript() && PrevTok) { - if (PrevTok->isOneOf(tok::colon, tok::less)) + if (PrevTok->isOneOf(tok::colon, tok::less)) { // A ':' indicates this code is in a type, or a braced list // following a label in an object literal ({a: {b: 1}}). // A '<' could be an object used in a comparison, but that is nonsense @@ -621,9 +628,10 @@ // trigger BK_Block. In both cases, this must be parsed as an inline // braced init. Tok->setBlockKind(BK_BracedInit); - else if (PrevTok->is(tok::r_paren)) + } else if (PrevTok->is(tok::r_paren)) { // `) { }` can only occur in function or method declarations in JS. Tok->setBlockKind(BK_Block); + } } else { Tok->setBlockKind(BK_Unknown); } @@ -1050,10 +1058,11 @@ Line += Lines.size(); if (Unreachable || - (!PPStack.empty() && PPStack.back().Kind == PP_Unreachable)) + (!PPStack.empty() && PPStack.back().Kind == PP_Unreachable)) { PPStack.push_back({PP_Unreachable, Line}); - else + } else { PPStack.push_back({PP_Conditional, Line}); + } } void UnwrappedLineParser::conditionalCompilationStart(bool Unreachable) { @@ -1107,7 +1116,7 @@ // If there's a #ifndef on the first line, and the only lines before it are // comments, it could be an include guard. bool MaybeIncludeGuard = IfNDef; - if (IncludeGuard == IG_Inited && MaybeIncludeGuard) + if (IncludeGuard == IG_Inited && MaybeIncludeGuard) { for (auto &Line : Lines) { if (!Line.Tokens.front().Tok->is(tok::comment)) { MaybeIncludeGuard = false; @@ -1115,6 +1124,7 @@ break; } } + } --PPBranchLevel; parsePPUnknown(); ++PPBranchLevel; @@ -1143,8 +1153,9 @@ // If the #endif of a potential include guard is the last thing in the file, // then we found an include guard. if (IncludeGuard == IG_Defined && PPBranchLevel == -1 && Tokens->isEOF() && - Style.IndentPPDirectives != FormatStyle::PPDIS_None) + Style.IndentPPDirectives != FormatStyle::PPDIS_None) { IncludeGuard = IG_Found; + } } void UnwrappedLineParser::parsePPDefine() { @@ -1178,8 +1189,9 @@ FormatTok->Tok.setIdentifierInfo(Keywords.kw_internal_ident_after_define); nextToken(); if (FormatTok->Tok.getKind() == tok::l_paren && - !FormatTok->hasWhitespaceBefore()) + !FormatTok->hasWhitespaceBefore()) { parseParens(); + } if (Style.IndentPPDirectives != FormatStyle::PPDIS_None) Line->Level += PPBranchLevel + 1; addUnwrappedLine(); @@ -1302,8 +1314,9 @@ return false; if (!isC78Type(*Tok) && - !Tok->isOneOf(tok::kw_register, tok::kw_struct, tok::kw_union)) + !Tok->isOneOf(tok::kw_register, tok::kw_struct, tok::kw_union)) { return false; + } if (Next->isNot(tok::star) && !Next->Tok.getIdentifierInfo()) return false; @@ -1332,8 +1345,9 @@ // Mark tokens up to the trailing line comments as implicit string // literals. if (FormatTok->isNot(tok::comment) && - !FormatTok->TokenText.startswith("//")) + !FormatTok->TokenText.startswith("//")) { FormatTok->setFinalizedType(TT_ImplicitStringLiteral); + } nextToken(); } } @@ -1386,11 +1400,13 @@ if (NextMustBeValue && !NextEndsTemplateExpr && !PreviousStartsTemplateExpr && (PreviousMustBeValue || Previous->isOneOf(tok::r_square, tok::r_paren, tok::plusplus, - tok::minusminus))) + tok::minusminus))) { return addUnwrappedLine(); + } if ((PreviousMustBeValue || Previous->is(tok::r_paren)) && - isJSDeclOrStmt(Keywords, Next)) + isJSDeclOrStmt(Keywords, Next)) { return addUnwrappedLine(); + } } void UnwrappedLineParser::parseStructuralElement(IfStmtKind *IfKind, @@ -1430,40 +1446,46 @@ case tok::kw_protected: case tok::kw_private: if (Style.Language == FormatStyle::LK_Java || Style.isJavaScript() || - Style.isCSharp()) + Style.isCSharp()) { nextToken(); - else + } else { parseAccessSpecifier(); + } return; case tok::kw_if: - if (Style.isJavaScript() && Line->MustBeDeclaration) + if (Style.isJavaScript() && Line->MustBeDeclaration) { // field/method declaration. break; + } parseIfThenElse(IfKind); return; case tok::kw_for: case tok::kw_while: - if (Style.isJavaScript() && Line->MustBeDeclaration) + if (Style.isJavaScript() && Line->MustBeDeclaration) { // field/method declaration. break; + } parseForOrWhileLoop(); return; case tok::kw_do: - if (Style.isJavaScript() && Line->MustBeDeclaration) + if (Style.isJavaScript() && Line->MustBeDeclaration) { // field/method declaration. break; + } parseDoWhile(); return; case tok::kw_switch: - if (Style.isJavaScript() && Line->MustBeDeclaration) + if (Style.isJavaScript() && Line->MustBeDeclaration) { // 'switch: string' field declaration. break; + } parseSwitch(); return; case tok::kw_default: - if (Style.isJavaScript() && Line->MustBeDeclaration) + if (Style.isJavaScript() && Line->MustBeDeclaration) { // 'default: string' field declaration. break; + } nextToken(); if (FormatTok->is(tok::colon)) { parseLabel(); @@ -1481,9 +1503,10 @@ return; case tok::kw_try: case tok::kw___try: - if (Style.isJavaScript() && Line->MustBeDeclaration) + if (Style.isJavaScript() && Line->MustBeDeclaration) { // field/method declaration. break; + } parseTryCatch(); return; case tok::kw_extern: @@ -1617,21 +1640,24 @@ nextToken(); if (FormatTok->is(tok::l_brace)) { if (Style.BraceWrapping.AfterControlStatement == - FormatStyle::BWACS_Always) + FormatStyle::BWACS_Always) { addUnwrappedLine(); + } parseBlock(); } addUnwrappedLine(); return; case tok::objc_synchronized: nextToken(); - if (FormatTok->is(tok::l_paren)) + if (FormatTok->is(tok::l_paren)) { // Skip synchronization object parseParens(); + } if (FormatTok->is(tok::l_brace)) { if (Style.BraceWrapping.AfterControlStatement == - FormatStyle::BWACS_Always) + FormatStyle::BWACS_Always) { addUnwrappedLine(); + } parseBlock(); } addUnwrappedLine(); @@ -1680,8 +1706,9 @@ if (FormatTok->isOneOf(Keywords.kw_NS_ENUM, Keywords.kw_NS_OPTIONS, Keywords.kw_CF_ENUM, Keywords.kw_CF_OPTIONS, Keywords.kw_CF_CLOSED_ENUM, - Keywords.kw_NS_CLOSED_ENUM)) + Keywords.kw_NS_CLOSED_ENUM)) { parseEnum(); + } break; case tok::kw_struct: case tok::kw_union: @@ -1693,13 +1720,15 @@ nextToken(); // In Java, classes have an implicit static member "class". if (Style.Language == FormatStyle::LK_Java && FormatTok && - FormatTok->is(tok::kw_class)) + FormatTok->is(tok::kw_class)) { nextToken(); + } if (Style.isJavaScript() && FormatTok && - FormatTok->Tok.getIdentifierInfo()) + FormatTok->Tok.getIdentifierInfo()) { // JavaScript only has pseudo keywords, all keywords are allowed to // appear in "IdentifierName" positions. See http://es5.github.io/#x7.6 nextToken(); + } break; case tok::semi: nextToken(); @@ -1728,8 +1757,9 @@ case tok::caret: nextToken(); if (FormatTok->Tok.isAnyIdentifier() || - FormatTok->isSimpleTypeSpecifier()) + FormatTok->isSimpleTypeSpecifier()) { nextToken(); + } if (FormatTok->is(tok::l_paren)) parseParens(); if (FormatTok->is(tok::l_brace)) @@ -1748,8 +1778,9 @@ // If necessary, we could set the type to something different than // TT_FunctionLBrace. if (Style.BraceWrapping.AfterControlStatement == - FormatStyle::BWACS_Always) + FormatStyle::BWACS_Always) { addUnwrappedLine(); + } } else if (Style.BraceWrapping.AfterFunction) { addUnwrappedLine(); } @@ -2206,8 +2237,9 @@ // replace this by using parseAssignmentExpression() inside. do { if (Style.isCSharp() && FormatTok->is(TT_FatArrow) && - tryToParseChildBlock()) + tryToParseChildBlock()) { continue; + } if (Style.isJavaScript()) { if (FormatTok->is(Keywords.kw_function) || FormatTok->startsSequence(Keywords.kw_async, Keywords.kw_function)) { @@ -2336,10 +2368,12 @@ case tok::identifier: if (Style.isJavaScript() && (FormatTok->is(Keywords.kw_function) || - FormatTok->startsSequence(Keywords.kw_async, Keywords.kw_function))) + FormatTok->startsSequence(Keywords.kw_async, + Keywords.kw_function))) { tryToParseJSFunction(); - else + } else { nextToken(); + } break; case tok::kw_requires: { auto RequiresToken = FormatTok; @@ -2554,8 +2588,10 @@ ElseLeftBrace = FormatTok; CompoundStatementIndenter Indenter(this, Style, Line->Level); if (parseBlock(/*MustBeDeclaration=*/false, /*AddLevels=*/1u, - /*MunchSemi=*/true, KeepElseBraces) == IfStmtKind::IfOnly) + /*MunchSemi=*/true, + KeepElseBraces) == IfStmtKind::IfOnly) { Kind = IfStmtKind::IfElseIf; + } addUnwrappedLine(); } else if (FormatTok->is(tok::kw_if)) { const FormatToken *Previous = Tokens->getPreviousToken(); @@ -2676,8 +2712,9 @@ ((Style.Language == FormatStyle::LK_Java || Style.isJavaScript()) && FormatTok->is(Keywords.kw_finally)) || (FormatTok->isObjCAtKeyword(tok::objc_catch) || - FormatTok->isObjCAtKeyword(tok::objc_finally)))) + FormatTok->isObjCAtKeyword(tok::objc_finally)))) { break; + } nextToken(); while (FormatTok->isNot(tok::l_brace)) { if (FormatTok->is(tok::l_paren)) { @@ -2719,13 +2756,14 @@ } else { while (FormatTok->isOneOf(tok::identifier, tok::coloncolon, tok::kw_inline, tok::l_square, tok::period, tok::l_paren) || - (Style.isCSharp() && FormatTok->is(tok::kw_union))) + (Style.isCSharp() && FormatTok->is(tok::kw_union))) { if (FormatTok->is(tok::l_square)) parseSquare(); else if (FormatTok->is(tok::l_paren)) parseParens(); else nextToken(); + } } if (FormatTok->is(tok::l_brace)) { if (ShouldBreakBeforeBrace(Style, InitialToken)) @@ -2884,8 +2922,9 @@ FormatStyle::BWACS_Always) { addUnwrappedLine(); if (!Style.IndentCaseBlocks && - Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths) + Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths) { ++Line->Level; + } } parseStructuralElement(); } @@ -3411,8 +3450,9 @@ } if (!Style.AllowShortEnumsOnASingleLine && - ShouldBreakBeforeBrace(Style, InitialToken)) + ShouldBreakBeforeBrace(Style, InitialToken)) { addUnwrappedLine(); + } // Parse enum body. nextToken(); if (!Style.AllowShortEnumsOnASingleLine) { @@ -3697,8 +3737,9 @@ nextToken(); // Early exit in case someone forgot a close angle. if (FormatTok->isOneOf(tok::semi, tok::l_brace) || - FormatTok->isObjCAtKeyword(tok::objc_end)) + FormatTok->isObjCAtKeyword(tok::objc_end)) { return; + } } while (!eof() && FormatTok->isNot(tok::greater)); nextToken(); // Skip '>'. } @@ -3743,9 +3784,10 @@ // The base class can also have lightweight generics applied to it. if (FormatTok->is(tok::less)) parseObjCLightweightGenerics(); - } else if (FormatTok->is(tok::l_paren)) + } else if (FormatTok->is(tok::l_paren)) { // Skip category, if present. parseParens(); + } if (FormatTok->is(tok::less)) parseObjCProtocolList(); @@ -3777,11 +3819,12 @@ nextToken(); // Early exit in case someone forgot a close angle. if (FormatTok->isOneOf(tok::semi, tok::l_brace) || - FormatTok->isObjCAtKeyword(tok::objc_end)) + FormatTok->isObjCAtKeyword(tok::objc_end)) { break; - if (FormatTok->is(tok::less)) + } + if (FormatTok->is(tok::less)) { ++NumOpenAngles; - else if (FormatTok->is(tok::greater)) { + } else if (FormatTok->is(tok::greater)) { assert(NumOpenAngles > 0 && "'>' makes NumOpenAngles negative"); --NumOpenAngles; } @@ -3795,9 +3838,10 @@ assert(FormatTok->Tok.getObjCKeywordID() == tok::objc_protocol); nextToken(); - if (FormatTok->is(tok::l_paren)) + if (FormatTok->is(tok::l_paren)) { // The expression form of @protocol, e.g. "Protocol* p = @protocol(foo);". return false; + } // The definition/declaration form, // @protocol Foo @@ -3845,8 +3889,9 @@ // parsing the structural element, i.e. the declaration or expression for // `export default`. if (!IsImport && !FormatTok->isOneOf(tok::l_brace, tok::star) && - !FormatTok->isStringLiteral()) + !FormatTok->isStringLiteral()) { return; + } while (!eof()) { if (FormatTok->is(tok::semi)) @@ -3943,8 +3988,9 @@ StringRef IndentContent = FormatTok.TokenText; if (FormatTok.TokenText.startswith("//") || - FormatTok.TokenText.startswith("/*")) + FormatTok.TokenText.startswith("/*")) { IndentContent = FormatTok.TokenText.substr(2); + } if (CommentPragmasRegex.match(IndentContent)) return false; @@ -4117,8 +4163,9 @@ continuesLineCommentSection(*FormatTok, *Line, CommentPragmasRegex); } if (!FormatTok->ContinuesLineCommentSection && - (isOnNewLine(*FormatTok) || FormatTok->IsFirst)) + (isOnNewLine(*FormatTok) || FormatTok->IsFirst)) { ShouldPushCommentsInCurrentLine = false; + } if (ShouldPushCommentsInCurrentLine) pushToken(FormatTok); else @@ -4180,8 +4227,9 @@ // before the preprocessor directive, at the same level as the // preprocessor directive, as we consider them to apply to the directive. if (Style.IndentPPDirectives == FormatStyle::PPDIS_BeforeHash && - PPBranchLevel > 0) + PPBranchLevel > 0) { Line->Level += PPBranchLevel; + } flushComments(isOnNewLine(*FormatTok)); parsePPDirective(); PreviousWasComment = FormatTok->is(tok::comment); @@ -4190,8 +4238,9 @@ } if (!PPStack.empty() && (PPStack.back().Kind == PP_Unreachable) && - !Line->InPPDirective) + !Line->InPPDirective) { continue; + } if (!FormatTok->is(tok::comment)) { distributeComments(Comments, FormatTok); diff --git a/clang/lib/Format/WhitespaceManager.cpp b/clang/lib/Format/WhitespaceManager.cpp --- a/clang/lib/Format/WhitespaceManager.cpp +++ b/clang/lib/Format/WhitespaceManager.cpp @@ -167,11 +167,12 @@ // If there are multiple changes in this token, sum up all the changes until // the end of the line. - if (Changes[i - 1].IsInsideToken && Changes[i - 1].NewlinesBefore == 0) + if (Changes[i - 1].IsInsideToken && Changes[i - 1].NewlinesBefore == 0) { LastOutsideTokenChange->TokenLength += Changes[i - 1].TokenLength + Changes[i - 1].Spaces; - else + } else { LastOutsideTokenChange = &Changes[i - 1]; + } Changes[i].PreviousEndOfTokenColumn = Changes[i - 1].StartOfTokenColumn + Changes[i - 1].TokenLength; @@ -227,13 +228,14 @@ Change.StartOfBlockComment = nullptr; Change.IndentationOffset = 0; if (Change.Tok->is(tok::comment)) { - if (Change.Tok->is(TT_LineComment) || !Change.IsInsideToken) + if (Change.Tok->is(TT_LineComment) || !Change.IsInsideToken) { LastBlockComment = &Change; - else { - if ((Change.StartOfBlockComment = LastBlockComment)) + } else { + if ((Change.StartOfBlockComment = LastBlockComment)) { Change.IndentationOffset = Change.StartOfTokenColumn - Change.StartOfBlockComment->StartOfTokenColumn; + } } } else { LastBlockComment = nullptr; @@ -303,18 +305,21 @@ for (unsigned i = Start; i != End; ++i) { if (ScopeStack.size() != 0 && Changes[i].indentAndNestingLevel() < - Changes[ScopeStack.back()].indentAndNestingLevel()) + Changes[ScopeStack.back()].indentAndNestingLevel()) { ScopeStack.pop_back(); + } // Compare current token to previous non-comment token to ensure whether // it is in a deeper scope or not. unsigned PreviousNonComment = i - 1; while (PreviousNonComment > Start && - Changes[PreviousNonComment].Tok->is(tok::comment)) + Changes[PreviousNonComment].Tok->is(tok::comment)) { --PreviousNonComment; + } if (i != Start && Changes[i].indentAndNestingLevel() > - Changes[PreviousNonComment].indentAndNestingLevel()) + Changes[PreviousNonComment].indentAndNestingLevel()) { ScopeStack.push_back(i); + } bool InsideNestedScope = ScopeStack.size() != 0; bool ContinuedStringLiteral = i > Start && @@ -337,10 +342,11 @@ Changes[i].Spaces += Shift; // FIXME: This is a workaround that should be removed when we fix // http://llvm.org/PR53699. An assertion later below verifies this. - if (Changes[i].NewlinesBefore == 0) + if (Changes[i].NewlinesBefore == 0) { Changes[i].Spaces = std::max(Changes[i].Spaces, static_cast(Changes[i].Tok->SpacesRequiredBefore)); + } } // This is for function parameters that are split across multiple lines, @@ -358,8 +364,9 @@ // Continued function declaration if (ScopeStart > Start + 1 && - Changes[ScopeStart - 2].Tok->is(TT_FunctionDeclarationName)) + Changes[ScopeStart - 2].Tok->is(TT_FunctionDeclarationName)) { return true; + } // Continued function call if (ScopeStart > Start + 1 && @@ -367,13 +374,15 @@ Changes[ScopeStart - 1].Tok->is(tok::l_paren) && Changes[ScopeStart].Tok->isNot(TT_LambdaLSquare)) { if (Changes[i].Tok->MatchingParen && - Changes[i].Tok->MatchingParen->is(TT_LambdaLBrace)) + Changes[i].Tok->MatchingParen->is(TT_LambdaLBrace)) { return false; + } if (Changes[ScopeStart].NewlinesBefore > 0) return false; if (Changes[i].Tok->is(tok::l_brace) && - Changes[i].Tok->is(BK_BracedInit)) + Changes[i].Tok->is(BK_BracedInit)) { return true; + } return Style.BinPackArguments; } @@ -387,16 +396,18 @@ // Continued ternary operator if (Changes[i].Tok->Previous && - Changes[i].Tok->Previous->is(TT_ConditionalExpr)) + Changes[i].Tok->Previous->is(TT_ConditionalExpr)) { return true; + } // Continued direct-list-initialization using braced list. if (ScopeStart > Start + 1 && Changes[ScopeStart - 2].Tok->is(tok::identifier) && Changes[ScopeStart - 1].Tok->is(tok::l_brace) && Changes[i].Tok->is(tok::l_brace) && - Changes[i].Tok->is(BK_BracedInit)) + Changes[i].Tok->is(BK_BracedInit)) { return true; + } // Continued braced list. if (ScopeStart > Start + 1 && @@ -406,8 +417,9 @@ for (unsigned OuterScopeStart : llvm::reverse(ScopeStack)) { // Lambda. if (OuterScopeStart > Start && - Changes[OuterScopeStart - 1].Tok->is(TT_LambdaLBrace)) + Changes[OuterScopeStart - 1].Tok->is(TT_LambdaLBrace)) { return false; + } } if (Changes[ScopeStart].NewlinesBefore > 0) return false; @@ -532,10 +544,11 @@ // We need to adjust the StartOfTokenColumn of each Change that is on a line // containing any matching token to be aligned and located after such token. auto AlignCurrentSequence = [&] { - if (StartOfSequence > 0 && StartOfSequence < EndOfSequence) + if (StartOfSequence > 0 && StartOfSequence < EndOfSequence) { AlignTokenSequence(Style, StartOfSequence, EndOfSequence, WidthLeft + WidthAnchor, RightJustify, Matches, Changes); + } WidthLeft = 0; WidthAnchor = 0; WidthRight = 0; @@ -567,8 +580,9 @@ // A new line starts, re-initialize line status tracking bools. // Keep the match state if a string literal is continued on this line. if (i == 0 || !Changes[i].Tok->is(tok::string_literal) || - !Changes[i - 1].Tok->is(tok::string_literal)) + !Changes[i - 1].Tok->is(tok::string_literal)) { FoundMatchOnLine = false; + } LineIsComment = true; } @@ -601,12 +615,12 @@ unsigned ChangeWidthLeft = Changes[i].StartOfTokenColumn; unsigned ChangeWidthAnchor = 0; unsigned ChangeWidthRight = 0; - if (RightJustify) { + if (RightJustify) if (ACS.PadOperators) ChangeWidthAnchor = Changes[i].TokenLength; else ChangeWidthLeft += Changes[i].TokenLength; - } else + else ChangeWidthRight = Changes[i].TokenLength; for (unsigned j = i + 1; j != e && Changes[j].NewlinesBefore == 0; ++j) { ChangeWidthRight += Changes[j].Spaces; @@ -749,9 +763,10 @@ !FoundMatchOnLine && !(LineIsComment && Style.AlignConsecutiveMacros.AcrossComments); - if (EmptyLineBreak || NoMatchBreak) + if (EmptyLineBreak || NoMatchBreak) { AlignMacroSequence(StartOfSequence, EndOfSequence, MinColumn, MaxColumn, FoundMatchOnLine, AlignMacrosMatches, Changes); + } // A new line starts, re-initialize line status tracking bools. FoundMatchOnLine = false; @@ -857,8 +872,9 @@ if (!Next->Tok.getIdentifierInfo()) break; if (Next->isOneOf(TT_StartOfName, TT_FunctionDeclarationName, - tok::kw_operator)) + tok::kw_operator)) { return false; + } } return true; }, @@ -1198,9 +1214,10 @@ if (Cell.HasSplit) return true; for (const auto *Next = Cell.NextColumnElement; Next != nullptr; - Next = Next->NextColumnElement) + Next = Next->NextColumnElement) { if (Next->HasSplit) return true; + } return false; } @@ -1372,12 +1389,13 @@ } if (C.CreateReplacement) { std::string ReplacementText = C.PreviousLinePostfix; - if (C.ContinuesPPDirective) + if (C.ContinuesPPDirective) { appendEscapedNewlineText(ReplacementText, C.NewlinesBefore, C.PreviousEndOfTokenColumn, C.EscapedNewlineColumn); - else + } else { appendNewlineText(ReplacementText, C.NewlinesBefore); + } // FIXME: This assert should hold if we computed the column correctly. // assert((int)C.StartOfTokenColumn >= C.Spaces); appendIndentText( @@ -1395,8 +1413,9 @@ SourceMgr.getFileOffset(Range.getBegin()); // Don't create a replacement, if it does not change anything. if (StringRef(SourceMgr.getCharacterData(Range.getBegin()), - WhitespaceLength) == Text) + WhitespaceLength) == Text) { return; + } auto Err = Replaces.add(tooling::Replacement( SourceMgr, CharSourceRange::getCharRange(Range), Text)); // FIXME: better error handling. For now, just print an error message in the