#include "TokenAnnotator.h"
#include "FormatToken.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Basic/TokenKinds.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/Support/Debug.h"
#define DEBUG_TYPE "format-token-annotator"
namespace clang {
namespace format {
namespace {
static bool startsWithInitStatement(const AnnotatedLine &Line) {
return Line.startsWith(tok::kw_for) || Line.startsWith(tok::kw_if) ||
Line.startsWith(tok::kw_switch);
}
static bool canBeObjCSelectorComponent(const FormatToken &Tok) {
return Tok.Tok.getIdentifierInfo() != nullptr;
}
static bool isLambdaParameterList(const FormatToken *Left) {
if (Left->Previous && Left->Previous->is(tok::greater) &&
Left->Previous->MatchingParen &&
Left->Previous->MatchingParen->is(TT_TemplateOpener)) {
Left = Left->Previous->MatchingParen;
}
return Left->Previous && Left->Previous->is(tok::r_square) &&
Left->Previous->MatchingParen &&
Left->Previous->MatchingParen->is(TT_LambdaLSquare);
}
static bool isKeywordWithCondition(const FormatToken &Tok) {
return Tok.isOneOf(tok::kw_if, tok::kw_for, tok::kw_while, tok::kw_switch,
tok::kw_constexpr, tok::kw_catch);
}
class AnnotatingParser {
public:
AnnotatingParser(const FormatStyle &Style, AnnotatedLine &Line,
const AdditionalKeywords &Keywords)
: Style(Style), Line(Line), CurrentToken(Line.First), AutoFound(false),
Keywords(Keywords) {
Contexts.push_back(Context(tok::unknown, 1, false));
resetTokenMetadata();
}
private:
bool parseAngle() {
if (!CurrentToken || !CurrentToken->Previous)
return false;
if (NonTemplateLess.count(CurrentToken->Previous))
return false;
const FormatToken &Previous = *CurrentToken->Previous; if (Previous.Previous) {
if (Previous.Previous->Tok.isLiteral())
return false;
if (Previous.Previous->is(tok::r_paren) && Contexts.size() > 1 &&
(!Previous.Previous->MatchingParen ||
!Previous.Previous->MatchingParen->is(
TT_OverloadedOperatorLParen))) {
return false;
}
}
FormatToken *Left = CurrentToken->Previous;
Left->ParentBracket = Contexts.back().ContextKind;
ScopedContextCreator ContextCreator(*this, tok::less, 12);
bool InExprContext = Contexts.back().IsExpression;
Contexts.back().IsExpression = false;
if (Left->Previous && Left->Previous->isNot(tok::kw_template))
Contexts.back().ContextType = Context::TemplateArgument;
if (Style.Language == FormatStyle::LK_Java &&
CurrentToken->is(tok::question)) {
next();
}
while (CurrentToken) {
if (CurrentToken->is(tok::greater)) {
if (CurrentToken->Next && CurrentToken->Next->is(tok::greater) &&
Left->ParentBracket != tok::less &&
(isKeywordWithCondition(*Line.First) ||
CurrentToken->getStartOfNonWhitespace() ==
CurrentToken->Next->getStartOfNonWhitespace().getLocWithOffset(
-1))) {
return false;
}
Left->MatchingParen = CurrentToken;
CurrentToken->MatchingParen = Left;
if (Style.Language == FormatStyle::LK_TextProto ||
(Style.Language == FormatStyle::LK_Proto && Left->Previous &&
Left->Previous->isOneOf(TT_SelectorName, TT_DictLiteral))) {
CurrentToken->setType(TT_DictLiteral);
} else {
CurrentToken->setType(TT_TemplateCloser);
}
next();
return true;
}
if (CurrentToken->is(tok::question) &&
Style.Language == FormatStyle::LK_Java) {
next();
continue;
}
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)) {
return false;
}
if (CurrentToken->Previous->isOneOf(tok::pipepipe, tok::ampamp) &&
CurrentToken->Previous->is(TT_BinaryOperator) &&
Contexts[Contexts.size() - 2].IsExpression &&
!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->setType(TT_SelectorName);
}
}
}
if (!consumeToken())
return false;
}
return false;
}
bool parseUntouchableParens() {
while (CurrentToken) {
CurrentToken->Finalized = true;
switch (CurrentToken->Tok.getKind()) {
case tok::l_paren:
next();
if (!parseUntouchableParens())
return false;
continue;
case tok::r_paren:
next();
return true;
default:
break;
}
next();
}
return false;
}
bool parseParens(bool LookForDecls = false) {
if (!CurrentToken)
return false;
assert(CurrentToken->Previous && "Unknown previous token");
FormatToken &OpeningParen = *CurrentToken->Previous;
assert(OpeningParen.is(tok::l_paren));
FormatToken *PrevNonComment = OpeningParen.getPreviousNonComment();
OpeningParen.ParentBracket = Contexts.back().ContextKind;
ScopedContextCreator ContextCreator(*this, tok::l_paren, 1);
Contexts.back().ColonIsForRangeExpr =
Contexts.size() == 2 && Contexts[0].ColonIsForRangeExpr;
if (OpeningParen.Previous &&
OpeningParen.Previous->is(TT_UntouchableMacroFunc)) {
OpeningParen.Finalized = true;
return parseUntouchableParens();
}
bool StartsObjCMethodExpr = false;
if (FormatToken *MaybeSel = OpeningParen.Previous) {
if (MaybeSel->isObjCAtKeyword(tok::objc_selector) && MaybeSel->Previous &&
MaybeSel->Previous->is(tok::at)) {
StartsObjCMethodExpr = true;
}
}
if (OpeningParen.is(TT_OverloadedOperatorLParen)) {
FormatToken *Prev = &OpeningParen;
while (!Prev->is(tok::kw_operator)) {
Prev = Prev->Previous;
assert(Prev && "Expect a kw_operator prior to the OperatorLParen!");
}
bool OperatorCalledAsMemberFunction =
Prev->Previous && Prev->Previous->isOneOf(tok::period, tok::arrow);
Contexts.back().IsExpression = OperatorCalledAsMemberFunction;
} else if (Style.isJavaScript() &&
(Line.startsWith(Keywords.kw_type, tok::identifier) ||
Line.startsWith(tok::kw_export, Keywords.kw_type,
tok::identifier))) {
Contexts.back().IsExpression = false;
} else if (OpeningParen.Previous &&
(OpeningParen.Previous->isOneOf(tok::kw_static_assert,
tok::kw_while, tok::l_paren,
tok::comma, TT_BinaryOperator) ||
OpeningParen.Previous->isIf())) {
Contexts.back().IsExpression = true;
} else if (Style.isJavaScript() && OpeningParen.Previous &&
(OpeningParen.Previous->is(Keywords.kw_function) ||
(OpeningParen.Previous->endsSequence(tok::identifier,
Keywords.kw_function)))) {
Contexts.back().IsExpression = false;
} else if (Style.isJavaScript() && OpeningParen.Previous &&
OpeningParen.Previous->is(TT_JsTypeColon)) {
Contexts.back().IsExpression = false;
} else if (isLambdaParameterList(&OpeningParen)) {
Contexts.back().IsExpression = false;
} else if (Line.InPPDirective &&
(!OpeningParen.Previous ||
!OpeningParen.Previous->is(tok::identifier))) {
Contexts.back().IsExpression = true;
} else if (Contexts[Contexts.size() - 2].CaretFound) {
Contexts.back().IsExpression = false;
} else if (OpeningParen.Previous &&
OpeningParen.Previous->is(TT_ForEachMacro)) {
Contexts.back().ContextType = Context::ForEachMacro;
Contexts.back().IsExpression = false;
} else if (OpeningParen.Previous && OpeningParen.Previous->MatchingParen &&
OpeningParen.Previous->MatchingParen->is(TT_ObjCBlockLParen)) {
Contexts.back().IsExpression = false;
} else if (!Line.MustBeDeclaration && !Line.InPPDirective) {
bool IsForOrCatch =
OpeningParen.Previous &&
OpeningParen.Previous->isOneOf(tok::kw_for, tok::kw_catch);
Contexts.back().IsExpression = !IsForOrCatch;
}
if (PrevNonComment && OpeningParen.is(TT_Unknown)) {
if (PrevNonComment->is(tok::kw___attribute)) {
OpeningParen.setType(TT_AttributeParen);
} else if (PrevNonComment->isOneOf(TT_TypenameMacro, tok::kw_decltype,
tok::kw_typeof, tok::kw__Atomic,
tok::kw___underlying_type)) {
OpeningParen.setType(TT_TypeDeclarationParen);
if (PrevNonComment->isOneOf(tok::kw_decltype, tok::kw_typeof))
Contexts.back().IsExpression = true;
}
}
if (StartsObjCMethodExpr) {
Contexts.back().ColonIsObjCMethodExpr = true;
OpeningParen.setType(TT_ObjCMethodExpr);
}
bool MightBeFunctionType = !Contexts[Contexts.size() - 2].IsExpression;
bool ProbablyFunctionType =
CurrentToken->isOneOf(tok::star, tok::amp, tok::ampamp, tok::caret);
bool HasMultipleLines = false;
bool HasMultipleParametersOnALine = false;
bool MightBeObjCForRangeLoop =
OpeningParen.Previous && OpeningParen.Previous->is(tok::kw_for);
FormatToken *PossibleObjCForInToken = nullptr;
while (CurrentToken) {
if (LookForDecls && CurrentToken->Next) {
FormatToken *Prev = CurrentToken->getPreviousNonComment();
if (Prev) {
FormatToken *PrevPrev = Prev->getPreviousNonComment();
FormatToken *Next = CurrentToken->Next;
if (PrevPrev && PrevPrev->is(tok::identifier) &&
Prev->isOneOf(tok::star, tok::amp, tok::ampamp) &&
CurrentToken->is(tok::identifier) && Next->isNot(tok::equal)) {
Prev->setType(TT_BinaryOperator);
LookForDecls = false;
}
}
}
if (CurrentToken->Previous->is(TT_PointerOrReference) &&
CurrentToken->Previous->Previous->isOneOf(tok::l_paren,
tok::coloncolon)) {
ProbablyFunctionType = true;
}
if (CurrentToken->is(tok::comma))
MightBeFunctionType = false;
if (CurrentToken->Previous->is(TT_BinaryOperator))
Contexts.back().IsExpression = true;
if (CurrentToken->is(tok::r_paren)) {
if (OpeningParen.isNot(TT_CppCastLParen) && MightBeFunctionType &&
ProbablyFunctionType && CurrentToken->Next &&
(CurrentToken->Next->is(tok::l_paren) ||
(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;
if (CurrentToken->Next && CurrentToken->Next->is(tok::l_brace) &&
OpeningParen.Previous && OpeningParen.Previous->is(tok::l_paren)) {
for (FormatToken *Tok = &OpeningParen; Tok != CurrentToken;
Tok = Tok->Next) {
if (Tok->is(TT_BinaryOperator) &&
Tok->isOneOf(tok::star, tok::amp, tok::ampamp)) {
Tok->setType(TT_PointerOrReference);
}
}
}
if (StartsObjCMethodExpr) {
CurrentToken->setType(TT_ObjCMethodExpr);
if (Contexts.back().FirstObjCSelectorName) {
Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
Contexts.back().LongestObjCSelectorName;
}
}
if (OpeningParen.is(TT_AttributeParen))
CurrentToken->setType(TT_AttributeParen);
if (OpeningParen.is(TT_TypeDeclarationParen))
CurrentToken->setType(TT_TypeDeclarationParen);
if (OpeningParen.Previous &&
OpeningParen.Previous->is(TT_JavaAnnotation)) {
CurrentToken->setType(TT_JavaAnnotation);
}
if (OpeningParen.Previous &&
OpeningParen.Previous->is(TT_LeadingJavaAnnotation)) {
CurrentToken->setType(TT_LeadingJavaAnnotation);
}
if (OpeningParen.Previous &&
OpeningParen.Previous->is(TT_AttributeSquare)) {
CurrentToken->setType(TT_AttributeSquare);
}
if (!HasMultipleLines)
OpeningParen.setPackingKind(PPK_Inconclusive);
else if (HasMultipleParametersOnALine)
OpeningParen.setPackingKind(PPK_BinPacked);
else
OpeningParen.setPackingKind(PPK_OnePerLine);
next();
return true;
}
if (CurrentToken->isOneOf(tok::r_square, tok::r_brace))
return false;
if (CurrentToken->is(tok::l_brace) && OpeningParen.is(TT_ObjCBlockLParen))
OpeningParen.setType(TT_Unknown);
if (CurrentToken->is(tok::comma) && CurrentToken->Next &&
!CurrentToken->Next->HasUnescapedNewline &&
!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))) {
Contexts.back().IsExpression = false;
}
if (CurrentToken->isOneOf(tok::semi, tok::colon)) {
MightBeObjCForRangeLoop = false;
if (PossibleObjCForInToken) {
PossibleObjCForInToken->setType(TT_Unknown);
PossibleObjCForInToken = nullptr;
}
}
if (MightBeObjCForRangeLoop && CurrentToken->is(Keywords.kw_in)) {
PossibleObjCForInToken = CurrentToken;
PossibleObjCForInToken->setType(TT_ObjCForIn);
}
if (CurrentToken->is(tok::comma))
Contexts.back().CanBeExpression = true;
FormatToken *Tok = CurrentToken;
if (!consumeToken())
return false;
updateParameterCount(&OpeningParen, Tok);
if (CurrentToken && CurrentToken->HasUnescapedNewline)
HasMultipleLines = true;
}
return false;
}
bool isCSharpAttributeSpecifier(const FormatToken &Tok) {
if (!Style.isCSharp())
return false;
if (Tok.Previous && Tok.Previous->is(tok::identifier))
return false;
if (Tok.Previous && Tok.Previous->is(tok::r_square)) {
auto *MatchingParen = Tok.Previous->MatchingParen;
if (!MatchingParen || MatchingParen->is(TT_ArraySubscriptLSquare))
return false;
}
const FormatToken *AttrTok = Tok.Next;
if (!AttrTok)
return false;
if (AttrTok->is(tok::r_square))
return false;
while (AttrTok && AttrTok->isNot(tok::r_square))
AttrTok = AttrTok->Next;
if (!AttrTok)
return false;
AttrTok = AttrTok->Next;
if (!AttrTok)
return true;
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)) {
return true;
}
if (AttrTok->Next &&
AttrTok->Next->startsSequence(tok::identifier, tok::l_paren)) {
return true;
}
return false;
}
bool isCpp11AttributeSpecifier(const FormatToken &Tok) {
if (!Style.isCpp() || !Tok.startsSequence(tok::l_square, tok::l_square))
return false;
if (Tok.Previous && Tok.Previous->is(tok::at))
return false;
const FormatToken *AttrTok = Tok.Next->Next;
if (!AttrTok)
return false;
if (AttrTok->startsSequence(tok::kw_using, tok::identifier, tok::colon))
return true;
if (AttrTok->isNot(tok::identifier))
return false;
while (AttrTok && !AttrTok->startsSequence(tok::r_square, tok::r_square)) {
if (AttrTok->is(tok::colon) ||
AttrTok->startsSequence(tok::identifier, tok::identifier) ||
AttrTok->startsSequence(tok::r_paren, tok::identifier)) {
return false;
}
if (AttrTok->is(tok::ellipsis))
return true;
AttrTok = AttrTok->Next;
}
return AttrTok && AttrTok->startsSequence(tok::r_square, tok::r_square);
}
bool parseSquare() {
if (!CurrentToken)
return false;
FormatToken *Left = CurrentToken->Previous;
Left->ParentBracket = Contexts.back().ContextKind;
FormatToken *Parent = Left->getPreviousNonComment();
bool CppArrayTemplates =
Style.isCpp() && Parent && Parent->is(TT_TemplateCloser) &&
(Contexts.back().CanBeExpression || Contexts.back().IsExpression ||
Contexts.back().ContextType == Context::TemplateArgument);
bool IsCpp11AttributeSpecifier = isCpp11AttributeSpecifier(*Left) ||
Contexts.back().InCpp11AttributeSpecifier;
bool IsCSharpAttributeSpecifier =
isCSharpAttributeSpecifier(*Left) ||
Contexts.back().InCSharpAttributeSpecifier;
bool InsideInlineASM = Line.startsWith(tok::kw_asm);
bool IsCppStructuredBinding = Left->isCppStructuredBinding(Style);
bool StartsObjCMethodExpr =
!IsCppStructuredBinding && !InsideInlineASM && !CppArrayTemplates &&
Style.isCpp() && !IsCpp11AttributeSpecifier &&
!IsCSharpAttributeSpecifier && Contexts.back().CanBeExpression &&
Left->isNot(TT_LambdaLSquare) &&
!CurrentToken->isOneOf(tok::l_brace, tok::r_square) &&
(!Parent ||
Parent->isOneOf(tok::colon, tok::l_square, tok::l_paren,
tok::kw_return, tok::kw_throw) ||
Parent->isUnaryOperator() ||
Parent->isOneOf(TT_ObjCForIn, TT_CastRParen) ||
(getBinOpPrecedence(Parent->Tok.getKind(), true, true) >
prec::Unknown));
bool ColonFound = false;
unsigned BindingIncrease = 1;
if (IsCppStructuredBinding) {
Left->setType(TT_StructuredBindingLSquare);
} else if (Left->is(TT_Unknown)) {
if (StartsObjCMethodExpr) {
Left->setType(TT_ObjCMethodExpr);
} else if (InsideInlineASM) {
Left->setType(TT_InlineASMSymbolicNameLSquare);
} else if (IsCpp11AttributeSpecifier) {
Left->setType(TT_AttributeSquare);
} else if (Style.isJavaScript() && Parent &&
Contexts.back().ContextKind == tok::l_brace &&
Parent->isOneOf(tok::l_brace, tok::comma)) {
Left->setType(TT_JsComputedPropertyName);
} else if (Style.isCpp() && Contexts.back().ContextKind == tok::l_brace &&
Parent && Parent->isOneOf(tok::l_brace, tok::comma)) {
Left->setType(TT_DesignatedInitializerLSquare);
} else if (IsCSharpAttributeSpecifier) {
Left->setType(TT_AttributeSquare);
} else if (CurrentToken->is(tok::r_square) && Parent &&
Parent->is(TT_TemplateCloser)) {
Left->setType(TT_ArraySubscriptLSquare);
} else if (Style.Language == FormatStyle::LK_Proto ||
Style.Language == FormatStyle::LK_TextProto) {
Left->setType(TT_ArrayInitializerLSquare);
if (!Left->endsSequence(tok::l_square, tok::numeric_constant,
tok::equal) &&
!Left->endsSequence(tok::l_square, tok::numeric_constant,
tok::identifier) &&
!Left->endsSequence(tok::l_square, tok::colon, TT_SelectorName)) {
Left->setType(TT_ProtoExtensionLSquare);
BindingIncrease = 10;
}
} else if (!CppArrayTemplates && Parent &&
Parent->isOneOf(TT_BinaryOperator, TT_TemplateCloser, tok::at,
tok::comma, tok::l_paren, tok::l_square,
tok::question, tok::colon, tok::kw_return,
tok::kw_default)) {
Left->setType(TT_ArrayInitializerLSquare);
} else {
BindingIncrease = 10;
Left->setType(TT_ArraySubscriptLSquare);
}
}
ScopedContextCreator ContextCreator(*this, tok::l_square, BindingIncrease);
Contexts.back().IsExpression = true;
if (Style.isJavaScript() && Parent && Parent->is(TT_JsTypeColon))
Contexts.back().IsExpression = false;
Contexts.back().ColonIsObjCMethodExpr = StartsObjCMethodExpr;
Contexts.back().InCpp11AttributeSpecifier = IsCpp11AttributeSpecifier;
Contexts.back().InCSharpAttributeSpecifier = IsCSharpAttributeSpecifier;
while (CurrentToken) {
if (CurrentToken->is(tok::r_square)) {
if (IsCpp11AttributeSpecifier)
CurrentToken->setType(TT_AttributeSquare);
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)) {
StartsObjCMethodExpr = false;
Left->setType(TT_Unknown);
}
if (StartsObjCMethodExpr && CurrentToken->Previous != Left) {
CurrentToken->setType(TT_ObjCMethodExpr);
if (!ColonFound && CurrentToken->Previous &&
CurrentToken->Previous->is(TT_Unknown) &&
canBeObjCSelectorComponent(*CurrentToken->Previous)) {
CurrentToken->Previous->setType(TT_SelectorName);
}
if (Parent && Parent->is(TT_PointerOrReference))
Parent->overwriteFixedType(TT_BinaryOperator);
}
if (CurrentToken->getType() == TT_ObjCMethodExpr &&
CurrentToken->Next && CurrentToken->Next->is(TT_LambdaArrow)) {
CurrentToken->Next->overwriteFixedType(TT_Unknown);
}
Left->MatchingParen = CurrentToken;
CurrentToken->MatchingParen = Left;
if (!Contexts.back().FirstObjCSelectorName) {
FormatToken *Previous = CurrentToken->getPreviousNonComment();
if (Previous && Previous->is(TT_SelectorName)) {
Previous->ObjCSelectorNameParts = 1;
Contexts.back().FirstObjCSelectorName = Previous;
}
} else {
Left->ParameterCount =
Contexts.back().FirstObjCSelectorName->ObjCSelectorNameParts;
}
if (Contexts.back().FirstObjCSelectorName) {
Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
Contexts.back().LongestObjCSelectorName;
if (Left->BlockParameterCount > 1)
Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName = 0;
}
next();
return true;
}
if (CurrentToken->isOneOf(tok::r_paren, tok::r_brace))
return false;
if (CurrentToken->is(tok::colon)) {
if (IsCpp11AttributeSpecifier &&
CurrentToken->endsSequence(tok::colon, tok::identifier,
tok::kw_using)) {
CurrentToken->setType(TT_AttributeColon);
} else if (Left->isOneOf(TT_ArraySubscriptLSquare,
TT_DesignatedInitializerLSquare)) {
Left->setType(TT_ObjCMethodExpr);
StartsObjCMethodExpr = true;
Contexts.back().ColonIsObjCMethodExpr = true;
if (Parent && Parent->is(tok::r_paren)) {
Parent->setType(TT_CastRParen);
}
}
ColonFound = true;
}
if (CurrentToken->is(tok::comma) && Left->is(TT_ObjCMethodExpr) &&
!ColonFound) {
Left->setType(TT_ArrayInitializerLSquare);
}
FormatToken *Tok = CurrentToken;
if (!consumeToken())
return false;
updateParameterCount(Left, Tok);
}
return false;
}
bool couldBeInStructArrayInitializer() const {
if (Contexts.size() < 2)
return false;
const auto End = std::next(Contexts.rbegin(), 2);
auto Last = Contexts.rbegin();
unsigned Depth = 0;
for (; Last != End; ++Last)
if (Last->ContextKind == tok::l_brace)
++Depth;
return Depth == 2 && Last->ContextKind != tok::l_brace;
}
bool parseBrace() {
if (!CurrentToken)
return true;
assert(CurrentToken->Previous);
FormatToken &OpeningBrace = *CurrentToken->Previous;
assert(OpeningBrace.is(tok::l_brace));
OpeningBrace.ParentBracket = Contexts.back().ContextKind;
if (Contexts.back().CaretFound)
OpeningBrace.overwriteFixedType(TT_ObjCBlockLBrace);
Contexts.back().CaretFound = false;
ScopedContextCreator ContextCreator(*this, tok::l_brace, 1);
Contexts.back().ColonIsDictLiteral = true;
if (OpeningBrace.is(BK_BracedInit))
Contexts.back().IsExpression = true;
if (Style.isJavaScript() && OpeningBrace.Previous &&
OpeningBrace.Previous->is(TT_JsTypeColon)) {
Contexts.back().IsExpression = false;
}
unsigned CommaCount = 0;
while (CurrentToken) {
if (CurrentToken->is(tok::r_brace)) {
assert(OpeningBrace.Optional == CurrentToken->Optional);
OpeningBrace.MatchingParen = CurrentToken;
CurrentToken->MatchingParen = &OpeningBrace;
if (Style.AlignArrayOfStructures != FormatStyle::AIAS_None) {
if (OpeningBrace.ParentBracket == tok::l_brace &&
couldBeInStructArrayInitializer() && CommaCount > 0) {
Contexts.back().ContextType = Context::StructArrayInitializer;
}
}
next();
return true;
}
if (CurrentToken->isOneOf(tok::r_paren, tok::r_square))
return false;
updateParameterCount(&OpeningBrace, CurrentToken);
if (CurrentToken->isOneOf(tok::colon, tok::l_brace, tok::less)) {
FormatToken *Previous = CurrentToken->getPreviousNonComment();
if (Previous->is(TT_JsTypeOptionalQuestion))
Previous = Previous->getPreviousNonComment();
if ((CurrentToken->is(tok::colon) &&
(!Contexts.back().ColonIsDictLiteral || !Style.isCpp())) ||
Style.Language == FormatStyle::LK_Proto ||
Style.Language == FormatStyle::LK_TextProto) {
OpeningBrace.setType(TT_DictLiteral);
if (Previous->Tok.getIdentifierInfo() ||
Previous->is(tok::string_literal)) {
Previous->setType(TT_SelectorName);
}
}
if (CurrentToken->is(tok::colon) && OpeningBrace.is(TT_Unknown))
OpeningBrace.setType(TT_DictLiteral);
else if (Style.isJavaScript())
OpeningBrace.overwriteFixedType(TT_DictLiteral);
}
if (CurrentToken->is(tok::comma)) {
if (Style.isJavaScript())
OpeningBrace.overwriteFixedType(TT_DictLiteral);
++CommaCount;
}
if (!consumeToken())
return false;
}
return true;
}
void updateParameterCount(FormatToken *Left, FormatToken *Current) {
if (Current->is(tok::l_brace) && Current->is(BK_Block))
++Left->BlockParameterCount;
if (Current->is(tok::comma)) {
++Left->ParameterCount;
if (!Left->Role)
Left->Role.reset(new CommaSeparatedList(Style));
Left->Role->CommaFound(Current);
} else if (Left->ParameterCount == 0 && Current->isNot(tok::comment)) {
Left->ParameterCount = 1;
}
}
bool parseConditional() {
while (CurrentToken) {
if (CurrentToken->is(tok::colon)) {
CurrentToken->setType(TT_ConditionalExpr);
next();
return true;
}
if (!consumeToken())
return false;
}
return false;
}
bool parseTemplateDeclaration() {
if (CurrentToken && CurrentToken->is(tok::less)) {
CurrentToken->setType(TT_TemplateOpener);
next();
if (!parseAngle())
return false;
if (CurrentToken)
CurrentToken->Previous->ClosesTemplateDeclaration = true;
return true;
}
return false;
}
bool consumeToken() {
FormatToken *Tok = CurrentToken;
next();
switch (Tok->Tok.getKind()) {
case tok::plus:
case tok::minus:
if (!Tok->Previous && Line.MustBeDeclaration)
Tok->setType(TT_ObjCMethodSpecifier);
break;
case tok::colon:
if (!Tok->Previous)
return false;
if (Style.isJavaScript()) {
if (Contexts.back().ColonIsForRangeExpr || (Contexts.size() == 1 && !Line.First->isOneOf(tok::kw_enum, tok::kw_case)) ||
Contexts.back().ContextKind == tok::l_paren || Contexts.back().ContextKind == tok::l_square || (!Contexts.back().IsExpression &&
Contexts.back().ContextKind == tok::l_brace) || (Contexts.size() == 1 &&
Line.MustBeDeclaration)) { Contexts.back().IsExpression = false;
Tok->setType(TT_JsTypeColon);
break;
}
} else if (Style.isCSharp()) {
if (Contexts.back().InCSharpAttributeSpecifier) {
Tok->setType(TT_AttributeColon);
break;
}
if (Contexts.back().ContextKind == tok::l_paren) {
Tok->setType(TT_CSharpNamedArgumentColon);
break;
}
}
if (Line.First->isOneOf(Keywords.kw_module, Keywords.kw_import) ||
Line.First->startsSequence(tok::kw_export, Keywords.kw_module) ||
Line.First->startsSequence(tok::kw_export, Keywords.kw_import)) {
Tok->setType(TT_ModulePartitionColon);
} else if (Contexts.back().ColonIsDictLiteral ||
Style.Language == FormatStyle::LK_Proto ||
Style.Language == FormatStyle::LK_TextProto) {
Tok->setType(TT_DictLiteral);
if (Style.Language == FormatStyle::LK_TextProto) {
if (FormatToken *Previous = Tok->getPreviousNonComment())
Previous->setType(TT_SelectorName);
}
} else if (Contexts.back().ColonIsObjCMethodExpr ||
Line.startsWith(TT_ObjCMethodSpecifier)) {
Tok->setType(TT_ObjCMethodExpr);
const FormatToken *BeforePrevious = Tok->Previous->Previous;
bool UnknownIdentifierInMethodDeclaration =
Line.startsWith(TT_ObjCMethodSpecifier) &&
Tok->Previous->is(tok::identifier) && Tok->Previous->is(TT_Unknown);
if (!BeforePrevious ||
!(BeforePrevious->is(TT_CastRParen) ||
(BeforePrevious->is(TT_ObjCMethodExpr) &&
BeforePrevious->is(tok::colon))) ||
BeforePrevious->is(tok::r_square) ||
Contexts.back().LongestObjCSelectorName == 0 ||
UnknownIdentifierInMethodDeclaration) {
Tok->Previous->setType(TT_SelectorName);
if (!Contexts.back().FirstObjCSelectorName) {
Contexts.back().FirstObjCSelectorName = Tok->Previous;
} 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;
}
} else if (Contexts.back().ColonIsForRangeExpr) {
Tok->setType(TT_RangeBasedForLoopColon);
} else if (CurrentToken && CurrentToken->is(tok::numeric_constant)) {
Tok->setType(TT_BitFieldColon);
} else if (Contexts.size() == 1 &&
!Line.First->isOneOf(tok::kw_enum, tok::kw_case,
tok::kw_default)) {
FormatToken *Prev = Tok->getPreviousNonComment();
if (!Prev)
break;
if (Prev->isOneOf(tok::r_paren, tok::kw_noexcept) ||
Prev->ClosesRequiresClause) {
Tok->setType(TT_CtorInitializerColon);
} else if (Prev->is(tok::kw_try)) {
FormatToken *PrevPrev = Prev->getPreviousNonComment();
if (!PrevPrev)
break;
if (PrevPrev && PrevPrev->isOneOf(tok::r_paren, tok::kw_noexcept))
Tok->setType(TT_CtorInitializerColon);
} 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 &&
Tok->Next->Next->is(tok::colon)))) {
Tok->setType(TT_ObjCMethodExpr);
} else if (Contexts.back().ContextKind == tok::l_paren) {
Tok->setType(TT_InlineASMColon);
}
break;
case tok::pipe:
case tok::amp:
if (Style.isJavaScript() && !Contexts.back().IsExpression)
Tok->setType(TT_JsTypeOperator);
break;
case tok::kw_if:
if (CurrentToken &&
CurrentToken->isOneOf(tok::kw_constexpr, tok::identifier)) {
next();
}
LLVM_FALLTHROUGH;
case tok::kw_while:
if (CurrentToken && CurrentToken->is(tok::l_paren)) {
next();
if (!parseParens(true))
return false;
}
break;
case tok::kw_for:
if (Style.isJavaScript()) {
if ((Tok->Previous && Tok->Previous->is(tok::period)) ||
(Tok->Next && Tok->Next->is(tok::colon))) {
break;
}
if (CurrentToken && CurrentToken->is(Keywords.kw_await))
next();
}
if (Style.isCpp() && CurrentToken && CurrentToken->is(tok::kw_co_await))
next();
Contexts.back().ColonIsForRangeExpr = true;
if (!CurrentToken || CurrentToken->isNot(tok::l_paren))
return false;
next();
if (!parseParens())
return false;
break;
case tok::l_paren:
if (Tok->Previous && Tok->Previous->is(tok::r_paren) &&
Tok->Previous->MatchingParen &&
Tok->Previous->MatchingParen->is(TT_OverloadedOperatorLParen)) {
Tok->Previous->setType(TT_OverloadedOperator);
Tok->Previous->MatchingParen->setType(TT_OverloadedOperator);
Tok->setType(TT_OverloadedOperatorLParen);
}
if (!parseParens())
return false;
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))) {
Line.MightBeFunctionDecl = true;
}
break;
case tok::l_square:
if (!parseSquare())
return false;
break;
case tok::l_brace:
if (Style.Language == FormatStyle::LK_TextProto) {
FormatToken *Previous = Tok->getPreviousNonComment();
if (Previous && Previous->getType() != TT_DictLiteral)
Previous->setType(TT_SelectorName);
}
if (!parseBrace())
return false;
break;
case tok::less:
if (parseAngle()) {
Tok->setType(TT_TemplateOpener);
if (Style.Language == FormatStyle::LK_TextProto ||
(Style.Language == FormatStyle::LK_Proto && Tok->Previous &&
Tok->Previous->isOneOf(TT_SelectorName, TT_DictLiteral))) {
Tok->setType(TT_DictLiteral);
FormatToken *Previous = Tok->getPreviousNonComment();
if (Previous && Previous->getType() != TT_DictLiteral)
Previous->setType(TT_SelectorName);
}
} else {
Tok->setType(TT_BinaryOperator);
NonTemplateLess.insert(Tok);
CurrentToken = Tok;
next();
}
break;
case tok::r_paren:
case tok::r_square:
return false;
case tok::r_brace:
if (Tok->Previous)
return false;
break;
case tok::greater:
if (Style.Language != FormatStyle::LK_TextProto)
Tok->setType(TT_BinaryOperator);
if (Tok->Previous && Tok->Previous->is(TT_TemplateCloser))
Tok->SpacesRequiredBefore = 1;
break;
case tok::kw_operator:
if (Style.Language == FormatStyle::LK_TextProto ||
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)) {
break;
}
if (CurrentToken && CurrentToken->Previous->isOneOf(
TT_BinaryOperator, TT_UnaryOperator, tok::comma,
tok::star, tok::arrow, tok::amp, tok::ampamp)) {
CurrentToken->Previous->setType(TT_OverloadedOperator);
}
}
if (CurrentToken && CurrentToken->is(tok::l_paren))
CurrentToken->setType(TT_OverloadedOperatorLParen);
if (CurrentToken && CurrentToken->Previous->is(TT_BinaryOperator))
CurrentToken->Previous->setType(TT_OverloadedOperator);
break;
case tok::question:
if (Style.isJavaScript() && Tok->Next &&
Tok->Next->isOneOf(tok::semi, tok::comma, tok::colon, tok::r_paren,
tok::r_brace)) {
Tok->setType(TT_JsTypeOptionalQuestion);
break;
}
if (Line.MustBeDeclaration && !Contexts.back().IsExpression &&
Style.isJavaScript()) {
break;
}
if (Style.isCSharp()) {
if ((!Contexts.back().IsExpression && Line.MustBeDeclaration) ||
(Tok->Next && Tok->Next->isOneOf(tok::r_paren, tok::greater)) ||
(Tok->Next && Tok->Next->is(tok::identifier) && Tok->Next->Next &&
Tok->Next->Next->is(tok::equal))) {
Tok->setType(TT_CSharpNullable);
break;
}
}
parseConditional();
break;
case tok::kw_template:
parseTemplateDeclaration();
break;
case tok::comma:
switch (Contexts.back().ContextType) {
case Context::CtorInitializer:
Tok->setType(TT_CtorInitializerComma);
break;
case Context::InheritanceList:
Tok->setType(TT_InheritanceComma);
break;
default:
if (Contexts.back().FirstStartOfName &&
(Contexts.size() == 1 || startsWithInitStatement(Line))) {
Contexts.back().FirstStartOfName->PartOfMultiVariableDeclStmt = true;
Line.IsMultiVariableDeclStmt = true;
}
break;
}
if (Contexts.back().ContextType == Context::ForEachMacro)
Contexts.back().IsExpression = true;
break;
case tok::identifier:
if (Tok->isOneOf(Keywords.kw___has_include,
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);
parseCSharpGenericTypeConstraint();
}
break;
case tok::arrow:
if (Tok->isNot(TT_LambdaArrow) && Tok->Previous &&
Tok->Previous->is(tok::kw_noexcept)) {
Tok->setType(TT_TrailingReturnArrow);
}
break;
default:
break;
}
return true;
}
void parseCSharpGenericTypeConstraint() {
int OpenAngleBracketsCount = 0;
while (CurrentToken) {
if (CurrentToken->is(tok::less)) {
CurrentToken->setType(TT_TemplateOpener);
++OpenAngleBracketsCount;
next();
} else if (CurrentToken->is(tok::greater)) {
CurrentToken->setType(TT_TemplateCloser);
--OpenAngleBracketsCount;
next();
} else if (CurrentToken->is(tok::comma) && OpenAngleBracketsCount == 0) {
CurrentToken->setType(TT_CSharpGenericTypeConstraintComma);
next();
} else if (CurrentToken->is(Keywords.kw_where)) {
CurrentToken->setType(TT_CSharpGenericTypeConstraint);
next();
} else if (CurrentToken->is(tok::colon)) {
CurrentToken->setType(TT_CSharpGenericTypeConstraintColon);
next();
} else {
next();
}
}
}
void parseIncludeDirective() {
if (CurrentToken && CurrentToken->is(tok::less)) {
next();
while (CurrentToken) {
if (CurrentToken->isNot(tok::comment) &&
!CurrentToken->TokenText.startswith("//")) {
CurrentToken->setType(TT_ImplicitStringLiteral);
}
next();
}
}
}
void parseWarningOrError() {
next();
next();
while (CurrentToken) {
CurrentToken->setType(TT_ImplicitStringLiteral);
next();
}
}
void parsePragma() {
next(); if (CurrentToken &&
CurrentToken->isOneOf(Keywords.kw_mark, Keywords.kw_option,
Keywords.kw_region)) {
bool IsMark = CurrentToken->is(Keywords.kw_mark);
next();
next(); while (CurrentToken) {
if (IsMark || CurrentToken->Previous->is(TT_BinaryOperator))
CurrentToken->setType(TT_ImplicitStringLiteral);
next();
}
}
}
void parseHasInclude() {
if (!CurrentToken || !CurrentToken->is(tok::l_paren))
return;
next(); parseIncludeDirective();
next(); }
LineType parsePreprocessorDirective() {
bool IsFirstToken = CurrentToken->IsFirst;
LineType Type = LT_PreprocessorDirective;
next();
if (!CurrentToken)
return Type;
if (Style.isJavaScript() && IsFirstToken) {
while (CurrentToken) {
CurrentToken->setType(TT_ImplicitStringLiteral);
next();
}
return LT_ImportStatement;
}
if (CurrentToken->is(tok::numeric_constant)) {
CurrentToken->SpacesRequiredBefore = 1;
return Type;
}
if (!CurrentToken->Tok.getIdentifierInfo())
return Type;
if (Style.isVerilog() && !Keywords.isVerilogPPDirective(*CurrentToken))
return LT_Invalid;
switch (CurrentToken->Tok.getIdentifierInfo()->getPPKeywordID()) {
case tok::pp_include:
case tok::pp_include_next:
case tok::pp_import:
next();
parseIncludeDirective();
Type = LT_ImportStatement;
break;
case tok::pp_error:
case tok::pp_warning:
parseWarningOrError();
break;
case tok::pp_pragma:
parsePragma();
break;
case tok::pp_if:
case tok::pp_elif:
Contexts.back().IsExpression = true;
next();
parseLine();
break;
default:
break;
}
while (CurrentToken) {
FormatToken *Tok = CurrentToken;
next();
if (Tok->is(tok::l_paren)) {
parseParens();
} else if (Tok->isOneOf(Keywords.kw___has_include,
Keywords.kw___has_include_next)) {
parseHasInclude();
}
}
return Type;
}
public:
LineType parseLine() {
if (!CurrentToken)
return LT_Invalid;
NonTemplateLess.clear();
if (CurrentToken->is(tok::hash)) {
auto Type = parsePreprocessorDirective();
if (Type != LT_Invalid)
return Type;
}
IdentifierInfo *Info = CurrentToken->Tok.getIdentifierInfo();
if ((Style.Language == FormatStyle::LK_Java &&
CurrentToken->is(Keywords.kw_package)) ||
(Info && Info->getPPKeywordID() == tok::pp_import &&
CurrentToken->Next &&
CurrentToken->Next->isOneOf(tok::string_literal, tok::identifier,
tok::kw_static))) {
next();
parseIncludeDirective();
return LT_ImportStatement;
}
if (CurrentToken->is(tok::less) && Line.Last->is(tok::greater)) {
parseIncludeDirective();
return LT_ImportStatement;
}
if (Style.Language == FormatStyle::LK_Proto && Line.Level == 0 &&
CurrentToken->isOneOf(Keywords.kw_option, Keywords.kw_package)) {
next();
if (CurrentToken && CurrentToken->is(tok::identifier)) {
while (CurrentToken)
next();
return LT_ImportStatement;
}
}
bool KeywordVirtualFound = false;
bool ImportStatement = false;
if (Style.isJavaScript() && CurrentToken->is(Keywords.kw_import))
ImportStatement = true;
while (CurrentToken) {
if (CurrentToken->is(tok::kw_virtual))
KeywordVirtualFound = true;
if (Style.isJavaScript()) {
if (Line.First->is(tok::kw_export) &&
CurrentToken->is(Keywords.kw_from) && CurrentToken->Next &&
CurrentToken->Next->isStringLiteral()) {
ImportStatement = true;
}
if (isClosureImportStatement(*CurrentToken))
ImportStatement = true;
}
if (!consumeToken())
return LT_Invalid;
}
if (KeywordVirtualFound)
return LT_VirtualFunctionDecl;
if (ImportStatement)
return LT_ImportStatement;
if (Line.startsWith(TT_ObjCMethodSpecifier)) {
if (Contexts.back().FirstObjCSelectorName) {
Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName =
Contexts.back().LongestObjCSelectorName;
}
return LT_ObjCMethodDecl;
}
for (const auto &ctx : Contexts)
if (ctx.ContextType == Context::StructArrayInitializer)
return LT_ArrayOfStructInitializer;
return LT_Other;
}
private:
bool isClosureImportStatement(const FormatToken &Tok) {
return Tok.TokenText == "goog" && Tok.Next && Tok.Next->is(tok::period) &&
Tok.Next->Next &&
(Tok.Next->Next->TokenText == "module" ||
Tok.Next->Next->TokenText == "provide" ||
Tok.Next->Next->TokenText == "require" ||
Tok.Next->Next->TokenText == "requireType" ||
Tok.Next->Next->TokenText == "forwardDeclare") &&
Tok.Next->Next->Next && Tok.Next->Next->Next->is(tok::l_paren);
}
void resetTokenMetadata() {
if (!CurrentToken)
return;
if (!CurrentToken->isTypeFinalized() &&
!CurrentToken->isOneOf(
TT_LambdaLSquare, TT_LambdaLBrace, TT_AttributeMacro, TT_IfMacro,
TT_ForEachMacro, TT_TypenameMacro, TT_FunctionLBrace,
TT_ImplicitStringLiteral, TT_InlineASMBrace, TT_FatArrow,
TT_LambdaArrow, TT_NamespaceMacro, TT_OverloadedOperator,
TT_RegexLiteral, TT_TemplateString, TT_ObjCStringLiteral,
TT_UntouchableMacroFunc, TT_StatementAttributeLikeMacro,
TT_FunctionLikeOrFreestandingMacro, TT_ClassLBrace, TT_EnumLBrace,
TT_RecordLBrace, TT_StructLBrace, TT_UnionLBrace, TT_RequiresClause,
TT_RequiresClauseInARequiresExpression, TT_RequiresExpression,
TT_RequiresExpressionLParen, TT_RequiresExpressionLBrace,
TT_CompoundRequirementLBrace, TT_BracedListLBrace)) {
CurrentToken->setType(TT_Unknown);
}
CurrentToken->Role.reset();
CurrentToken->MatchingParen = nullptr;
CurrentToken->FakeLParens.clear();
CurrentToken->FakeRParens = 0;
}
void next() {
if (!CurrentToken)
return;
CurrentToken->NestingLevel = Contexts.size() - 1;
CurrentToken->BindingStrength = Contexts.back().BindingStrength;
modifyContext(*CurrentToken);
determineTokenType(*CurrentToken);
CurrentToken = CurrentToken->Next;
resetTokenMetadata();
}
struct Context {
Context(tok::TokenKind ContextKind, unsigned BindingStrength,
bool IsExpression)
: ContextKind(ContextKind), BindingStrength(BindingStrength),
IsExpression(IsExpression) {}
tok::TokenKind ContextKind;
unsigned BindingStrength;
bool IsExpression;
unsigned LongestObjCSelectorName = 0;
bool ColonIsForRangeExpr = false;
bool ColonIsDictLiteral = false;
bool ColonIsObjCMethodExpr = false;
FormatToken *FirstObjCSelectorName = nullptr;
FormatToken *FirstStartOfName = nullptr;
bool CanBeExpression = true;
bool CaretFound = false;
bool InCpp11AttributeSpecifier = false;
bool InCSharpAttributeSpecifier = false;
enum {
Unknown,
CtorInitializer,
ForEachMacro,
InheritanceList,
StructArrayInitializer,
TemplateArgument,
} ContextType = Unknown;
};
struct ScopedContextCreator {
AnnotatingParser &P;
ScopedContextCreator(AnnotatingParser &P, tok::TokenKind ContextKind,
unsigned Increase)
: P(P) {
P.Contexts.push_back(Context(ContextKind,
P.Contexts.back().BindingStrength + Increase,
P.Contexts.back().IsExpression));
}
~ScopedContextCreator() {
if (P.Style.AlignArrayOfStructures != FormatStyle::AIAS_None) {
if (P.Contexts.back().ContextType == Context::StructArrayInitializer) {
P.Contexts.pop_back();
P.Contexts.back().ContextType = Context::StructArrayInitializer;
return;
}
}
P.Contexts.pop_back();
}
};
void modifyContext(const FormatToken &Current) {
auto AssignmentStartsExpression = [&]() {
if (Current.getPrecedence() != prec::Assignment)
return false;
if (Line.First->isOneOf(tok::kw_using, tok::kw_return))
return false;
if (Line.First->is(tok::kw_template)) {
assert(Current.Previous);
if (Current.Previous->is(tok::kw_operator)) {
return false;
}
const FormatToken *Tok = Line.First->getNextNonComment();
assert(Tok); if (Tok->isNot(TT_TemplateOpener)) {
return false;
}
Tok = Tok->MatchingParen;
if (!Tok)
return false;
Tok = Tok->getNextNonComment();
if (!Tok)
return false;
if (Tok->isOneOf(tok::kw_class, tok::kw_enum, tok::kw_concept,
tok::kw_struct, tok::kw_using)) {
return false;
}
return true;
}
if (Style.isJavaScript() &&
(Line.startsWith(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);
};
if (AssignmentStartsExpression()) {
Contexts.back().IsExpression = true;
if (!Line.startsWith(TT_UnaryOperator)) {
for (FormatToken *Previous = Current.Previous;
Previous && Previous->Previous &&
!Previous->Previous->isOneOf(tok::comma, tok::semi);
Previous = Previous->Previous) {
if (Previous->isOneOf(tok::r_square, tok::r_paren)) {
Previous = Previous->MatchingParen;
if (!Previous)
break;
}
if (Previous->opensScope())
break;
if (Previous->isOneOf(TT_BinaryOperator, TT_UnaryOperator) &&
Previous->isOneOf(tok::star, tok::amp, tok::ampamp) &&
Previous->Previous && Previous->Previous->isNot(tok::equal)) {
Previous->setType(TT_PointerOrReference);
}
}
}
} else if (Current.is(tok::lessless) &&
(!Current.Previous || !Current.Previous->is(tok::kw_operator))) {
Contexts.back().IsExpression = true;
} else if (Current.isOneOf(tok::kw_return, tok::kw_throw)) {
Contexts.back().IsExpression = true;
} else if (Current.is(TT_TrailingReturnArrow)) {
Contexts.back().IsExpression = false;
} else if (Current.is(TT_LambdaArrow) || Current.is(Keywords.kw_assert)) {
Contexts.back().IsExpression = Style.Language == FormatStyle::LK_Java;
} else if (Current.Previous &&
Current.Previous->is(TT_CtorInitializerColon)) {
Contexts.back().IsExpression = true;
Contexts.back().ContextType = Context::CtorInitializer;
} else if (Current.Previous && Current.Previous->is(TT_InheritanceColon)) {
Contexts.back().ContextType = Context::InheritanceList;
} 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->setType(TT_PointerOrReference);
}
if (Line.MustBeDeclaration &&
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) ||
(Current.is(tok::exclaim) && Current.Previous &&
!Current.Previous->is(tok::kw_operator))) {
Contexts.back().IsExpression = true;
}
}
static FormatToken *untilMatchingParen(FormatToken *Current) {
int ParenLevel = 0;
while (Current) {
if (Current->is(tok::l_paren))
++ParenLevel;
if (Current->is(tok::r_paren))
--ParenLevel;
if (ParenLevel < 1)
break;
Current = Current->Next;
}
return Current;
}
static bool isDeductionGuide(FormatToken &Current) {
if (Current.Previous && Current.Previous->is(tok::r_paren) &&
Current.startsSequence(tok::arrow, tok::identifier, tok::less)) {
FormatToken *TemplateCloser = Current.Next->Next;
int NestingLevel = 0;
while (TemplateCloser) {
if (TemplateCloser->is(tok::l_paren)) {
TemplateCloser = untilMatchingParen(TemplateCloser);
if (!TemplateCloser)
break;
}
if (TemplateCloser->is(tok::less))
++NestingLevel;
if (TemplateCloser->is(tok::greater))
--NestingLevel;
if (NestingLevel < 1)
break;
TemplateCloser = TemplateCloser->Next;
}
if (TemplateCloser && TemplateCloser->Next &&
TemplateCloser->Next->is(tok::semi) &&
Current.Previous->MatchingParen) {
FormatToken *LeadingIdentifier =
Current.Previous->MatchingParen->Previous;
if (LeadingIdentifier) {
FormatToken *PriorLeadingIdentifier = LeadingIdentifier->Previous;
if (PriorLeadingIdentifier &&
PriorLeadingIdentifier->is(tok::kw_explicit)) {
PriorLeadingIdentifier = PriorLeadingIdentifier->Previous;
}
return PriorLeadingIdentifier &&
(PriorLeadingIdentifier->is(TT_TemplateCloser) ||
PriorLeadingIdentifier->ClosesRequiresClause) &&
LeadingIdentifier->TokenText == Current.Next->TokenText;
}
}
}
return false;
}
void determineTokenType(FormatToken &Current) {
if (!Current.is(TT_Unknown)) {
return;
}
if ((Style.isJavaScript() || Style.isCSharp()) &&
Current.is(tok::exclaim)) {
if (Current.Previous) {
bool IsIdentifier =
Style.isJavaScript()
? Keywords.IsJavaScriptIdentifier(
*Current.Previous, true)
: Current.Previous->is(tok::identifier);
if (IsIdentifier ||
Current.Previous->isOneOf(
tok::kw_default, tok::kw_namespace, tok::r_paren, tok::r_square,
tok::r_brace, tok::kw_false, tok::kw_true, Keywords.kw_type,
Keywords.kw_get, Keywords.kw_init, Keywords.kw_set) ||
Current.Previous->Tok.isLiteral()) {
Current.setType(TT_NonNullAssertion);
return;
}
}
if (Current.Next &&
Current.Next->isOneOf(TT_BinaryOperator, Keywords.kw_as)) {
Current.setType(TT_NonNullAssertion);
return;
}
}
if (Current.is(Keywords.kw_instanceof)) {
Current.setType(TT_BinaryOperator);
} else if (isStartOfName(Current) &&
(!Line.MightBeFunctionDecl || Current.NestingLevel != 0)) {
Contexts.back().FirstStartOfName = &Current;
Current.setType(TT_StartOfName);
} else if (Current.is(tok::semi)) {
Contexts.back().FirstStartOfName = nullptr;
} else if (Current.isOneOf(tok::kw_auto, tok::kw___auto_type)) {
AutoFound = true;
} else if (Current.is(tok::arrow) &&
Style.Language == FormatStyle::LK_Java) {
Current.setType(TT_LambdaArrow);
} else if (Current.is(tok::arrow) && AutoFound && Line.MustBeDeclaration &&
Current.NestingLevel == 0 &&
!Current.Previous->isOneOf(tok::kw_operator, tok::identifier)) {
Current.setType(TT_TrailingReturnArrow);
} else if (Current.is(tok::arrow) && Current.Previous &&
Current.Previous->is(tok::r_brace)) {
Current.setType(TT_TrailingReturnArrow);
} else if (isDeductionGuide(Current)) {
Current.setType(TT_TrailingReturnArrow);
} else if (Current.isOneOf(tok::star, tok::amp, tok::ampamp)) {
Current.setType(determineStarAmpUsage(
Current,
Contexts.back().CanBeExpression && Contexts.back().IsExpression,
Contexts.back().ContextType == Context::TemplateArgument));
} else if (Current.isOneOf(tok::minus, tok::plus, tok::caret)) {
Current.setType(determinePlusMinusCaretUsage(Current));
if (Current.is(TT_UnaryOperator) && Current.is(tok::caret))
Contexts.back().CaretFound = true;
} else if (Current.isOneOf(tok::minusminus, tok::plusplus)) {
Current.setType(determineIncrementUsage(Current));
} else if (Current.isOneOf(tok::exclaim, tok::tilde)) {
Current.setType(TT_UnaryOperator);
} else if (Current.is(tok::question)) {
if (Style.isJavaScript() && Line.MustBeDeclaration &&
!Contexts.back().IsExpression) {
Current.setType(TT_JsTypeOptionalQuestion);
} else {
Current.setType(TT_ConditionalExpr);
}
} else if (Current.isBinaryOperator() &&
(!Current.Previous || Current.Previous->isNot(tok::l_square)) &&
(!Current.is(tok::greater) &&
Style.Language != FormatStyle::LK_TextProto)) {
Current.setType(TT_BinaryOperator);
} else if (Current.is(tok::comment)) {
if (Current.TokenText.startswith("/*")) {
if (Current.TokenText.endswith("*/")) {
Current.setType(TT_BlockComment);
} else {
Current.Tok.setKind(tok::unknown);
}
} else {
Current.setType(TT_LineComment);
}
} else if (Current.is(tok::l_paren)) {
if (lParenStartsCppCast(Current))
Current.setType(TT_CppCastLParen);
} else if (Current.is(tok::r_paren)) {
if (rParenEndsCast(Current))
Current.setType(TT_CastRParen);
if (Current.MatchingParen && Current.Next &&
!Current.Next->isBinaryOperator() &&
!Current.Next->isOneOf(tok::semi, tok::colon, tok::l_brace,
tok::comma, tok::period, tok::arrow,
tok::coloncolon)) {
if (FormatToken *AfterParen = Current.MatchingParen->Next) {
if (AfterParen->isNot(tok::caret)) {
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)) {
Current.setType(TT_FunctionAnnotationRParen);
}
}
}
}
}
} else if (Current.is(tok::at) && Current.Next && !Style.isJavaScript() &&
Style.Language != FormatStyle::LK_Java) {
switch (Current.Next->Tok.getObjCKeywordID()) {
case tok::objc_interface:
case tok::objc_implementation:
case tok::objc_protocol:
Current.setType(TT_ObjCDecl);
break;
case tok::objc_property:
Current.setType(TT_ObjCProperty);
break;
default:
break;
}
} else if (Current.is(tok::period)) {
FormatToken *PreviousNoComment = Current.getPreviousNonComment();
if (PreviousNoComment &&
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)) {
Current.setType(Current.Previous->getType());
}
} else if (canBeObjCSelectorComponent(Current) &&
Current.Previous && Current.Previous->is(TT_CastRParen) &&
Current.Previous->MatchingParen &&
Current.Previous->MatchingParen->Previous &&
Current.Previous->MatchingParen->Previous->is(
TT_ObjCMethodSpecifier)) {
Current.setType(TT_SelectorName);
} else if (Current.isOneOf(tok::identifier, tok::kw_const, tok::kw_noexcept,
tok::kw_requires) &&
Current.Previous &&
!Current.Previous->isOneOf(tok::equal, tok::at) &&
Line.MightBeFunctionDecl && Contexts.size() == 1) {
Current.setType(TT_TrailingAnnotation);
} else if ((Style.Language == FormatStyle::LK_Java ||
Style.isJavaScript()) &&
Current.Previous) {
if (Current.Previous->is(tok::at) &&
Current.isNot(Keywords.kw_interface)) {
const FormatToken &AtToken = *Current.Previous;
const FormatToken *Previous = AtToken.getPreviousNonComment();
if (!Previous || Previous->is(TT_LeadingJavaAnnotation))
Current.setType(TT_LeadingJavaAnnotation);
else
Current.setType(TT_JavaAnnotation);
} else if (Current.Previous->is(tok::period) &&
Current.Previous->isOneOf(TT_JavaAnnotation,
TT_LeadingJavaAnnotation)) {
Current.setType(Current.Previous->getType());
}
}
}
bool isStartOfName(const FormatToken &Tok) {
if (Tok.isNot(tok::identifier) || !Tok.Previous)
return false;
if (Tok.Previous->isOneOf(TT_LeadingJavaAnnotation, Keywords.kw_instanceof,
Keywords.kw_as)) {
return false;
}
if (Style.isJavaScript() && Tok.Previous->is(Keywords.kw_in))
return false;
FormatToken *PreviousNotConst = Tok.getPreviousNonComment();
if (!Style.isJavaScript())
while (PreviousNotConst && PreviousNotConst->is(tok::kw_const))
PreviousNotConst = PreviousNotConst->getPreviousNonComment();
if (!PreviousNotConst)
return false;
if (PreviousNotConst->ClosesRequiresClause)
return false;
bool IsPPKeyword = PreviousNotConst->is(tok::identifier) &&
PreviousNotConst->Previous &&
PreviousNotConst->Previous->is(tok::hash);
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)) {
return true;
}
if (IsPPKeyword)
return false;
if (PreviousNotConst->isOneOf(tok::identifier, tok::kw_auto))
return true;
if (PreviousNotConst->is(TT_PointerOrReference))
return true;
if (PreviousNotConst->isSimpleTypeSpecifier())
return true;
return Style.isJavaScript() && PreviousNotConst->is(tok::kw_const);
}
bool lParenStartsCppCast(const FormatToken &Tok) {
if (!Style.isCpp())
return false;
FormatToken *LeftOfParens = Tok.getPreviousNonComment();
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)) {
return true;
}
}
return false;
}
bool rParenEndsCast(const FormatToken &Tok) {
if (!Style.isCSharp() && !Style.isCpp() &&
Style.Language != FormatStyle::LK_Java) {
return false;
}
if (Tok.Previous == Tok.MatchingParen || !Tok.Next || !Tok.MatchingParen)
return false;
FormatToken *LeftOfParens = Tok.MatchingParen->getPreviousNonComment();
if (LeftOfParens) {
if (LeftOfParens->is(tok::r_paren) &&
LeftOfParens->isNot(TT_CastRParen)) {
if (!LeftOfParens->MatchingParen ||
!LeftOfParens->MatchingParen->Previous) {
return false;
}
LeftOfParens = LeftOfParens->MatchingParen->Previous;
}
if (LeftOfParens->is(tok::r_square)) {
auto MayBeArrayDelete = [](FormatToken *Tok) -> FormatToken * {
if (Tok->isNot(tok::r_square))
return nullptr;
Tok = Tok->getPreviousNonComment();
if (!Tok || Tok->isNot(tok::l_square))
return nullptr;
Tok = Tok->getPreviousNonComment();
if (!Tok || Tok->isNot(tok::kw_delete))
return nullptr;
return Tok;
};
if (FormatToken *MaybeDelete = MayBeArrayDelete(LeftOfParens))
LeftOfParens = MaybeDelete;
}
if (LeftOfParens->Tok.getIdentifierInfo() && LeftOfParens->Previous &&
LeftOfParens->Previous->is(tok::kw_operator)) {
return false;
}
if (LeftOfParens->Tok.getIdentifierInfo() &&
!LeftOfParens->isOneOf(Keywords.kw_in, tok::kw_return, tok::kw_case,
tok::kw_delete)) {
return false;
}
if (LeftOfParens->isOneOf(tok::at, tok::r_square, TT_OverloadedOperator,
TT_TemplateCloser, tok::ellipsis)) {
return false;
}
}
if (Tok.Next->is(tok::question))
return false;
if (Tok.Next->is(Keywords.kw_in) && Style.isCSharp())
return false;
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)) {
return false;
}
if (Style.Language == FormatStyle::LK_Java && Tok.Next->is(tok::l_paren))
return true;
if (Tok.Next->isNot(tok::string_literal) &&
(Tok.Next->Tok.isLiteral() ||
Tok.Next->isOneOf(tok::kw_sizeof, tok::kw_alignof))) {
return true;
}
auto IsQualifiedPointerOrReference = [](FormatToken *T) {
assert(!T->isSimpleTypeSpecifier() && "Should have already been checked");
while (T) {
if (T->is(TT_AttributeParen)) {
if (T->MatchingParen && T->MatchingParen->Previous &&
T->MatchingParen->Previous->is(tok::kw___attribute)) {
T = T->MatchingParen->Previous->Previous;
continue;
}
} else if (T->is(TT_AttributeSquare)) {
if (T->MatchingParen && T->MatchingParen->Previous) {
T = T->MatchingParen->Previous;
continue;
}
} else if (T->canBePointerOrReferenceQualifier()) {
T = T->Previous;
continue;
}
break;
}
return T && T->is(TT_PointerOrReference);
};
bool ParensAreType =
!Tok.Previous ||
Tok.Previous->isOneOf(TT_TemplateCloser, TT_TypeDeclarationParen) ||
Tok.Previous->isSimpleTypeSpecifier() ||
IsQualifiedPointerOrReference(Tok.Previous);
bool ParensCouldEndDecl =
Tok.Next->isOneOf(tok::equal, tok::semi, tok::l_brace, tok::greater);
if (ParensAreType && !ParensCouldEndDecl)
return true;
if (!LeftOfParens)
return false;
for (const FormatToken *Token = Tok.MatchingParen->Next; Token != &Tok;
Token = Token->Next) {
if (Token->is(TT_BinaryOperator))
return false;
}
if (Tok.Next->isOneOf(tok::identifier, tok::kw_this))
return true;
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)) {
return true;
}
}
if (!Tok.Next->Next)
return false;
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)) {
return false;
}
for (FormatToken *Prev = Tok.Previous; Prev != Tok.MatchingParen;
Prev = Prev->Previous) {
if (!Prev->isOneOf(tok::kw_const, tok::identifier, tok::coloncolon))
return false;
}
return true;
}
bool determineUnaryOperatorByUsage(const FormatToken &Tok) {
const FormatToken *PrevToken = Tok.getPreviousNonComment();
if (!PrevToken)
return true;
if (PrevToken->isOneOf(
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)) {
return true;
}
if (PrevToken->is(tok::kw_sizeof))
return true;
if (PrevToken->isOneOf(TT_CastRParen, TT_UnaryOperator))
return true;
if (PrevToken->is(TT_BinaryOperator))
return true;
return false;
}
TokenType determineStarAmpUsage(const FormatToken &Tok, bool IsExpression,
bool InTemplateArgument) {
if (Style.isJavaScript())
return TT_BinaryOperator;
if (Style.isCSharp() && Tok.is(tok::ampamp))
return TT_BinaryOperator;
const FormatToken *PrevToken = Tok.getPreviousNonComment();
if (!PrevToken)
return TT_UnaryOperator;
const FormatToken *NextToken = Tok.getNextNonComment();
if (InTemplateArgument && NextToken && NextToken->is(tok::kw_noexcept))
return TT_BinaryOperator;
if (!NextToken ||
NextToken->isOneOf(tok::arrow, tok::equal, tok::kw_noexcept) ||
NextToken->canBePointerOrReferenceQualifier() ||
(NextToken->is(tok::l_brace) && !NextToken->getNextNonComment())) {
return TT_PointerOrReference;
}
if (PrevToken->is(tok::coloncolon))
return TT_PointerOrReference;
if (PrevToken->is(tok::r_paren) && PrevToken->is(TT_TypeDeclarationParen))
return TT_PointerOrReference;
if (determineUnaryOperatorByUsage(Tok))
return TT_UnaryOperator;
if (NextToken->is(tok::l_square) && NextToken->isNot(TT_LambdaLSquare))
return TT_PointerOrReference;
if (NextToken->is(tok::kw_operator) && !IsExpression)
return TT_PointerOrReference;
if (NextToken->isOneOf(tok::comma, tok::semi))
return TT_PointerOrReference;
if (PrevToken->is(tok::r_brace) && Tok.is(tok::star) &&
!PrevToken->MatchingParen)
return TT_PointerOrReference;
if (PrevToken->Tok.isLiteral() ||
PrevToken->isOneOf(tok::r_paren, tok::r_square, tok::kw_true,
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())) {
return TT_BinaryOperator;
}
if (InTemplateArgument && NextToken->Tok.isAnyIdentifier())
return TT_BinaryOperator;
if (Tok.is(tok::ampamp) && NextToken->is(tok::l_paren))
return TT_BinaryOperator;
if (NextToken->Tok.isAnyIdentifier()) {
const FormatToken *NextNextToken = NextToken->getNextNonComment();
if (NextNextToken && NextNextToken->is(tok::arrow))
return TT_BinaryOperator;
}
if (IsExpression && !Contexts.back().CaretFound)
return TT_BinaryOperator;
return TT_PointerOrReference;
}
TokenType determinePlusMinusCaretUsage(const FormatToken &Tok) {
if (determineUnaryOperatorByUsage(Tok))
return TT_UnaryOperator;
const FormatToken *PrevToken = Tok.getPreviousNonComment();
if (!PrevToken)
return TT_UnaryOperator;
if (PrevToken->is(tok::at))
return TT_UnaryOperator;
return TT_BinaryOperator;
}
TokenType determineIncrementUsage(const FormatToken &Tok) {
const FormatToken *PrevToken = Tok.getPreviousNonComment();
if (!PrevToken || PrevToken->is(TT_CastRParen))
return TT_UnaryOperator;
if (PrevToken->isOneOf(tok::r_paren, tok::r_square, tok::identifier))
return TT_TrailingUnaryOperator;
return TT_UnaryOperator;
}
SmallVector<Context, 8> Contexts;
const FormatStyle &Style;
AnnotatedLine &Line;
FormatToken *CurrentToken;
bool AutoFound;
const AdditionalKeywords &Keywords;
llvm::SmallPtrSet<FormatToken *, 16> NonTemplateLess;
};
static const int PrecedenceUnaryOperator = prec::PointerToMember + 1;
static const int PrecedenceArrowAndPeriod = prec::PointerToMember + 2;
class ExpressionParser {
public:
ExpressionParser(const FormatStyle &Style, const AdditionalKeywords &Keywords,
AnnotatedLine &Line)
: Style(Style), Keywords(Keywords), Line(Line), Current(Line.First) {}
void parse(int Precedence = 0) {
while (Current && (Current->is(tok::kw_return) ||
(Current->is(tok::colon) &&
Current->isOneOf(TT_ObjCMethodExpr, TT_DictLiteral)))) {
next();
}
if (!Current || Precedence > PrecedenceArrowAndPeriod)
return;
if (Precedence == prec::Conditional) {
parseConditionalExpr();
return;
}
if (Precedence == PrecedenceUnaryOperator) {
parseUnaryOperator();
return;
}
FormatToken *Start = Current;
FormatToken *LatestOperator = nullptr;
unsigned OperatorIndex = 0;
while (Current) {
parse(Precedence + 1);
int CurrentPrecedence = getCurrentPrecedence();
if (Precedence == CurrentPrecedence && Current &&
Current->is(TT_SelectorName)) {
if (LatestOperator)
addFakeParenthesis(Start, prec::Level(Precedence));
Start = Current;
}
if (!Current ||
(Current->closesScope() &&
(Current->MatchingParen || Current->is(TT_TemplateString))) ||
(CurrentPrecedence != -1 && CurrentPrecedence < Precedence) ||
(CurrentPrecedence == prec::Conditional &&
Precedence == prec::Assignment && Current->is(tok::colon))) {
break;
}
if (Current->opensScope() ||
Current->isOneOf(TT_RequiresClause,
TT_RequiresClauseInARequiresExpression)) {
while (Current && (!Current->closesScope() || Current->opensScope())) {
next();
parse();
}
next();
} else {
if (CurrentPrecedence == Precedence) {
if (LatestOperator)
LatestOperator->NextOperator = Current;
LatestOperator = Current;
Current->OperatorIndex = OperatorIndex;
++OperatorIndex;
}
next(Precedence > 0);
}
}
if (LatestOperator && (Current || Precedence > 0)) {
auto End =
(Start->Previous &&
Start->Previous->isOneOf(TT_RequiresClause,
TT_RequiresClauseInARequiresExpression))
? [this](){
auto Ret = Current ? Current : Line.Last;
while (!Ret->ClosesRequiresClause && Ret->Previous)
Ret = Ret->Previous;
return Ret;
}()
: nullptr;
if (Precedence == PrecedenceArrowAndPeriod) {
addFakeParenthesis(Start, prec::Unknown, End);
} else {
addFakeParenthesis(Start, prec::Level(Precedence), End);
}
}
}
private:
int getCurrentPrecedence() {
if (Current) {
const FormatToken *NextNonComment = Current->getNextNonComment();
if (Current->is(TT_ConditionalExpr))
return prec::Conditional;
if (NextNonComment && Current->is(TT_SelectorName) &&
(NextNonComment->isOneOf(TT_DictLiteral, TT_JsTypeColon) ||
((Style.Language == FormatStyle::LK_Proto ||
Style.Language == FormatStyle::LK_TextProto) &&
NextNonComment->is(tok::less)))) {
return prec::Assignment;
}
if (Current->is(TT_JsComputedPropertyName))
return prec::Assignment;
if (Current->is(TT_LambdaArrow))
return prec::Comma;
if (Current->is(TT_FatArrow))
return prec::Assignment;
if (Current->isOneOf(tok::semi, TT_InlineASMColon, TT_SelectorName) ||
(Current->is(tok::comment) && NextNonComment &&
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)) {
return prec::Relational;
}
if (Style.isJavaScript() &&
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)) {
return 0;
}
}
return -1;
}
void addFakeParenthesis(FormatToken *Start, prec::Level Precedence,
FormatToken *End = nullptr) {
Start->FakeLParens.push_back(Precedence);
if (Precedence > prec::Unknown)
Start->StartsBinaryExpression = true;
if (!End && Current)
End = Current->getPreviousNonComment();
if (End) {
++End->FakeRParens;
if (Precedence > prec::Unknown)
End->EndsBinaryExpression = true;
}
}
void parseUnaryOperator() {
llvm::SmallVector<FormatToken *, 2> Tokens;
while (Current && Current->is(TT_UnaryOperator)) {
Tokens.push_back(Current);
next();
}
parse(PrecedenceArrowAndPeriod);
for (FormatToken *Token : llvm::reverse(Tokens)) {
addFakeParenthesis(Token, prec::Unknown);
}
}
void parseConditionalExpr() {
while (Current && Current->isTrailingComment())
next();
FormatToken *Start = Current;
parse(prec::LogicalOr);
if (!Current || !Current->is(tok::question))
return;
next();
parse(prec::Assignment);
if (!Current || Current->isNot(TT_ConditionalExpr))
return;
next();
parse(prec::Assignment);
addFakeParenthesis(Start, prec::Conditional);
}
void next(bool SkipPastLeadingComments = true) {
if (Current)
Current = Current->Next;
while (Current &&
(Current->NewlinesBefore == 0 || SkipPastLeadingComments) &&
Current->isTrailingComment()) {
Current = Current->Next;
}
}
const FormatStyle &Style;
const AdditionalKeywords &Keywords;
const AnnotatedLine &Line;
FormatToken *Current;
};
}
void TokenAnnotator::setCommentLineLevels(
SmallVectorImpl<AnnotatedLine *> &Lines) const {
const AnnotatedLine *NextNonCommentLine = nullptr;
for (AnnotatedLine *Line : llvm::reverse(Lines)) {
assert(Line->First);
if (NextNonCommentLine && Line->isComment() &&
NextNonCommentLine->First->NewlinesBefore <= 1 &&
NextNonCommentLine->First->OriginalColumn ==
Line->First->OriginalColumn) {
Line->Level =
(Style.IndentPPDirectives != FormatStyle::PPDIS_BeforeHash &&
(NextNonCommentLine->Type == LT_PreprocessorDirective ||
NextNonCommentLine->Type == LT_ImportStatement))
? 0
: NextNonCommentLine->Level;
} else {
NextNonCommentLine = Line->First->isNot(tok::r_brace) ? Line : nullptr;
}
setCommentLineLevels(Line->Children);
}
}
static unsigned maxNestingDepth(const AnnotatedLine &Line) {
unsigned Result = 0;
for (const auto *Tok = Line.First; Tok != nullptr; Tok = Tok->Next)
Result = std::max(Result, Tok->NestingLevel);
return Result;
}
void TokenAnnotator::annotate(AnnotatedLine &Line) const {
for (auto &Child : Line.Children)
annotate(*Child);
AnnotatingParser Parser(Style, Line, Keywords);
Line.Type = Parser.parseLine();
if (maxNestingDepth(Line) > 50)
Line.Type = LT_Invalid;
if (Line.Type == LT_Invalid)
return;
ExpressionParser ExprParser(Style, Keywords, Line);
ExprParser.parse();
if (Line.startsWith(TT_ObjCMethodSpecifier))
Line.Type = LT_ObjCMethodDecl;
else if (Line.startsWith(TT_ObjCDecl))
Line.Type = LT_ObjCDecl;
else if (Line.startsWith(TT_ObjCProperty))
Line.Type = LT_ObjCProperty;
Line.First->SpacesRequiredBefore = 1;
Line.First->CanBreakBefore = Line.First->MustBreakBefore;
}
static bool isFunctionDeclarationName(bool IsCpp, const FormatToken &Current,
const AnnotatedLine &Line) {
auto skipOperatorName = [](const FormatToken *Next) -> const FormatToken * {
for (; Next; Next = Next->Next) {
if (Next->is(TT_OverloadedOperatorLParen))
return Next;
if (Next->is(TT_OverloadedOperator))
continue;
if (Next->isOneOf(tok::kw_new, tok::kw_delete)) {
if (Next->Next &&
Next->Next->startsSequence(tok::l_square, tok::r_square)) {
Next = Next->Next->Next;
}
continue;
}
if (Next->startsSequence(tok::l_square, tok::r_square)) {
Next = Next->Next;
continue;
}
if ((Next->isSimpleTypeSpecifier() || Next->is(tok::identifier)) &&
Next->Next && Next->Next->isOneOf(tok::star, tok::amp, tok::ampamp)) {
Next = Next->Next;
continue;
}
if (Next->is(TT_TemplateOpener) && Next->MatchingParen) {
Next = Next->MatchingParen;
continue;
}
break;
}
return nullptr;
};
const FormatToken *Next = Current.Next;
if (Current.is(tok::kw_operator)) {
if (Current.Previous && Current.Previous->is(tok::coloncolon))
return false;
Next = skipOperatorName(Next);
} else {
if (!Current.is(TT_StartOfName) || Current.NestingLevel != 0)
return false;
for (; Next; Next = Next->Next) {
if (Next->is(TT_TemplateOpener)) {
Next = Next->MatchingParen;
} else if (Next->is(tok::coloncolon)) {
Next = Next->Next;
if (!Next)
return false;
if (Next->is(tok::kw_operator)) {
Next = skipOperatorName(Next->Next);
break;
}
if (!Next->is(tok::identifier))
return false;
} else if (Next->is(tok::l_paren)) {
break;
} else {
return false;
}
}
}
if (!Next || !Next->is(tok::l_paren) || !Next->MatchingParen)
return false;
if (Line.Last->is(tok::l_brace))
return true;
if (Next->Next == Next->MatchingParen)
return true; if (Next->MatchingParen->Next &&
Next->MatchingParen->Next->is(TT_PointerOrReference)) {
return true;
}
if (IsCpp && Next->Next && Next->Next->is(tok::identifier) &&
!Line.endsWith(tok::semi)) {
return true;
}
for (const FormatToken *Tok = Next->Next; Tok && Tok != Next->MatchingParen;
Tok = Tok->Next) {
if (Tok->is(TT_TypeDeclarationParen))
return true;
if (Tok->isOneOf(tok::l_paren, TT_TemplateOpener) && Tok->MatchingParen) {
Tok = Tok->MatchingParen;
continue;
}
if (Tok->is(tok::kw_const) || Tok->isSimpleTypeSpecifier() ||
Tok->isOneOf(TT_PointerOrReference, TT_StartOfName, tok::ellipsis)) {
return true;
}
if (Tok->isOneOf(tok::l_brace, tok::string_literal, TT_ObjCMethodExpr) ||
Tok->Tok.isLiteral()) {
return false;
}
}
return false;
}
bool TokenAnnotator::mustBreakForReturnType(const AnnotatedLine &Line) const {
assert(Line.MightBeFunctionDecl);
if ((Style.AlwaysBreakAfterReturnType == FormatStyle::RTBS_TopLevel ||
Style.AlwaysBreakAfterReturnType ==
FormatStyle::RTBS_TopLevelDefinitions) &&
Line.Level > 0) {
return false;
}
switch (Style.AlwaysBreakAfterReturnType) {
case FormatStyle::RTBS_None:
return false;
case FormatStyle::RTBS_All:
case FormatStyle::RTBS_TopLevel:
return true;
case FormatStyle::RTBS_AllDefinitions:
case FormatStyle::RTBS_TopLevelDefinitions:
return Line.mightBeFunctionDefinition();
}
return false;
}
void TokenAnnotator::calculateFormattingInformation(AnnotatedLine &Line) const {
for (AnnotatedLine *ChildLine : Line.Children)
calculateFormattingInformation(*ChildLine);
Line.First->TotalLength =
Line.First->IsMultiline ? Style.ColumnLimit
: Line.FirstStartColumn + Line.First->ColumnWidth;
FormatToken *Current = Line.First->Next;
bool InFunctionDecl = Line.MightBeFunctionDecl;
bool AlignArrayOfStructures =
(Style.AlignArrayOfStructures != FormatStyle::AIAS_None &&
Line.Type == LT_ArrayOfStructInitializer);
if (AlignArrayOfStructures)
calculateArrayInitializerColumnList(Line);
while (Current) {
if (isFunctionDeclarationName(Style.isCpp(), *Current, Line))
Current->setType(TT_FunctionDeclarationName);
const FormatToken *Prev = Current->Previous;
if (Current->is(TT_LineComment)) {
if (Prev->is(BK_BracedInit) && Prev->opensScope()) {
Current->SpacesRequiredBefore =
(Style.Cpp11BracedListStyle && !Style.SpacesInParentheses) ? 0 : 1;
} else {
Current->SpacesRequiredBefore = Style.SpacesBeforeTrailingComments;
}
if (!Current->HasUnescapedNewline) {
for (FormatToken *Parameter = Current->Previous; Parameter;
Parameter = Parameter->Previous) {
if (Parameter->isOneOf(tok::comment, tok::r_brace))
break;
if (Parameter->Previous && Parameter->Previous->is(tok::comma)) {
if (!Parameter->Previous->is(TT_CtorInitializerComma) &&
Parameter->HasUnescapedNewline) {
Parameter->MustBreakBefore = true;
}
break;
}
}
}
} else if (Current->SpacesRequiredBefore == 0 &&
spaceRequiredBefore(Line, *Current)) {
Current->SpacesRequiredBefore = 1;
}
const auto &Children = Prev->Children;
if (!Children.empty() && Children.back()->Last->is(TT_LineComment)) {
Current->MustBreakBefore = true;
} else {
Current->MustBreakBefore =
Current->MustBreakBefore || mustBreakBefore(Line, *Current);
if (!Current->MustBreakBefore && InFunctionDecl &&
Current->is(TT_FunctionDeclarationName)) {
Current->MustBreakBefore = mustBreakForReturnType(Line);
}
}
Current->CanBreakBefore =
Current->MustBreakBefore || canBreakBefore(Line, *Current);
unsigned ChildSize = 0;
if (Prev->Children.size() == 1) {
FormatToken &LastOfChild = *Prev->Children[0]->Last;
ChildSize = LastOfChild.isTrailingComment() ? Style.ColumnLimit
: LastOfChild.TotalLength + 1;
}
if (Current->MustBreakBefore || Prev->Children.size() > 1 ||
(Prev->Children.size() == 1 &&
Prev->Children[0]->First->MustBreakBefore) ||
Current->IsMultiline) {
Current->TotalLength = Prev->TotalLength + Style.ColumnLimit;
} else {
Current->TotalLength = Prev->TotalLength + Current->ColumnWidth +
ChildSize + Current->SpacesRequiredBefore;
}
if (Current->is(TT_CtorInitializerColon))
InFunctionDecl = false;
Current->SplitPenalty = splitPenalty(Line, *Current, InFunctionDecl);
if (Style.Language == FormatStyle::LK_ObjC &&
Current->is(TT_SelectorName) && Current->ParameterIndex > 0) {
if (Current->ParameterIndex == 1)
Current->SplitPenalty += 5 * Current->BindingStrength;
} else {
Current->SplitPenalty += 20 * Current->BindingStrength;
}
Current = Current->Next;
}
calculateUnbreakableTailLengths(Line);
unsigned IndentLevel = Line.Level;
for (Current = Line.First; Current != nullptr; Current = Current->Next) {
if (Current->Role)
Current->Role->precomputeFormattingInfos(Current);
if (Current->MatchingParen &&
Current->MatchingParen->opensBlockOrBlockTypeList(Style) &&
IndentLevel > 0) {
--IndentLevel;
}
Current->IndentLevel = IndentLevel;
if (Current->opensBlockOrBlockTypeList(Style))
++IndentLevel;
}
LLVM_DEBUG({ printDebugInfo(Line); });
}
void TokenAnnotator::calculateUnbreakableTailLengths(
AnnotatedLine &Line) const {
unsigned UnbreakableTailLength = 0;
FormatToken *Current = Line.Last;
while (Current) {
Current->UnbreakableTailLength = UnbreakableTailLength;
if (Current->CanBreakBefore ||
Current->isOneOf(tok::comment, tok::string_literal)) {
UnbreakableTailLength = 0;
} else {
UnbreakableTailLength +=
Current->ColumnWidth + Current->SpacesRequiredBefore;
}
Current = Current->Previous;
}
}
void TokenAnnotator::calculateArrayInitializerColumnList(
AnnotatedLine &Line) const {
if (Line.First == Line.Last)
return;
auto *CurrentToken = Line.First;
CurrentToken->ArrayInitializerLineStart = true;
unsigned Depth = 0;
while (CurrentToken != nullptr && CurrentToken != Line.Last) {
if (CurrentToken->is(tok::l_brace)) {
CurrentToken->IsArrayInitializer = true;
if (CurrentToken->Next != nullptr)
CurrentToken->Next->MustBreakBefore = true;
CurrentToken =
calculateInitializerColumnList(Line, CurrentToken->Next, Depth + 1);
} else {
CurrentToken = CurrentToken->Next;
}
}
}
FormatToken *TokenAnnotator::calculateInitializerColumnList(
AnnotatedLine &Line, FormatToken *CurrentToken, unsigned Depth) const {
while (CurrentToken != nullptr && CurrentToken != Line.Last) {
if (CurrentToken->is(tok::l_brace))
++Depth;
else if (CurrentToken->is(tok::r_brace))
--Depth;
if (Depth == 2 && CurrentToken->isOneOf(tok::l_brace, tok::comma)) {
CurrentToken = CurrentToken->Next;
if (CurrentToken == nullptr)
break;
CurrentToken->StartsColumn = true;
CurrentToken = CurrentToken->Previous;
}
CurrentToken = CurrentToken->Next;
}
return CurrentToken;
}
unsigned TokenAnnotator::splitPenalty(const AnnotatedLine &Line,
const FormatToken &Tok,
bool InFunctionDecl) const {
const FormatToken &Left = *Tok.Previous;
const FormatToken &Right = Tok;
if (Left.is(tok::semi))
return 0;
if (Style.Language == FormatStyle::LK_Java) {
if (Right.isOneOf(Keywords.kw_extends, Keywords.kw_throws))
return 1;
if (Right.is(Keywords.kw_implements))
return 2;
if (Left.is(tok::comma) && Left.NestingLevel == 0)
return 3;
} else if (Style.isJavaScript()) {
if (Right.is(Keywords.kw_function) && Left.isNot(tok::comma))
return 100;
if (Left.is(TT_JsTypeColon))
return 35;
if ((Left.is(TT_TemplateString) && Left.TokenText.endswith("${")) ||
(Right.is(TT_TemplateString) && Right.TokenText.startswith("}"))) {
return 100;
}
if (Left.opensScope() && Right.closesScope())
return 200;
}
if (Right.is(tok::identifier) && Right.Next && Right.Next->is(TT_DictLiteral))
return 1;
if (Right.is(tok::l_square)) {
if (Style.Language == FormatStyle::LK_Proto)
return 1;
if (Left.is(tok::r_square))
return 200;
if (Right.is(TT_LambdaLSquare) && Left.is(tok::equal))
return 35;
if (!Right.isOneOf(TT_ObjCMethodExpr, TT_LambdaLSquare,
TT_ArrayInitializerLSquare,
TT_DesignatedInitializerLSquare, TT_AttributeSquare)) {
return 500;
}
}
if (Left.is(tok::coloncolon) ||
(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)
return 3;
if (Left.is(TT_StartOfName))
return 110;
if (InFunctionDecl && Right.NestingLevel == 0)
return Style.PenaltyReturnTypeOnItsOwnLine;
return 200;
}
if (Right.is(TT_PointerOrReference))
return 190;
if (Right.is(TT_LambdaArrow))
return 110;
if (Left.is(tok::equal) && Right.is(tok::l_brace))
return 160;
if (Left.is(TT_CastRParen))
return 100;
if (Left.isOneOf(tok::kw_class, tok::kw_struct))
return 5000;
if (Left.is(tok::comment))
return 1000;
if (Left.isOneOf(TT_RangeBasedForLoopColon, TT_InheritanceColon,
TT_CtorInitializerColon)) {
return 2;
}
if (Right.isMemberAccess()) {
return !Right.NextOperator || !Right.NextOperator->Previous->closesScope()
? 150
: 35;
}
if (Right.is(TT_TrailingAnnotation) &&
(!Right.Next || Right.Next->isNot(tok::l_paren))) {
if (Line.startsWith(TT_ObjCMethodSpecifier))
return 10;
bool is_short_annotation = Right.TokenText.size() < 10;
return (Left.is(tok::r_paren) ? 100 : 120) + (is_short_annotation ? 50 : 0);
}
if (Line.startsWith(tok::kw_for) && Left.is(tok::equal))
return 4;
if (Right.is(TT_SelectorName))
return 0;
if (Left.is(tok::colon) && Left.is(TT_ObjCMethodExpr))
return Line.MightBeFunctionDecl ? 50 : 500;
if (Line.Type == LT_ObjCDecl && Left.is(tok::l_paren) && Left.Previous &&
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) {
return 100;
}
if (Left.is(tok::l_paren) && Left.Previous &&
(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))
return 1;
if (Left.is(TT_TemplateOpener))
return 100;
if (Left.opensScope()) {
if (Style.AlignAfterOpenBracket == FormatStyle::BAS_DontAlign &&
(Left.ParameterCount <= 1 || Style.AllowAllArgumentsOnNextLine)) {
return 0;
}
if (Left.is(tok::l_brace) && !Style.Cpp11BracedListStyle)
return 19;
return Left.ParameterCount > 1 ? Style.PenaltyBreakBeforeFirstCallParameter
: 19;
}
if (Left.is(TT_JavaAnnotation))
return 50;
if (Left.is(TT_UnaryOperator))
return 60;
if (Left.isOneOf(tok::plus, tok::comma) && Left.Previous &&
Left.Previous->isLabelString() &&
(Left.NextOperator || Left.OperatorIndex != 0)) {
return 50;
}
if (Right.is(tok::plus) && Left.isLabelString() &&
(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)) {
return 25;
}
if (Right.is(tok::lessless)) {
if (!Left.is(tok::r_paren) || Right.OperatorIndex > 0) {
return 2;
}
return 1;
}
if (Left.ClosesTemplateDeclaration)
return Style.PenaltyBreakTemplateDeclaration;
if (Left.ClosesRequiresClause)
return 0;
if (Left.is(TT_ConditionalExpr))
return prec::Conditional;
prec::Level Level = Left.getPrecedence();
if (Level == prec::Unknown)
Level = Right.getPrecedence();
if (Level == prec::Assignment)
return Style.PenaltyBreakAssignment;
if (Level != prec::Unknown)
return Level;
return 3;
}
bool TokenAnnotator::spaceRequiredBeforeParens(const FormatToken &Right) const {
if (Style.SpaceBeforeParens == FormatStyle::SBPO_Always)
return true;
if (Right.is(TT_OverloadedOperatorLParen) &&
Style.SpaceBeforeParensOptions.AfterOverloadedOperator) {
return true;
}
if (Style.SpaceBeforeParensOptions.BeforeNonEmptyParentheses &&
Right.ParameterCount > 0) {
return true;
}
return false;
}
bool TokenAnnotator::spaceRequiredBetween(const AnnotatedLine &Line,
const FormatToken &Left,
const FormatToken &Right) const {
if (Left.is(tok::kw_return) &&
!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) {
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))) {
return Style.SpaceInEmptyParentheses;
}
if (Style.SpacesInConditionalStatement) {
const FormatToken *LeftParen = nullptr;
if (Left.is(tok::l_paren))
LeftParen = &Left;
else if (Right.is(tok::r_paren) && Right.MatchingParen)
LeftParen = Right.MatchingParen;
if (LeftParen && LeftParen->Previous &&
isKeywordWithCondition(*LeftParen->Previous)) {
return true;
}
}
if (Left.is(tok::kw_auto) && Right.isOneOf(tok::l_paren, tok::l_brace))
return false;
if (Right.is(tok::l_paren) && Left.is(tok::kw_co_await) && Left.Previous &&
Left.Previous->is(tok::kw_operator)) {
return false;
}
if (Left.isOneOf(tok::kw_co_await, tok::kw_co_yield, tok::kw_co_return) &&
!Right.isOneOf(tok::semi, tok::r_paren)) {
return true;
}
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) {
bool IsLightweightGeneric = Right.MatchingParen &&
Right.MatchingParen->Next &&
Right.MatchingParen->Next->is(tok::colon);
return !IsLightweightGeneric && Style.ObjCSpaceBeforeProtocolList;
}
if (Right.is(tok::less) && Left.is(tok::kw_template))
return Style.SpaceAfterTemplateKeyword;
if (Left.isOneOf(tok::exclaim, tok::tilde))
return false;
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)) {
return false;
}
if (Left.is(tok::colon))
return !Left.is(TT_ObjCMethodExpr);
if (Left.is(tok::coloncolon))
return false;
if (Left.is(tok::less) || Right.isOneOf(tok::greater, tok::less)) {
if (Style.Language == FormatStyle::LK_TextProto ||
(Style.Language == FormatStyle::LK_Proto &&
(Left.is(TT_DictLiteral) || Right.is(TT_DictLiteral)))) {
if (Left.is(tok::less) && Right.is(tok::greater))
return false;
return !Style.Cpp11BracedListStyle;
}
return false;
}
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)) {
if (Left.is(tok::r_paren) && Line.MightBeFunctionDecl) {
if (!Left.MatchingParen)
return true;
FormatToken *TokenBeforeMatchingParen =
Left.MatchingParen->getPreviousNonComment();
if (!TokenBeforeMatchingParen || !Left.is(TT_TypeDeclarationParen))
return true;
}
if ((Style.SpaceAroundPointerQualifiers == FormatStyle::SAPQ_After ||
Style.SpaceAroundPointerQualifiers == FormatStyle::SAPQ_Both) &&
(Left.is(TT_AttributeParen) ||
Left.canBePointerOrReferenceQualifier())) {
return true;
}
if (Left.Tok.isLiteral())
return true;
if (Left.isTypeOrIdentifier() && Right.Next && Right.Next->Next &&
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 ||
(Line.IsMultiVariableDeclStmt &&
(Left.NestingLevel == 0 ||
(Left.NestingLevel == 1 && startsWithInitStatement(Line)))));
}
if (Right.is(TT_FunctionTypeLParen) && Left.isNot(tok::l_paren) &&
(!Left.is(TT_PointerOrReference) ||
(getTokenPointerOrReferenceAlignment(Left) != FormatStyle::PAS_Right &&
!Line.IsMultiVariableDeclStmt))) {
return true;
}
if (Left.is(TT_PointerOrReference)) {
if ((Style.SpaceAroundPointerQualifiers == FormatStyle::SAPQ_Before ||
Style.SpaceAroundPointerQualifiers == FormatStyle::SAPQ_Both) &&
Right.canBePointerOrReferenceQualifier()) {
return true;
}
if (Right.Tok.isLiteral())
return true;
if (Right.is(TT_BlockComment))
return true;
if (Right.isOneOf(Keywords.kw_override, Keywords.kw_final) &&
!Right.is(TT_StartOfName)) {
return true;
}
if (Right.is(tok::l_brace) && Right.is(BK_Block))
return true;
if (Left.Previous && Left.Previous->isTypeOrIdentifier() && Right.Next &&
Right.Next->is(TT_RangeBasedForLoopColon)) {
return getTokenPointerOrReferenceAlignment(Left) !=
FormatStyle::PAS_Right;
}
if (Right.isOneOf(TT_PointerOrReference, TT_ArraySubscriptLSquare,
tok::l_paren)) {
return false;
}
if (getTokenPointerOrReferenceAlignment(Left) == FormatStyle::PAS_Right)
return false;
if (Line.IsMultiVariableDeclStmt &&
(Left.NestingLevel == Line.First->NestingLevel ||
((Left.NestingLevel == Line.First->NestingLevel + 1) &&
startsWithInitStatement(Line)))) {
return false;
}
return Left.Previous && !Left.Previous->isOneOf(
tok::l_paren, tok::coloncolon, tok::l_square);
}
if (Left.is(tok::ellipsis) && Left.Previous &&
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;
if (Left.is(tok::star) && Right.isOneOf(tok::star, tok::amp, tok::ampamp))
return false;
if (Right.isOneOf(tok::star, tok::amp, tok::ampamp)) {
const FormatToken *Previous = &Left;
while (Previous && !Previous->is(tok::kw_operator)) {
if (Previous->is(tok::identifier) || Previous->isSimpleTypeSpecifier()) {
Previous = Previous->getPreviousNonComment();
continue;
}
if (Previous->is(TT_TemplateCloser) && Previous->MatchingParen) {
Previous = Previous->MatchingParen->getPreviousNonComment();
continue;
}
if (Previous->is(tok::coloncolon)) {
Previous = Previous->getPreviousNonComment();
continue;
}
break;
}
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)) {
return (Style.PointerAlignment != FormatStyle::PAS_Left) ||
(Style.SpaceAroundPointerQualifiers ==
FormatStyle::SAPQ_After) ||
(Style.SpaceAroundPointerQualifiers == FormatStyle::SAPQ_Both);
}
}
}
const auto SpaceRequiredForArrayInitializerLSquare =
[](const FormatToken &LSquareTok, const FormatStyle &Style) {
return Style.SpacesInContainerLiterals ||
((Style.Language == FormatStyle::LK_Proto ||
Style.Language == FormatStyle::LK_TextProto) &&
!Style.Cpp11BracedListStyle &&
LSquareTok.endsSequence(tok::l_square, tok::colon,
TT_SelectorName));
};
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)) {
return Right.MatchingParen &&
((Right.MatchingParen->is(TT_ArrayInitializerLSquare) &&
SpaceRequiredForArrayInitializerLSquare(*Right.MatchingParen,
Style)) ||
(Style.SpacesInSquareBrackets &&
Right.MatchingParen->isOneOf(TT_ArraySubscriptLSquare,
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))) {
return false;
}
if (Left.is(tok::l_brace) && Right.is(tok::r_brace))
return !Left.Children.empty(); if ((Left.is(tok::l_brace) && Left.isNot(BK_Block)) ||
(Right.is(tok::r_brace) && Right.MatchingParen &&
Right.MatchingParen->isNot(BK_Block))) {
return Style.Cpp11BracedListStyle ? Style.SpacesInParentheses : true;
}
if (Left.is(TT_BlockComment)) {
return Style.isJavaScript() || !Left.TokenText.endswith("=*/");
}
if (Left.is(TT_TemplateCloser) && Right.is(TT_AttributeSquare))
return true;
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)) {
return Style.SpaceBeforeParensOptions.AfterRequiresInClause ||
spaceRequiredBeforeParens(Right);
}
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))) {
return true;
}
if (Left.is(TT_ForEachMacro)) {
return Style.SpaceBeforeParensOptions.AfterForeachMacros ||
spaceRequiredBeforeParens(Right);
}
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)) {
return Style.SpaceBeforeParensOptions.AfterControlStatements ||
spaceRequiredBeforeParens(Right);
}
if (Right.is(TT_OverloadedOperatorLParen))
return spaceRequiredBeforeParens(Right);
if (Line.MightBeFunctionDecl && (Left.is(TT_FunctionDeclarationName))) {
if (Line.mightBeFunctionDefinition()) {
return Style.SpaceBeforeParensOptions.AfterFunctionDefinitionName ||
spaceRequiredBeforeParens(Right);
} else {
return Style.SpaceBeforeParensOptions.AfterFunctionDeclarationName ||
spaceRequiredBeforeParens(Right);
}
}
if (Line.Type != LT_PreprocessorDirective && Left.is(tok::r_square) &&
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)) {
return Style.SpaceBeforeParensOptions.AfterControlStatements ||
spaceRequiredBeforeParens(Right);
}
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)) {
return (Style.SpaceBeforeParens != FormatStyle::SBPO_Never) ||
spaceRequiredBeforeParens(Right);
}
}
if (Line.Type != LT_PreprocessorDirective &&
(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)) {
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)) {
return false;
}
if (Left.is(tok::period) || Right.is(tok::period))
return false;
if (Right.is(tok::hash) && Left.is(tok::identifier) &&
(Left.TokenText == "L" || Left.TokenText == "u" ||
Left.TokenText == "U" || Left.TokenText == "u8" ||
Left.TokenText == "LR" || Left.TokenText == "uR" ||
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))) {
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)) {
return false;
}
if (Right.is(tok::r_brace) && Right.MatchingParen &&
Right.MatchingParen->endsSequence(TT_DictLiteral, tok::at)) {
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))) {
return getTokenReferenceAlignment(Right) != FormatStyle::PAS_Left;
}
return true;
}
bool TokenAnnotator::spaceRequiredBefore(const AnnotatedLine &Line,
const FormatToken &Right) const {
const FormatToken &Left = *Right.Previous;
if (Left.Finalized)
return Right.hasWhitespaceBefore();
if (Keywords.isWordLike(Right) && Keywords.isWordLike(Left))
return true;
if (Left.is(tok::star) && Right.is(tok::comment))
return true;
if (Style.isCpp()) {
if (Left.is(Keywords.kw_import) && Right.isOneOf(tok::less, tok::ellipsis))
return true;
if (Left.isOneOf(Keywords.kw_module, Keywords.kw_import) &&
Right.is(TT_ModulePartitionColon)) {
return true;
}
if (Left.is(tok::identifier) && Right.is(TT_ModulePartitionColon))
return false;
if (Left.is(TT_ModulePartitionColon) &&
Right.isOneOf(tok::identifier, tok::kw_private)) {
return false;
}
if (Left.is(tok::ellipsis) && Right.is(tok::identifier) &&
Line.First->is(Keywords.kw_import)) {
return false;
}
if (Left.is(TT_AttributeParen) && Right.is(tok::coloncolon))
return true;
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) {
return true;
}
if (Left.is(tok::less) && Left.is(TT_OverloadedOperator) &&
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)) {
return true;
}
if (Right.is(tok::l_paren) &&
Left.isOneOf(Keywords.kw_returns, Keywords.kw_option)) {
return true;
}
if (Right.isOneOf(tok::l_brace, tok::less) && Left.is(TT_SelectorName))
return true;
if (Left.is(tok::slash) || Right.is(tok::slash))
return false;
if (Left.MatchingParen &&
Left.MatchingParen->is(TT_ProtoExtensionLSquare) &&
Right.isOneOf(tok::l_brace, tok::less)) {
return !Style.Cpp11BracedListStyle;
}
if (Left.is(tok::percent))
return false;
if (Left.is(tok::numeric_constant) && Right.is(tok::percent))
return Right.hasWhitespaceBefore();
} else if (Style.isJson()) {
if (Right.is(tok::colon))
return false;
} else if (Style.isCSharp()) {
if (Left.is(tok::kw_this) && Right.is(tok::l_square))
return false;
if (Left.is(tok::kw_new) && Right.is(tok::l_paren))
return false;
if (Right.is(tok::l_brace))
return true;
if (Left.is(tok::l_brace) && Right.isNot(tok::r_brace))
return true;
if (Left.isNot(tok::l_brace) && Right.is(tok::r_brace))
return true;
if (Left.is(TT_FatArrow) || Right.is(TT_FatArrow))
return true;
if (Left.is(TT_AttributeColon) || Right.is(TT_AttributeColon))
return false;
if (Left.is(TT_TemplateCloser) && Right.is(TT_StartOfName))
return true;
if (Left.is(tok::l_square) || Right.is(tok::r_square))
return Style.SpacesInSquareBrackets;
if (Right.is(TT_CSharpNullable))
return false;
if (Right.is(TT_NonNullAssertion))
return false;
if (Left.is(tok::comma) && Right.is(tok::comma))
return false;
if (Left.is(Keywords.kw_var) && Right.is(tok::l_paren))
return true;
if (Right.is(tok::l_paren)) {
if (Left.isOneOf(tok::kw_using, Keywords.kw_async, Keywords.kw_when,
Keywords.kw_lock)) {
return Style.SpaceBeforeParensOptions.AfterControlStatements ||
spaceRequiredBeforeParens(Right);
}
}
if (Left.isOneOf(tok::kw_public, tok::kw_private, tok::kw_protected,
tok::kw_virtual, tok::kw_extern, tok::kw_static,
Keywords.kw_internal, Keywords.kw_abstract,
Keywords.kw_sealed, Keywords.kw_override,
Keywords.kw_async, Keywords.kw_unsafe) &&
Right.is(tok::l_paren)) {
return true;
}
} else if (Style.isJavaScript()) {
if (Left.is(TT_FatArrow))
return true;
if (Right.is(tok::l_paren) && Left.is(Keywords.kw_await) && Left.Previous &&
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();
if (Next && Next->is(TT_FatArrow))
return true;
}
if ((Left.is(TT_TemplateString) && Left.TokenText.endswith("${")) ||
(Right.is(TT_TemplateString) && Right.TokenText.startswith("}"))) {
return false;
}
if (Keywords.IsJavaScriptIdentifier(Left,
false) &&
Right.is(TT_TemplateString)) {
return false;
}
if (Right.is(tok::star) &&
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)) {
return true;
}
if (Right.is(tok::l_paren)) {
if (Line.MustBeDeclaration && Left.Tok.getIdentifierInfo())
return false;
if (Left.Previous && Left.Previous->is(tok::period) &&
Left.Tok.getIdentifierInfo()) {
return false;
}
if (Left.isOneOf(tok::kw_throw, Keywords.kw_await, Keywords.kw_typeof,
tok::kw_void)) {
return true;
}
}
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) ||
(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))) {
return true;
}
if (Left.isOneOf(tok::kw_for, Keywords.kw_as) && Left.Previous &&
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)) {
return true;
}
if (Left.is(tok::kw_default) && Left.Previous &&
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))
return false;
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)) {
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)) {
return false;
}
if (Right.is(TT_NonNullAssertion))
return false;
if (Left.is(TT_NonNullAssertion) &&
Right.isOneOf(Keywords.kw_as, Keywords.kw_in)) {
return true; }
} 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)) {
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)) {
return true;
}
} else if (Style.isVerilog()) {
if (!Left.is(TT_BinaryOperator) &&
Left.isOneOf(Keywords.kw_verilogHash, Keywords.kw_verilogHashHash)) {
return false;
}
if (!Right.is(tok::semi) &&
(Left.endsSequence(tok::numeric_constant, Keywords.kw_verilogHash) ||
Left.endsSequence(tok::numeric_constant,
Keywords.kw_verilogHashHash) ||
(Left.is(tok::r_paren) && Left.MatchingParen &&
Left.MatchingParen->endsSequence(tok::l_paren, tok::at)))) {
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)) {
return false;
}
}
if (Line.Type == LT_ObjCProperty &&
(Right.is(tok::equal) || Left.is(tok::equal))) {
return false;
}
if (Right.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))
return false;
if (Right.is(TT_ObjCBlockLParen))
return true;
if (Right.is(TT_CtorInitializerColon))
return Style.SpaceBeforeCtorInitializerColon;
if (Right.is(TT_InheritanceColon) && !Style.SpaceBeforeInheritanceColon)
return false;
if (Right.is(TT_RangeBasedForLoopColon) &&
!Style.SpaceBeforeRangeBasedForLoopColon) {
return false;
}
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;
const FormatToken *Next = Right.getNextNonComment();
if (!Next || Next->is(tok::semi))
return false;
if (Right.is(TT_ObjCMethodExpr))
return false;
if (Left.is(tok::question))
return false;
if (Right.is(TT_InlineASMColon) && Left.is(tok::coloncolon))
return false;
if (Right.is(TT_DictLiteral))
return Style.SpacesInContainerLiterals;
if (Right.is(TT_AttributeColon))
return false;
if (Right.is(TT_CSharpNamedArgumentColon))
return false;
if (Right.is(TT_BitFieldColon)) {
return Style.BitFieldColonSpacing == FormatStyle::BFCS_Both ||
Style.BitFieldColonSpacing == FormatStyle::BFCS_Before;
}
return true;
}
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))) {
return true;
}
if (Left.is(TT_UnaryOperator)) {
if (!Right.is(tok::l_paren)) {
if (Left.is(tok::exclaim) && Left.TokenText == "not")
return true;
if (Left.is(tok::tilde) && Left.TokenText == "compl")
return true;
if (Left.is(tok::amp) && Right.is(tok::r_square))
return Style.SpacesInSquareBrackets;
}
return (Style.SpaceAfterLogicalNot && Left.is(tok::exclaim)) ||
Right.is(TT_BinaryOperator);
}
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)
return true;
if (this->Style.SpacesInAngles == FormatStyle::SIAS_Leave)
return Right.hasWhitespaceBefore();
return false;
};
if (Left.is(tok::greater) && Right.is(tok::greater)) {
if (Style.Language == FormatStyle::LK_TextProto ||
(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))) {
return false;
}
if (!Style.SpaceBeforeAssignmentOperators && Left.isNot(TT_TemplateCloser) &&
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))) {
return false;
}
if (Right.is(tok::coloncolon) && Left.is(tok::identifier)) {
return Right.hasWhitespaceBefore();
}
if (Right.is(tok::coloncolon) &&
!Left.isOneOf(tok::l_brace, tok::comment, tok::l_paren)) {
return (Left.is(TT_TemplateOpener) &&
((Style.Standard < FormatStyle::LS_Cpp11) ||
ShouldAddSpacesInAngles())) ||
!(Left.isOneOf(tok::l_paren, tok::r_paren, tok::l_square,
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();
if (Right.is(TT_StructuredBindingLSquare)) {
return !Left.isOneOf(tok::amp, tok::ampamp) ||
getTokenReferenceAlignment(Left) != FormatStyle::PAS_Right;
}
if (Right.Next && Right.Next->is(TT_StructuredBindingLSquare) &&
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))) {
return true;
}
if (Right.is(TT_TemplateOpener) && Left.is(tok::r_paren) &&
Left.MatchingParen &&
Left.MatchingParen->is(TT_OverloadedOperatorLParen)) {
return false;
}
if (Right.is(tok::less) && Left.isNot(tok::l_paren) &&
Line.startsWith(tok::hash)) {
return true;
}
if (Right.is(TT_TrailingUnaryOperator))
return false;
if (Left.is(TT_RegexLiteral))
return false;
return spaceRequiredBetween(Line, Left, Right);
}
static bool isAllmanBrace(const FormatToken &Tok) {
return Tok.is(tok::l_brace) && Tok.is(BK_Block) &&
!Tok.isOneOf(TT_ObjCBlockLBrace, TT_LambdaLBrace, TT_DictLiteral);
}
static bool IsFunctionArgument(const FormatToken &Tok) {
return Tok.MatchingParen && Tok.MatchingParen->Next &&
Tok.MatchingParen->Next->isOneOf(tok::comma, tok::r_paren);
}
static bool
isItAnEmptyLambdaAllowed(const FormatToken &Tok,
FormatStyle::ShortLambdaStyle ShortLambdaOption) {
return Tok.Children.empty() && ShortLambdaOption != FormatStyle::SLS_None;
}
static bool isAllmanLambdaBrace(const FormatToken &Tok) {
return Tok.is(tok::l_brace) && Tok.is(BK_Block) &&
!Tok.isOneOf(TT_ObjCBlockLBrace, TT_DictLiteral);
}
static const FormatToken *getFirstNonComment(const AnnotatedLine &Line) {
const FormatToken *Next = Line.First;
if (!Next)
return Next;
if (Next->is(tok::comment))
Next = Next->getNextNonComment();
return Next;
}
bool TokenAnnotator::mustBreakBefore(const AnnotatedLine &Line,
const FormatToken &Right) const {
const FormatToken &Left = *Right.Previous;
if (Right.NewlinesBefore > 1 && Style.MaxEmptyLinesToKeep > 0)
return true;
if (Style.isCSharp()) {
if (Left.is(TT_FatArrow) && Right.is(tok::l_brace) &&
Style.BraceWrapping.AfterFunction) {
return true;
}
if (Right.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 == "_"))) {
return true;
}
if (Left.is(TT_AttributeSquare) && Left.is(tok::r_square) &&
(Right.isAccessSpecifier(false) ||
Right.is(Keywords.kw_internal))) {
return true;
}
if (Left.is(TT_AttributeSquare) && Right.is(TT_AttributeSquare) &&
Left.is(tok::r_square) && Right.is(tok::l_square)) {
return true;
}
} else if (Style.isJavaScript()) {
if (Right.is(tok::string_literal) && Left.is(tok::plus) && Left.Previous &&
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) &&
!Line.First->isOneOf(Keywords.kw_var, Keywords.kw_let)) {
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))) {
return true;
}
if (Right.is(tok::r_brace) && Left.is(tok::l_brace) && Left.Previous &&
Left.Previous->is(TT_FatArrow)) {
switch (Style.AllowShortLambdasOnASingleLine) {
case FormatStyle::SLS_All:
return false;
case FormatStyle::SLS_None:
return true;
case FormatStyle::SLS_Empty:
return !Left.Children.empty();
case FormatStyle::SLS_Inline:
return (Left.NestingLevel == 0 && Line.Level == 0) &&
!Left.Children.empty();
}
llvm_unreachable("Unknown FormatStyle::ShortLambdaStyle enum");
}
if (Right.is(tok::r_brace) && Left.is(tok::l_brace) &&
!Left.Children.empty()) {
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)) {
return true;
}
} else if (Style.Language == FormatStyle::LK_Cpp ||
Style.Language == FormatStyle::LK_ObjC ||
Style.Language == FormatStyle::LK_Proto ||
Style.Language == FormatStyle::LK_TableGen ||
Style.Language == FormatStyle::LK_TextProto) {
if (Left.isStringLiteral() && Right.isStringLiteral())
return true;
}
if (Style.isJson()) {
if (Left.is(TT_DictLiteral) && Left.is(tok::l_brace))
return true;
if (Left.is(TT_ArrayInitializerLSquare) && Left.is(tok::l_square) &&
!Right.is(tok::r_square)) {
return true;
}
if (Left.is(tok::comma))
return true;
}
if (Style.JavaScriptWrapImports || Line.Type != LT_ImportStatement) {
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) {
BeforeClosingBrace = Left.MatchingParen->Previous;
} 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())) {
return true;
}
}
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)) {
return true;
}
if (Right.is(TT_RequiresClause)) {
switch (Style.RequiresClausePosition) {
case FormatStyle::RCPS_OwnLine:
case FormatStyle::RCPS_WithFollowing:
return true;
default:
break;
}
}
if (Left.ClosesTemplateDeclaration && Left.MatchingParen &&
Left.MatchingParen->NestingLevel == 0) {
if (Right.is(tok::kw_concept))
return Style.BreakBeforeConceptDeclarations == FormatStyle::BBCDS_Always;
return Style.AlwaysBreakTemplateDeclarations == FormatStyle::BTDS_Yes;
}
if (Left.ClosesRequiresClause && Right.isNot(tok::semi)) {
switch (Style.RequiresClausePosition) {
case FormatStyle::RCPS_OwnLine:
case FormatStyle::RCPS_WithPreceding:
return true;
default:
break;
}
}
if (Style.PackConstructorInitializers == FormatStyle::PCIS_Never) {
if (Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeColon &&
(Left.is(TT_CtorInitializerComma) ||
Right.is(TT_CtorInitializerColon))) {
return true;
}
if (Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon &&
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)) {
return true;
}
if (Style.BreakInheritanceList == FormatStyle::BILS_BeforeComma &&
Right.is(TT_InheritanceComma)) {
return true;
}
if (Style.BreakInheritanceList == FormatStyle::BILS_AfterComma &&
Left.is(TT_InheritanceComma)) {
return true;
}
if (Right.is(tok::string_literal) && Right.TokenText.startswith("R\"")) {
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) {
return true;
}
if (Right.is(TT_InlineASMBrace))
return Right.HasUnescapedNewline;
if (isAllmanBrace(Left) || isAllmanBrace(Right)) {
auto FirstNonComment = getFirstNonComment(Line);
bool AccessSpecifier =
FirstNonComment &&
FirstNonComment->isOneOf(Keywords.kw_internal, tok::kw_public,
tok::kw_private, tok::kw_protected);
if (Style.BraceWrapping.AfterEnum) {
if (Line.startsWith(tok::kw_enum) ||
Line.startsWith(tok::kw_typedef, tok::kw_enum)) {
return true;
}
if (AccessSpecifier && FirstNonComment->Next &&
FirstNonComment->Next->is(tok::kw_enum)) {
return true;
}
}
if (Style.BraceWrapping.AfterClass &&
((AccessSpecifier && FirstNonComment->Next &&
FirstNonComment->Next->is(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) {
return true;
}
if (Left.is(TT_AttributeParen) && Right.is(TT_ObjCDecl))
return true;
if (Left.is(TT_LambdaLBrace)) {
if (IsFunctionArgument(Left) &&
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)) {
return true;
}
}
if (Style.BraceWrapping.BeforeLambdaBody && Right.is(TT_LambdaLBrace) &&
Left.isOneOf(tok::star, tok::amp, tok::ampamp, TT_TemplateCloser)) {
return true;
}
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)) {
return true;
}
if (Right.is(TT_ProtoExtensionLSquare))
return true;
if ((Style.Language == FormatStyle::LK_Proto ||
Style.Language == FormatStyle::LK_TextProto) &&
Right.is(TT_SelectorName) && !Right.is(tok::r_square) && Right.Next) {
if (Left.is(tok::at))
return false;
FormatToken *LBrace = Right.Next;
if (LBrace && LBrace->is(tok::colon)) {
LBrace = LBrace->Next;
if (LBrace && LBrace->is(tok::at)) {
LBrace = LBrace->Next;
if (LBrace)
LBrace = LBrace->Next;
}
}
if (LBrace &&
((LBrace->is(tok::l_brace) &&
(LBrace->is(TT_DictLiteral) ||
(LBrace->Next && LBrace->Next->is(tok::r_brace)))) ||
LBrace->is(TT_ArrayInitializerLSquare) || LBrace->is(tok::less))) {
if (Left.ParameterCount == 0)
return true;
}
if (Left.isOneOf(tok::r_brace, tok::greater, tok::r_square))
return true;
}
if ((Style.Language == FormatStyle::LK_Cpp ||
Style.Language == FormatStyle::LK_ObjC) &&
Left.is(tok::l_paren) && Left.BlockParameterCount > 0 &&
!Right.isOneOf(tok::l_paren, TT_LambdaLSquare)) {
if (Left.BlockParameterCount > 1)
return true;
if (!Left.Role)
return false;
auto Comma = Left.Role->lastComma();
if (!Comma)
return false;
auto Next = Comma->getNextNonComment();
if (!Next)
return false;
if (!Next->isOneOf(TT_LambdaLSquare, tok::l_brace, tok::caret))
return true;
}
return false;
}
bool TokenAnnotator::canBreakBefore(const AnnotatedLine &Line,
const FormatToken &Right) const {
const FormatToken &Left = *Right.Previous;
if (Style.isCSharp()) {
if (Left.isOneOf(TT_CSharpNamedArgumentColon, TT_AttributeColon) ||
Right.isOneOf(TT_CSharpNamedArgumentColon, TT_AttributeColon)) {
return false;
}
if (Line.First->is(TT_CSharpGenericTypeConstraint))
return Left.is(TT_CSharpGenericTypeConstraintComma);
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;
}
if (Right.isOneOf(Keywords.kw_throws, Keywords.kw_extends,
Keywords.kw_implements)) {
return true;
}
} else if (Style.isJavaScript()) {
const FormatToken *NonComment = Right.getPreviousNonComment();
if (NonComment &&
NonComment->isOneOf(
tok::kw_return, Keywords.kw_yield, tok::kw_continue, tok::kw_break,
tok::kw_throw, Keywords.kw_interface, Keywords.kw_type,
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)) {
return false; }
if (Right.NestingLevel == 0 &&
(Left.Tok.getIdentifierInfo() ||
Left.isOneOf(tok::r_square, tok::r_paren)) &&
Right.isOneOf(tok::l_square, tok::l_paren)) {
return false; }
if (NonComment && NonComment->is(tok::identifier) &&
NonComment->TokenText == "asserts") {
return false;
}
if (Left.is(TT_FatArrow) && Right.is(tok::l_brace))
return false;
if (Left.is(TT_JsTypeColon))
return true;
if (Left.is(tok::exclaim) && Right.is(tok::colon))
return false;
if (Right.is(Keywords.kw_is)) {
const FormatToken *Next = Right.getNextNonComment();
if (!Next || !Next->is(tok::colon))
return false;
}
if (Left.is(Keywords.kw_in))
return Style.BreakBeforeBinaryOperators == FormatStyle::BOS_None;
if (Right.is(Keywords.kw_in))
return Style.BreakBeforeBinaryOperators != FormatStyle::BOS_None;
if (Right.is(Keywords.kw_as))
return false; if (Right.isOneOf(Keywords.kw_extends, Keywords.kw_infer)) {
return false;
}
if (Left.is(Keywords.kw_as))
return true;
if (Left.is(TT_NonNullAssertion))
return true;
if (Left.is(Keywords.kw_declare) &&
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)) {
return false;
}
if (Left.isOneOf(Keywords.kw_module, tok::kw_namespace) &&
Right.isOneOf(tok::identifier, tok::string_literal)) {
return false; }
if (Right.is(TT_TemplateString) && Right.closesScope())
return false;
if (Left.is(tok::identifier) && Right.is(TT_TemplateString))
return false;
if (Left.is(TT_TemplateString) && Left.opensScope())
return true;
}
if (Left.is(tok::at))
return false;
if (Left.Tok.getObjCKeywordID() == tok::objc_interface)
return false;
if (Left.isOneOf(TT_JavaAnnotation, TT_LeadingJavaAnnotation))
return !Right.is(tok::l_paren);
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)) {
return true;
}
if (Left.is(TT_PointerOrReference))
return false;
if (Right.isTrailingComment()) {
return Left.is(BK_BracedInit) ||
(Left.is(TT_CtorInitializerColon) && Right.NewlinesBefore > 0 &&
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))
return Style.BreakBeforeTernaryOperators;
if (Left.is(TT_ConditionalExpr) || Left.is(tok::question))
return !Style.BreakBeforeTernaryOperators;
if (Left.is(TT_InheritanceColon))
return Style.BreakInheritanceList == FormatStyle::BILS_AfterColon;
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)) {
return true;
}
if (Right.is(tok::colon) &&
!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) {
if (!Style.AlwaysBreakBeforeMultilineStrings && Right.isStringLiteral())
return false;
if (((Right.is(tok::l_brace) || Right.is(tok::less)) &&
Right.is(TT_DictLiteral)) ||
Right.is(TT_ArrayInitializerLSquare)) {
return false;
}
}
return true;
}
if (Right.is(tok::r_square) && Right.MatchingParen &&
Right.MatchingParen->is(TT_ProtoExtensionLSquare)) {
return false;
}
if (Right.is(TT_SelectorName) || (Right.is(tok::identifier) && Right.Next &&
Right.Next->is(TT_ObjCMethodExpr))) {
return Left.isNot(tok::period); }
if (Left.is(tok::r_paren) && Line.Type == LT_ObjCProperty)
return true;
if (Right.is(tok::kw_concept))
return Style.BreakBeforeConceptDeclarations != FormatStyle::BBCDS_Never;
if (Right.is(TT_RequiresClause))
return true;
if (Left.ClosesTemplateDeclaration || Left.is(TT_FunctionAnnotationRParen))
return true;
if (Left.ClosesRequiresClause)
return true;
if (Right.isOneOf(TT_RangeBasedForLoopColon, TT_OverloadedOperatorLParen,
TT_OverloadedOperator)) {
return false;
}
if (Left.is(TT_RangeBasedForLoopColon))
return true;
if (Right.is(TT_RangeBasedForLoopColon))
return false;
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))) {
return false;
}
if (Right.is(TT_BinaryOperator) &&
Style.BreakBeforeBinaryOperators != FormatStyle::BOS_None &&
(Style.BreakBeforeBinaryOperators == FormatStyle::BOS_All ||
Right.getPrecedence() != prec::Assignment)) {
return true;
}
if (Left.isOneOf(TT_TemplateCloser, TT_UnaryOperator) ||
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) {
return false;
}
if (Left.is(tok::equal) && Right.is(tok::l_brace) &&
!Style.Cpp11BracedListStyle) {
return false;
}
if (Left.is(tok::l_paren) &&
Left.isOneOf(TT_AttributeParen, TT_TypeDeclarationParen)) {
return false;
}
if (Left.is(tok::l_paren) && Left.Previous &&
(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)) {
return false;
}
if (Right.is(tok::r_brace))
return Right.MatchingParen && Right.MatchingParen->is(BK_Block);
if (Right.is(tok::r_paren)) {
if (Style.AlignAfterOpenBracket != FormatStyle::BAS_BlockIndent ||
!Right.MatchingParen) {
return false;
}
const FormatToken *Previous = Right.MatchingParen->Previous;
return !(Previous && (Previous->is(tok::kw_for) || Previous->isIf()));
}
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))) {
return !Left.is(TT_AttributeSquare);
}
if (Left.is(tok::identifier) && Right.is(tok::string_literal))
return true;
if (Right.is(tok::identifier) && Right.Next && Right.Next->is(TT_DictLiteral))
return true;
if (Left.is(TT_CtorInitializerColon)) {
return Style.BreakConstructorInitializers == FormatStyle::BCIS_AfterColon &&
(!Right.isTrailingComment() || Right.NewlinesBefore > 0);
}
if (Right.is(TT_CtorInitializerColon))
return Style.BreakConstructorInitializers != FormatStyle::BCIS_AfterColon;
if (Left.is(TT_CtorInitializerComma) &&
Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma) {
return false;
}
if (Right.is(TT_CtorInitializerComma) &&
Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma) {
return true;
}
if (Left.is(TT_InheritanceComma) &&
Style.BreakInheritanceList == FormatStyle::BILS_BeforeComma) {
return false;
}
if (Right.is(TT_InheritanceComma) &&
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))
return true;
if ((Left.isBinaryOperator() || Left.is(TT_BinaryOperator)) &&
!Left.isOneOf(tok::arrowstar, tok::lessless) &&
Style.BreakBeforeBinaryOperators != FormatStyle::BOS_All &&
(Style.BreakBeforeBinaryOperators == FormatStyle::BOS_None ||
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))) {
return false;
}
auto ShortLambdaOption = Style.AllowShortLambdasOnASingleLine;
if (Style.BraceWrapping.BeforeLambdaBody && Right.is(TT_LambdaLBrace)) {
if (isAllmanLambdaBrace(Left))
return !isItAnEmptyLambdaAllowed(Left, ShortLambdaOption);
if (isAllmanLambdaBrace(Right))
return !isItAnEmptyLambdaAllowed(Right, ShortLambdaOption);
}
return Left.isOneOf(tok::comma, tok::coloncolon, tok::semi, tok::l_brace,
tok::kw_class, tok::kw_struct, tok::comment) ||
Right.isMemberAccess() ||
Right.isOneOf(TT_TrailingReturnArrow, TT_LambdaArrow, tok::lessless,
tok::colon, tok::l_square, tok::at) ||
(Left.is(tok::r_paren) &&
Right.isOneOf(tok::identifier, tok::kw_const)) ||
(Left.is(tok::l_paren) && !Right.is(tok::r_paren)) ||
(Left.is(TT_TemplateOpener) && !Right.is(TT_TemplateCloser));
}
void TokenAnnotator::printDebugInfo(const AnnotatedLine &Line) const {
llvm::errs() << "AnnotatedTokens(L=" << Line.Level << "):\n";
const FormatToken *Tok = Line.First;
while (Tok) {
llvm::errs() << " M=" << Tok->MustBreakBefore
<< " C=" << Tok->CanBreakBefore
<< " T=" << getTokenTypeName(Tok->getType())
<< " S=" << Tok->SpacesRequiredBefore
<< " F=" << Tok->Finalized << " B=" << Tok->BlockParameterCount
<< " BK=" << Tok->getBlockKind() << " P=" << Tok->SplitPenalty
<< " Name=" << Tok->Tok.getName() << " L=" << Tok->TotalLength
<< " PPK=" << Tok->getPackingKind() << " FakeLParens=";
for (prec::Level LParen : Tok->FakeLParens)
llvm::errs() << LParen << "/";
llvm::errs() << " FakeRParens=" << Tok->FakeRParens;
llvm::errs() << " II=" << Tok->Tok.getIdentifierInfo();
llvm::errs() << " Text='" << Tok->TokenText << "'\n";
if (!Tok->Next)
assert(Tok == Line.Last);
Tok = Tok->Next;
}
llvm::errs() << "----\n";
}
FormatStyle::PointerAlignmentStyle
TokenAnnotator::getTokenReferenceAlignment(const FormatToken &Reference) const {
assert(Reference.isOneOf(tok::amp, tok::ampamp));
switch (Style.ReferenceAlignment) {
case FormatStyle::RAS_Pointer:
return Style.PointerAlignment;
case FormatStyle::RAS_Left:
return FormatStyle::PAS_Left;
case FormatStyle::RAS_Right:
return FormatStyle::PAS_Right;
case FormatStyle::RAS_Middle:
return FormatStyle::PAS_Middle;
}
assert(0); return Style.PointerAlignment;
}
FormatStyle::PointerAlignmentStyle
TokenAnnotator::getTokenPointerOrReferenceAlignment(
const FormatToken &PointerOrReference) const {
if (PointerOrReference.isOneOf(tok::amp, tok::ampamp)) {
switch (Style.ReferenceAlignment) {
case FormatStyle::RAS_Pointer:
return Style.PointerAlignment;
case FormatStyle::RAS_Left:
return FormatStyle::PAS_Left;
case FormatStyle::RAS_Right:
return FormatStyle::PAS_Right;
case FormatStyle::RAS_Middle:
return FormatStyle::PAS_Middle;
}
}
assert(PointerOrReference.is(tok::star));
return Style.PointerAlignment;
}
} }