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);
// ** blah blah blah
// */
if (Lines.size() >= 2 && Content[1].startswith("**") &&
- static_cast<unsigned>(ContentColumn[1]) == StartColumn) {
+ static_cast<unsigned>(ContentColumn[1]) == StartColumn)
DecorationColumn = StartColumn;
- }
Decoration = "* ";
if (Lines.size() == 1 && !FirstInLine) {
// correctly indented.
LastLineNeedsDecoration = false;
// Align the star in the last '*/' with the stars on the previous lines.
- if (e >= 2 && !Decoration.empty()) {
+ if (e >= 2 && !Decoration.empty())
ContentColumn[i] = DecorationColumn;
- }
} else if (Decoration.empty()) {
// For all other lines, set the start column to 0 if they're empty, so
// we do not insert trailing whitespace anywhere.
unsigned DecorationSize = Decoration.startswith(Content[i])
? Content[i].size()
: Decoration.size();
- if (DecorationSize) {
+ if (DecorationSize)
ContentColumn[i] = DecorationColumn + DecorationSize;
- }
Content[i] = Content[i].substr(DecorationSize);
if (!Decoration.startswith(Content[i]))
IndentAtLineBreak =
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";
- }
});
}
// /** line 0 */
// is "* line 0", so we need to skip over the decoration in that case.
StringRef ContentWithNoDecoration = Content[LineIndex];
- if (LineIndex == 0 && ContentWithNoDecoration.startswith("*")) {
+ if (LineIndex == 0 && ContentWithNoDecoration.startswith("*"))
ContentWithNoDecoration = ContentWithNoDecoration.substr(1).ltrim(Blanks);
- }
StringRef FirstWord = ContentWithNoDecoration.substr(
0, ContentWithNoDecoration.find_first_of(Blanks));
if (ContentIndentingJavadocAnnotations.find(FirstWord) !=
// Content[LineIndex] may exclude the indent after the '*' decoration. In that
// case, we compute the start of the comment pragma manually.
StringRef IndentContent = Content[LineIndex];
- if (Lines[LineIndex].ltrim(Blanks).startswith("*")) {
+ if (Lines[LineIndex].ltrim(Blanks).startswith("*"))
IndentContent = Lines[LineIndex].ltrim(Blanks).substr(1);
- }
return LineIndex > 0 && !CommentPragmasRegex.match(IndentContent) &&
mayReflowContent(Content[LineIndex]) && !Tok.Finalized &&
!switchesFormatting(tokenAt(LineIndex));
}
void BreakableLineCommentSection::updateNextToken(LineState &State) const {
- if (LastLineTok) {
+ if (LastLineTok)
State.NextToken = LastLineTok->Next;
- }
}
bool BreakableLineCommentSection::mayReflow(
// Line comments have the indent as part of the prefix, so we need to
// recompute the start of the line.
StringRef IndentContent = Content[LineIndex];
- if (Lines[LineIndex].startswith("//")) {
+ if (Lines[LineIndex].startswith("//"))
IndentContent = Lines[LineIndex].substr(2);
- }
// FIXME: Decide whether we want to reflow non-regular indents:
// Currently, we only reflow when the OriginalPrefix[LineIndex] matches the
// OriginalPrefix[LineIndex-1]. That means we don't reflow
static StringRef
getCanonicalRawStringDelimiter(const FormatStyle &Style,
FormatStyle::LanguageKind Language) {
- for (const auto &Format : Style.RawStringFormats) {
+ for (const auto &Format : Style.RawStringFormats)
if (Format.Language == Language)
return StringRef(Format.CanonicalDelimiter);
- }
return "";
}
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 (State.Stack.back().IsCSharpGenericTypeConstraint &&
// * always un-indent by the operator when
// BreakBeforeTernaryOperators=true
unsigned Indent = State.Stack.back().Indent;
- if (Style.AlignOperands != FormatStyle::OAS_DontAlign) {
+ if (Style.AlignOperands != FormatStyle::OAS_DontAlign)
Indent -= Style.ContinuationIndentWidth;
- }
if (Style.BreakBeforeTernaryOperators &&
State.Stack.back().UnindentOperator)
Indent -= 2;
auto NewCode = applyAllReplacements(RawText, Fixes.first);
tooling::Replacements NoFixes;
- if (!NewCode) {
+ if (!NewCode)
return addMultilineToken(Current, State);
- }
if (!DryRun) {
if (NewDelimiter != OldDelimiter) {
// In 'R"delimiter(...', the delimiter starts 2 characters after the start
return nullptr;
// Don't break string literals inside Objective-C array literals (doing so
// raises the warning -Wobjc-string-concatenation).
- if (State.Stack.back().IsInsideObjCArrayLiteral) {
+ if (State.Stack.back().IsInsideObjCArrayLiteral)
return nullptr;
- }
StringRef Text = Current.TokenText;
StringRef Prefix;
// 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<BreakableBlockComment>(
Current, StartColumn, Current.OriginalColumn, !Current.Previous,
State.Line->InPPDirective, Encoding, Style, Whitespaces.useCRLF());
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 ||
unsigned ExcessCharactersPenalty =
(ContentStartColumn + ToSplitColumns - ColumnLimit) *
Style.PenaltyExcessCharacter;
- if (NewBreakPenalty < ExcessCharactersPenalty) {
+ if (NewBreakPenalty < ExcessCharactersPenalty)
Reflow = false;
- }
}
}
}
// If we break the token inside a parameter list, we need to break before
// the next parameter on all levels, so that the next parameter is clearly
// visible. Line comments already introduce a break.
- if (Current.isNot(TT_LineComment)) {
+ if (Current.isNot(TT_LineComment))
for (ParenState &Paren : State.Stack)
Paren.BreakBeforeParameter = true;
- }
if (Current.is(TT_BlockComment))
State.NoContinuation = true;
TargetToken = TargetLine->First;
while (TargetToken && !TargetToken->is(tok::r_brace))
TargetToken = TargetToken->Next;
- if (!TargetToken) {
+ if (!TargetToken)
while (I < Lines.size() && !Lines[I]->First->is(tok::r_brace))
++I;
- }
} else if (CurrentLine->First->closesScope()) {
if (OpeningLineIndex > Lines.size())
continue;
IO.mapOptional("QualifierAlignment", Style.QualifierAlignment);
// Default Order for Left/Right based Qualifier alignment.
- if (Style.QualifierAlignment == FormatStyle::QAS_Right) {
+ if (Style.QualifierAlignment == FormatStyle::QAS_Right)
Style.QualifierOrder = {"type", "const", "volatile"};
- } else if (Style.QualifierAlignment == FormatStyle::QAS_Left) {
+ else if (Style.QualifierAlignment == FormatStyle::QAS_Left)
Style.QualifierOrder = {"const", "volatile", "type"};
- } else if (Style.QualifierAlignment == FormatStyle::QAS_Custom) {
+ else if (Style.QualifierAlignment == FormatStyle::QAS_Custom)
IO.mapOptional("QualifierOrder", Style.QualifierOrder);
- }
IO.mapOptional("CompactNamespaces", Style.CompactNamespaces);
IO.mapOptional("ConstructorInitializerIndentWidth",
IO.mapOptional("Maximum", signedMaximum);
Space.Maximum = static_cast<unsigned>(signedMaximum);
- if (Space.Maximum != -1u) {
+ if (Space.Maximum != -1u)
Space.Minimum = std::min(Space.Minimum, Space.Maximum);
- }
}
};
LLVMStyle.WhitespaceSensitiveMacros.push_back("CF_SWIFT_NAME");
// Defaults that differ when not C++.
- if (Language == FormatStyle::LK_TableGen) {
+ if (Language == FormatStyle::LK_TableGen)
LLVMStyle.SpacesInContainerLiterals = false;
- }
- if (LLVMStyle.isJson()) {
+ if (LLVMStyle.isJson())
LLVMStyle.ColumnLimit = 0;
- }
return LLVMStyle;
}
bool getPredefinedStyle(StringRef Name, FormatStyle::LanguageKind Language,
FormatStyle *Style) {
- if (Name.equals_insensitive("llvm")) {
+ if (Name.equals_insensitive("llvm"))
*Style = getLLVMStyle(Language);
- } else if (Name.equals_insensitive("chromium")) {
+ else if (Name.equals_insensitive("chromium"))
*Style = getChromiumStyle(Language);
- } else if (Name.equals_insensitive("mozilla")) {
+ else if (Name.equals_insensitive("mozilla"))
*Style = getMozillaStyle();
- } else if (Name.equals_insensitive("google")) {
+ else if (Name.equals_insensitive("google"))
*Style = getGoogleStyle(Language);
- } else if (Name.equals_insensitive("webkit")) {
+ else if (Name.equals_insensitive("webkit"))
*Style = getWebKitStyle();
- } else if (Name.equals_insensitive("gnu")) {
+ else if (Name.equals_insensitive("gnu"))
*Style = getGNUStyle();
- } else if (Name.equals_insensitive("microsoft")) {
+ else if (Name.equals_insensitive("microsoft"))
*Style = getMicrosoftStyle(Language);
- } else if (Name.equals_insensitive("none")) {
+ else if (Name.equals_insensitive("none"))
*Style = getNoStyle();
- } else if (Name.equals_insensitive("inheritparentconfig")) {
+ else if (Name.equals_insensitive("inheritparentconfig"))
Style->InheritsParentConfig = true;
- } else {
+ else
return false;
- }
Style->Language = Language;
return true;
}
bool containsOnlyComments(const AnnotatedLine &Line) {
- for (FormatToken *Tok = Line.First; Tok != nullptr; Tok = Tok->Next) {
+ for (FormatToken *Tok = Line.First; Tok != nullptr; Tok = Tok->Next)
if (Tok->isNot(tok::comment))
return false;
- }
return true;
}
unsigned Idx = 0;
while (Idx < Tokens.size()) {
unsigned St = Idx, End = Idx;
- while ((End + 1) < Tokens.size() &&
- Tokens[End]->Next == Tokens[End + 1]) {
+ while ((End + 1) < Tokens.size() && Tokens[End]->Next == Tokens[End + 1])
++End;
- }
auto SR = CharSourceRange::getCharRange(Tokens[St]->Tok.getLocation(),
Tokens[End]->Tok.getEndLoc());
auto Err =
// Determines whether 'Ranges' intersects with ('Start', 'End').
static bool affectsRange(ArrayRef<tooling::Range> Ranges, unsigned Start,
unsigned End) {
- for (auto Range : Ranges) {
+ for (auto Range : Ranges)
if (Range.getOffset() < End &&
Range.getOffset() + Range.getLength() > Start)
return true;
- }
return false;
}
SmallVector<unsigned, 16> Indices =
llvm::to_vector<16>(llvm::seq<unsigned>(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();
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.
FormattingOff = true;
}
- if (Trimmed.contains(RawStringTermination)) {
+ if (Trimmed.contains(RawStringTermination))
FormattingOff = false;
- }
if (Trimmed == "// clang-format off" || Trimmed == "/* clang-format off */")
FormattingOff = true;
StringRef Static = Matches[1];
StringRef Identifier = Matches[2];
bool IsStatic = false;
- if (Static.contains("static")) {
+ if (Static.contains("static"))
IsStatic = true;
- }
ImportsInBlock.push_back(
{Identifier, Line, Prev, AssociatedCommentLines, IsStatic});
AssociatedCommentLines.clear();
// add a replacement to remove the "x = " from the result.
if (!Replaces.add(tooling::Replacement(FileName, 0, 4, ""))) {
// apply the reformatting changes and the removal of "x = ".
- if (applyAllReplacements(Code, Replaces)) {
+ if (applyAllReplacements(Code, Replaces))
return {Replaces, 0};
- }
}
return {tooling::Replacements(), 0};
}
StringRef FallbackStyleName,
StringRef Code, llvm::vfs::FileSystem *FS,
bool AllowUnknownOptions) {
- if (!FS) {
+ if (!FS)
FS = llvm::vfs::getRealFileSystem().get();
- }
FormatStyle Style = getLLVMStyle(guessLanguage(FileName, Code));
FormatStyle FallbackStyle = getNoStyle();
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);
Tokens.back()->Tok.setKind(tok::period);
return;
}
- if (tryMergeNullishCoalescingEqual()) {
+ if (tryMergeNullishCoalescingEqual())
return;
- }
}
if (Style.isCSharp()) {
StringRef Buffer = SourceMgr.getBufferOrFake(ID).getBuffer();
// Calculate the offset of the start of the current line.
auto LineOffset = Buffer.rfind('\n', FirstInLineOffset);
- if (LineOffset == StringRef::npos) {
+ if (LineOffset == StringRef::npos)
LineOffset = 0;
- } else {
+ else
++LineOffset;
- }
auto FirstSpace = Buffer.find_first_of(" \n", LineOffset);
StringRef LineStart;
- if (FirstSpace == StringRef::npos) {
+ if (FirstSpace == StringRef::npos)
LineStart = Buffer.substr(LineOffset);
- } else {
+ else
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();
FormatTok->Tok.setKind(tok::kw_if);
}
} else if (FormatTok->is(tok::identifier)) {
- if (MacroBlockBeginRegex.match(Text)) {
+ if (MacroBlockBeginRegex.match(Text))
FormatTok->setType(TT_MacroBlockBegin);
- } else if (MacroBlockEndRegex.match(Text)) {
+ else if (MacroBlockEndRegex.match(Text))
FormatTok->setType(TT_MacroBlockEnd);
- }
}
}
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) {
"^/[/*] *( +([a-zA-Z0-9:_]+))?\\.? *(\\*/)?$", llvm::Regex::IgnoreCase);
// Pull out just the comment text.
- if (!CommentPattern.match(Comment->Next->TokenText, &Groups)) {
+ if (!CommentPattern.match(Comment->Next->TokenText, &Groups))
return false;
- }
NamespaceNameInComment = Groups.size() > 2 ? Groups[2] : "";
return (NamespaceNameInComment == NamespaceName);
// Don't attempt to comment unbalanced braces or this can
// lead to comments being placed on the closing brace which isn't
// the matching brace of the namespace. (occurs during incomplete editing).
- if (Braces != 0) {
+ if (Braces != 0)
return {Fixes, 0};
- }
std::string AllNamespaceNames;
size_t StartLineIndex = SIZE_MAX;
const FormatToken *EndCommentPrevTok = RBraceTok;
// Namespaces often end with '};'. In that case, attach namespace end
// comments to the semicolon tokens.
- if (RBraceTok->Next && RBraceTok->Next->is(tok::semi)) {
+ if (RBraceTok->Next && RBraceTok->Next->is(tok::semi))
EndCommentPrevTok = RBraceTok->Next;
- }
if (StartLineIndex == SIZE_MAX)
StartLineIndex = EndLine->MatchingOpeningBlockLineIndex;
std::string NamespaceName = computeName(NamespaceTok);
}
static bool endsWithSpace(const std::string &s) {
- if (s.empty()) {
+ if (s.empty())
return false;
- }
return isspace(s.back());
}
static bool startsWithSpace(const std::string &s) {
- if (s.empty()) {
+ if (s.empty())
return false;
- }
return isspace(s.front());
}
// Then move through the other tokens.
auto *Tok = Begin;
while (Tok != End) {
- if (!NewText.empty() && !endsWithSpace(NewText)) {
+ if (!NewText.empty() && !endsWithSpace(NewText))
NewText += " ";
- }
NewText += Tok->TokenText;
Tok = Tok->Next;
// If we are rotating to the right we move the first token to the back.
if (!Left) {
- if (!NewText.empty() && !startsWithSpace(NewText)) {
+ if (!NewText.empty() && !startsWithSpace(NewText))
NewText += " ";
- }
NewText += First->TokenText;
}
// The case `const Foo &&` -> `Foo const &&`
// The case `const std::Foo &&` -> `std::Foo const &&`
// The case `const std::Foo<T> &&` -> `std::Foo<T> const &&`
- while (Next && Next->isOneOf(tok::identifier, tok::coloncolon)) {
+ while (Next && Next->isOneOf(tok::identifier, tok::coloncolon))
Next = Next->Next;
- }
if (Next && Next->is(TT_TemplateOpener)) {
Next = Next->MatchingParen;
// Move to the end of any template class members e.g.
break;
}
- if (!Qual) {
+ if (!Qual)
return Tok;
- }
if (LastQual && Qual != LastQual && Qual->is(QualifierType)) {
rotateTokens(SourceMgr, Fixes, Tok, Qual, /*Left=*/true);
}
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<T> const` -> `const std::Foo<T> &&`
while (Next && Next->isOneOf(tok::identifier, tok::coloncolon))
tok::TokenKind QualifierToken =
LeftRightQualifierAlignmentFixer::getTokenFromQualifier(s);
- if (QualifierToken != tok::kw_typeof && QualifierToken != tok::identifier) {
+ if (QualifierToken != tok::kw_typeof && QualifierToken != tok::identifier)
Qualifiers.push_back(QualifierToken);
- }
if (left)
// Reverse the order for left aligned items.
// harmless and will be stripped by the subsequent formatting pass.
// FIXME: A better long term fix is to re-calculate Ranges after sorting.
unsigned PreviousSize = PreviousText.size();
- while (ReferencesText.size() < PreviousSize) {
+ while (ReferencesText.size() < PreviousSize)
ReferencesText += " ";
- }
// Separate references from the main code body of the file.
if (FirstNonImportLine && FirstNonImportLine->First->NewlinesBefore < 2 &&
nextToken();
while (Current->is(tok::identifier)) {
nextToken();
- if (Current->is(tok::semi)) {
+ if (Current->is(tok::semi))
return true;
- }
if (!Current->is(tok::period))
return false;
nextToken();
if (FormatToken *MaybeSel = Left->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 (Left->is(TT_OverloadedOperatorLParen)) {
// Detect the case where macros are used to generate lambdas or
// function bodies, e.g.:
// auto my_lambda = MACRO((Type *type, int i) { .. body .. });
- for (FormatToken *Tok = Left; Tok != CurrentToken; Tok = Tok->Next) {
+ for (FormatToken *Tok = Left; Tok != CurrentToken; Tok = Tok->Next)
if (Tok->is(TT_BinaryOperator) &&
Tok->isOneOf(tok::star, tok::amp, tok::ampamp))
Tok->setType(TT_PointerOrReference);
- }
}
if (StartsObjCMethodExpr) {
return false;
// Move along the tokens inbetween the '[' and ']' e.g. [STAThread].
- while (AttrTok && AttrTok->isNot(tok::r_square)) {
+ while (AttrTok && AttrTok->isNot(tok::r_square))
AttrTok = AttrTok->Next;
- }
if (!AttrTok)
return false;
// 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 &&
if (!Style.isCpp() || !Tok.startsSequence(tok::l_square, tok::l_square))
return false;
// The first square bracket is part of an ObjC array literal
- if (Tok.Previous && Tok.Previous->is(tok::at)) {
+ if (Tok.Previous && Tok.Previous->is(tok::at))
return false;
- }
const FormatToken *AttrTok = Tok.Next->Next;
if (!AttrTok)
return false;
const auto End = std::next(Contexts.rbegin(), 2);
auto Last = Contexts.rbegin();
unsigned Depth = 0;
- for (; Last != End; ++Last) {
+ for (; Last != End; ++Last)
if (Last->ContextKind == tok::l_brace)
++Depth;
- }
return Depth == 2 && Last->ContextKind != tok::l_brace;
}
CurrentToken->MatchingParen = Left;
if (Style.AlignArrayOfStructures != FormatStyle::AIAS_None) {
if (Left->ParentBracket == tok::l_brace &&
- couldBeInStructArrayInitializer() && CommaCount > 0) {
+ couldBeInStructArrayInitializer() && CommaCount > 0)
Contexts.back().InStructArrayInitializer = true;
- }
}
next();
return true;
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);
return LT_ObjCMethodDecl;
}
- for (const auto &ctx : Contexts) {
+ for (const auto &ctx : Contexts)
if (ctx.InStructArrayInitializer)
return LT_ArrayOfStructInitializer;
- }
return LT_Other;
}
Style.Language != FormatStyle::LK_TextProto)) {
Current.setType(TT_BinaryOperator);
} else if (Current.is(tok::comment)) {
- if (Current.TokenText.startswith("/*")) {
+ if (Current.TokenText.startswith("/*"))
if (Current.TokenText.endswith("*/"))
Current.setType(TT_BlockComment);
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::r_paren)) {
if (rParenEndsCast(Current))
Current.setType(TT_CastRParen);
Current.setType(TT_DesignatedInitializerPeriod);
else if (Style.Language == FormatStyle::LK_Java && Current.Previous &&
Current.Previous->isOneOf(TT_JavaAnnotation,
- TT_LeadingJavaAnnotation)) {
+ TT_LeadingJavaAnnotation))
Current.setType(Current.Previous->getType());
- }
} else if (canBeObjCSelectorComponent(Current) &&
// FIXME(bug 36976): ObjC return types shouldn't use
// TT_CastRParen.
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;
}
(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 {}
if (Current->opensScope()) {
}
void parseConditionalExpr() {
- while (Current && Current->isTrailingComment()) {
+ while (Current && Current->isTrailingComment())
next();
- }
FormatToken *Start = Current;
parse(prec::LogicalOr);
if (!Current || !Current->is(tok::question))
Current->Role->precomputeFormattingInfos(Current);
if (Current->MatchingParen &&
Current->MatchingParen->opensBlockOrBlockTypeList(Style) &&
- IndentLevel > 0) {
+ IndentLevel > 0)
--IndentLevel;
- }
Current->IndentLevel = IndentLevel;
if (Current->opensBlockOrBlockTypeList(Style))
++IndentLevel;
}
void TokenAnnotator::calculateArrayInitializerColumnList(AnnotatedLine &Line) {
- if (Line.First == Line.Last) {
+ if (Line.First == Line.Last)
return;
- }
auto *CurrentToken = Line.First;
CurrentToken->ArrayInitializerLineStart = true;
unsigned Depth = 0;
return true;
}
// `foo as const;` casts into a const type.
- if (Left.endsSequence(tok::kw_const, Keywords.kw_as)) {
+ if (Left.endsSequence(tok::kw_const, Keywords.kw_as))
return false;
- }
if ((Left.isOneOf(Keywords.kw_let, Keywords.kw_var, Keywords.kw_in,
tok::kw_const) ||
// "of" is only a keyword if it appears after another identifier
}
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()) &&
if (Line.First->is(TT_CSharpGenericTypeConstraint))
return Left.is(TT_CSharpGenericTypeConstraintComma);
// Keep nullable operators attached to their identifiers.
- if (Right.is(TT_CSharpNullable)) {
+ if (Right.is(TT_CSharpNullable))
return false;
- }
} else if (Style.Language == FormatStyle::LK_Java) {
if (Left.isOneOf(Keywords.kw_throws, Keywords.kw_extends,
Keywords.kw_implements))
return false;
// Don't split tagged template literal so there is a break between the tag
// identifier and template string.
- if (Left.is(tok::identifier) && Right.is(TT_TemplateString)) {
+ if (Left.is(tok::identifier) && Right.is(TT_TemplateString))
return false;
- }
if (Left.is(TT_TemplateString) && Left.opensScope())
return true;
}
: 0;
if (Tok && Tok->is(tok::kw_template) &&
- Style.BraceWrapping.SplitEmptyRecord && EmptyBlock) {
+ Style.BraceWrapping.SplitEmptyRecord && EmptyBlock)
return 0;
- }
}
auto ShouldMergeShortFunctions =
}
// Try to merge a function block with left brace unwrapped
- if (TheLine->Last->is(TT_FunctionLBrace) &&
- TheLine->First != TheLine->Last) {
+ if (TheLine->Last->is(TT_FunctionLBrace) && TheLine->First != TheLine->Last)
return MergeShortFunctions ? tryMergeSimpleBlock(I, E, Limit) : 0;
- }
// Try to merge a control statement block with left brace unwrapped
if (TheLine->Last->is(tok::l_brace) && TheLine->First != TheLine->Last &&
TheLine->First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_for,
: 0;
}
if (TheLine->InPPDirective &&
- (TheLine->First->HasUnescapedNewline || TheLine->First->IsFirst)) {
+ (TheLine->First->HasUnescapedNewline || TheLine->First->IsFirst))
return tryMergeSimplePPDirective(I, E, Limit);
- }
return 0;
}
SmallVectorImpl<AnnotatedLine *>::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;
}
}
bool containsMustBreak(const AnnotatedLine *Line) {
- for (const FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
+ for (const FormatToken *Tok = Line->First; Tok; Tok = Tok->Next)
if (Tok->MustBreakBefore)
return true;
- }
return false;
}
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;
}
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";
- }
});
}
}
}
~ScopedLineState() {
- if (!Parser.Line->Tokens.empty()) {
+ if (!Parser.Line->Tokens.empty())
Parser.addUnwrappedLine();
- }
assert(Parser.Line->Tokens.empty());
Parser.Line = std::move(PreBlockLine);
if (Parser.CurrentLines == &Parser.PreprocessorDirectives)
bool SwitchLabelEncountered = false;
do {
tok::TokenKind kind = FormatTok->Tok.getKind();
- if (FormatTok->getType() == TT_MacroBlockBegin) {
+ if (FormatTok->getType() == TT_MacroBlockBegin)
kind = tok::l_brace;
- } else if (FormatTok->getType() == TT_MacroBlockEnd) {
+ else if (FormatTok->getType() == TT_MacroBlockEnd)
kind = tok::r_brace;
- }
switch (kind) {
case tok::comment:
return false;
if (FormatTok->isNot(tok::r_brace) || StatementCount != 1 ||
IsPrecededByCommentOrPPDirective ||
- precededByCommentOrPPDirective()) {
+ precededByCommentOrPPDirective())
return false;
- }
const FormatToken *Next = Tokens->peekNextToken();
if (Next->is(tok::comment) && Next->NewlinesBefore == 0)
return false;
} while (Tok->Tok.isNot(tok::eof) && !LBraceStack.empty());
// Assume other blocks for all unclosed opening braces.
- for (FormatToken *LBrace : LBraceStack) {
+ for (FormatToken *LBrace : LBraceStack)
if (LBrace->is(BK_Unknown))
LBrace->setBlockKind(BK_Block);
- }
FormatTok = Tokens->setPosition(StoredPosition);
}
void UnwrappedLineParser::conditionalCompilationEnd() {
assert(PPBranchLevel < (int)PPLevelBranchIndex.size());
if (PPBranchLevel >= 0 && !PPChainBranchIndex.empty()) {
- if (PPChainBranchIndex.top() + 1 > PPLevelBranchCount[PPBranchLevel]) {
+ if (PPChainBranchIndex.top() + 1 > PPLevelBranchCount[PPBranchLevel])
PPLevelBranchCount[PPBranchLevel] = PPChainBranchIndex.top() + 1;
- }
}
// Guard against #endif's without #if.
if (PPBranchLevel > -1)
nextToken();
if (FormatTok->Tok.getKind() == tok::l_paren &&
- !FormatTok->hasWhitespaceBefore()) {
+ !FormatTok->hasWhitespaceBefore())
parseParens();
- }
if (Style.IndentPPDirectives != FormatStyle::PPDIS_None)
Line->Level += PPBranchLevel + 1;
addUnwrappedLine();
case tok::kw_struct:
case tok::kw_union:
case tok::kw_class:
- if (parseStructLike()) {
+ if (parseStructLike())
return;
- }
break;
case tok::period:
nextToken();
}
if (FormatTok->is(Keywords.kw_interface)) {
- if (parseStructLike()) {
+ if (parseStructLike())
return;
- }
break;
}
return false;
}
nextToken();
- if (FormatTok->is(tok::l_square)) {
+ if (FormatTok->is(tok::l_square))
return false;
- }
parseSquare(/*LambdaIntroducer=*/true);
return true;
}
}
}
// Parse try with resource.
- if (Style.Language == FormatStyle::LK_Java && FormatTok->is(tok::l_paren)) {
+ if (Style.Language == FormatStyle::LK_Java && FormatTok->is(tok::l_paren))
parseParens();
- }
keepAncestorBraces();
if (FormatTok->is(tok::l_brace)) {
CompoundStatementIndenter Indenter(this, Style, Line->Level);
parseBlock();
- if (Style.BraceWrapping.BeforeCatch) {
+ if (Style.BraceWrapping.BeforeCatch)
addUnwrappedLine();
- } else {
+ else
NeedsUnwrappedLine = true;
- }
} else if (!FormatTok->is(tok::kw_catch)) {
// The C++ standard requires a compound-statement after a try.
// If there's none, we try to assume there's a structuralElement
} else {
while (FormatTok->isOneOf(tok::identifier, tok::coloncolon, tok::kw_inline,
tok::l_square, tok::period) ||
- (Style.isCSharp() && FormatTok->is(tok::kw_union))) {
+ (Style.isCSharp() && FormatTok->is(tok::kw_union)))
if (FormatTok->is(tok::l_square))
parseSquare();
else
nextToken();
- }
}
if (FormatTok->Tok.is(tok::l_brace)) {
if (ShouldBreakBeforeBrace(Style, InitialToken))
FormatStyle::BWACS_Always) {
addUnwrappedLine();
if (!Style.IndentCaseBlocks &&
- Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths) {
+ Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths)
++Line->Level;
- }
}
parseStructuralElement();
}
}
nextToken();
}
- if (FormatTok->Tok.is(tok::kw_requires)) {
+ if (FormatTok->Tok.is(tok::kw_requires))
parseRequiresExpression(OriginalLevel);
- }
if (FormatTok->Tok.is(tok::less)) {
parseBracedList(/*ContinueOnSemicolons=*/false, /*IsEnum=*/false,
/*ClosingBraceKind=*/tok::greater);
}
- if (FormatTok->Tok.is(tok::l_paren)) {
+ if (FormatTok->Tok.is(tok::l_paren))
parseParens();
- }
if (FormatTok->Tok.is(tok::l_brace)) {
if (Style.BraceWrapping.AfterFunction)
addUnwrappedLine();
nextToken();
addUnwrappedLine();
}
- if (FormatTok->Tok.is(tok::colon)) {
+ if (FormatTok->Tok.is(tok::colon))
return;
- }
if (!FormatTok->Tok.isOneOf(tok::ampamp, tok::pipepipe)) {
if (FormatTok->Previous &&
!FormatTok->Previous->isOneOf(tok::identifier, tok::kw_requires,
- tok::coloncolon)) {
+ tok::coloncolon))
addUnwrappedLine();
- }
- if (Style.IndentRequires && OriginalLevel != Line->Level) {
+ if (Style.IndentRequires && OriginalLevel != Line->Level)
--Line->Level;
- }
break;
} else {
FormatTok->setType(TT_ConstraintJunctions);
unsigned OriginalLevel = Line->Level;
if (FormatTok->Previous && FormatTok->Previous->is(tok::greater)) {
addUnwrappedLine();
- if (Style.IndentRequires) {
+ if (Style.IndentRequires)
++Line->Level;
- }
}
nextToken();
ScopedTokenPosition AutoPosition(Tokens);
FormatToken *Tok = Tokens->getNextToken();
// We already read the first [ check for the second.
- if (!Tok->is(tok::l_square)) {
+ if (!Tok->is(tok::l_square))
return false;
- }
// Double check that the attribute is just something
// fairly simple.
while (Tok->isNot(tok::eof)) {
- if (Tok->is(tok::r_square)) {
+ if (Tok->is(tok::r_square))
break;
- }
Tok = Tokens->getNextToken();
}
if (Tok->is(tok::eof))
return false;
Tok = Tokens->getNextToken();
- if (!Tok->is(tok::r_square)) {
+ if (!Tok->is(tok::r_square))
return false;
- }
Tok = Tokens->getNextToken();
- if (Tok->is(tok::semi)) {
+ if (Tok->is(tok::semi))
return false;
- }
return true;
}
// @interface can be followed by a lightweight generic
// specialization list, then either a base class or a category.
- if (FormatTok->Tok.is(tok::less)) {
+ if (FormatTok->Tok.is(tok::less))
parseObjCLightweightGenerics();
- }
if (FormatTok->Tok.is(tok::colon)) {
nextToken();
nextToken(); // base class name
// The base class can also have lightweight generics applied to it.
- if (FormatTok->Tok.is(tok::less)) {
+ if (FormatTok->Tok.is(tok::less))
parseObjCLightweightGenerics();
- }
} else if (FormatTok->Tok.is(tok::l_paren))
// Skip category, if present.
parseParens();
PreviousToken = Node.Tok;
// Grab the last newline preceding a token in this unwrapped line.
- if (Node.Tok->NewlinesBefore > 0) {
+ if (Node.Tok->NewlinesBefore > 0)
MinColumnToken = Node.Tok;
- }
}
- if (PreviousToken && PreviousToken->is(tok::l_brace)) {
+ if (PreviousToken && PreviousToken->is(tok::l_brace))
MinColumnToken = PreviousToken;
- }
return continuesLineComment(FormatTok, /*Previous=*/Line.Tokens.back().Tok,
MinColumnToken);
continuesLineCommentSection(*FormatTok, *Line, CommentPragmasRegex);
}
if (!FormatTok->ContinuesLineCommentSection &&
- (isOnNewLine(*FormatTok) || FormatTok->IsFirst)) {
+ (isOnNewLine(*FormatTok) || FormatTok->IsFirst))
ShouldPushCommentsInCurrentLine = false;
- }
- if (ShouldPushCommentsInCurrentLine) {
+ if (ShouldPushCommentsInCurrentLine)
pushToken(FormatTok);
- } else {
+ else
CommentsBeforeNextToken.push_back(FormatTok);
- }
}
}
while (FormatTok->getType() == TT_ConflictStart ||
FormatTok->getType() == TT_ConflictEnd ||
FormatTok->getType() == TT_ConflictAlternative) {
- if (FormatTok->getType() == TT_ConflictStart) {
+ if (FormatTok->getType() == TT_ConflictStart)
conditionalCompilationStart(/*Unreachable=*/false);
- } else if (FormatTok->getType() == TT_ConflictAlternative) {
+ else if (FormatTok->getType() == TT_ConflictAlternative)
conditionalCompilationAlternative();
- } else if (FormatTok->getType() == TT_ConflictEnd) {
+ else if (FormatTok->getType() == TT_ConflictEnd)
conditionalCompilationEnd();
- }
FormatTok = Tokens->getNextToken();
FormatTok->MustBreakBefore = true;
}
}
if (!PPStack.empty() && (PPStack.back().Kind == PP_Unreachable) &&
- !Line->InPPDirective) {
+ !Line->InPPDirective)
continue;
- }
if (!FormatTok->Tok.is(tok::comment)) {
distributeComments(Comments, FormatTok);
Change.ConditionalsLevel = ConditionalsLevel;
- for (unsigned i = Change.Tok->FakeRParens; i > 0 && ScopeStack.size();
- --i) {
+ for (unsigned i = Change.Tok->FakeRParens; i > 0 && ScopeStack.size(); --i)
if (ScopeStack.pop_back_val())
--ConditionalsLevel;
- }
}
}
LineIsComment = true;
}
- if (!Changes[i].Tok->is(tok::comment)) {
+ if (!Changes[i].Tok->is(tok::comment))
LineIsComment = false;
- }
if (Changes[i].Tok->is(tok::comma)) {
++CommasBeforeMatch;
LineIsComment = true;
}
- if (!Changes[I].Tok->is(tok::comment)) {
+ if (!Changes[I].Tok->is(tok::comment))
LineIsComment = false;
- }
if (!AlignMacrosMatches(Changes[I]))
continue;
// Ensure we keep alignment of wrapped operands with non-wrapped operands
// Since we actually align the operators, the wrapped operands need the
// extra offset to be properly aligned.
- for (Change &C : Changes) {
+ for (Change &C : Changes)
if (AlignWrappedOperand(C))
C.StartOfTokenColumn -= 2;
- }
AlignTokens(
Style,
[this](Change const &C) {
unsigned Column) {
for (unsigned i = Start; i != End; ++i) {
int Shift = 0;
- if (Changes[i].IsTrailingComment) {
+ if (Changes[i].IsTrailingComment)
Shift = Column - Changes[i].StartOfTokenColumn;
- }
if (Changes[i].StartOfBlockComment) {
Shift = Changes[i].IndentationOffset +
Changes[i].StartOfBlockComment->StartOfTokenColumn -
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;
}
return;
// If the line is broken anywhere in there make sure everything
// is aligned to the parent
- for (auto i = Start + 1; i < End; i++) {
+ for (auto i = Start + 1; i < End; i++)
if (Changes[i].NewlinesBefore > 0)
Changes[i].Spaces = Changes[Start].Spaces;
- }
}
WhitespaceManager::CellDescriptions