Index: lib/Format/FormatToken.h =================================================================== --- lib/Format/FormatToken.h +++ lib/Format/FormatToken.h @@ -1,767 +1,768 @@ -//===--- FormatToken.h - Format C++ code ------------------------*- C++ -*-===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// -/// -/// \file -/// \brief This file contains the declaration of the FormatToken, a wrapper -/// around Token with additional information related to formatting. -/// -//===----------------------------------------------------------------------===// - -#ifndef LLVM_CLANG_LIB_FORMAT_FORMATTOKEN_H -#define LLVM_CLANG_LIB_FORMAT_FORMATTOKEN_H - -#include "clang/Basic/IdentifierTable.h" -#include "clang/Basic/OperatorPrecedence.h" -#include "clang/Format/Format.h" -#include "clang/Lex/Lexer.h" -#include -#include - -namespace clang { -namespace format { - -#define LIST_TOKEN_TYPES \ - TYPE(ArrayInitializerLSquare) \ - TYPE(ArraySubscriptLSquare) \ - TYPE(AttributeParen) \ - TYPE(BinaryOperator) \ - TYPE(BitFieldColon) \ - TYPE(BlockComment) \ - TYPE(CastRParen) \ - TYPE(ConditionalExpr) \ - TYPE(ConflictAlternative) \ - TYPE(ConflictEnd) \ - TYPE(ConflictStart) \ - TYPE(CtorInitializerColon) \ - TYPE(CtorInitializerComma) \ - TYPE(DesignatedInitializerLSquare) \ - TYPE(DesignatedInitializerPeriod) \ - TYPE(DictLiteral) \ - TYPE(ForEachMacro) \ - TYPE(FunctionAnnotationRParen) \ - TYPE(FunctionDeclarationName) \ - TYPE(FunctionLBrace) \ - TYPE(FunctionTypeLParen) \ - TYPE(ImplicitStringLiteral) \ - TYPE(InheritanceColon) \ - TYPE(InheritanceComma) \ - TYPE(InlineASMBrace) \ - TYPE(InlineASMColon) \ - TYPE(JavaAnnotation) \ - TYPE(JsComputedPropertyName) \ - TYPE(JsExponentiation) \ - TYPE(JsExponentiationEqual) \ - TYPE(JsFatArrow) \ - TYPE(JsNonNullAssertion) \ - TYPE(JsTypeColon) \ - TYPE(JsTypeOperator) \ - TYPE(JsTypeOptionalQuestion) \ - TYPE(LambdaArrow) \ - TYPE(LambdaLSquare) \ - TYPE(LeadingJavaAnnotation) \ - TYPE(LineComment) \ - TYPE(MacroBlockBegin) \ - TYPE(MacroBlockEnd) \ - TYPE(ObjCBlockLBrace) \ - TYPE(ObjCBlockLParen) \ - TYPE(ObjCDecl) \ - TYPE(ObjCForIn) \ - TYPE(ObjCMethodExpr) \ - TYPE(ObjCMethodSpecifier) \ - TYPE(ObjCProperty) \ - TYPE(ObjCStringLiteral) \ - TYPE(OverloadedOperator) \ - TYPE(OverloadedOperatorLParen) \ - TYPE(PointerOrReference) \ - TYPE(PureVirtualSpecifier) \ - TYPE(RangeBasedForLoopColon) \ - TYPE(RegexLiteral) \ - TYPE(SelectorName) \ - TYPE(StartOfName) \ - TYPE(TemplateCloser) \ - TYPE(TemplateOpener) \ - TYPE(TemplateString) \ - TYPE(TrailingAnnotation) \ - TYPE(TrailingReturnArrow) \ - TYPE(TrailingUnaryOperator) \ - TYPE(UnaryOperator) \ - TYPE(Unknown) - -enum TokenType { -#define TYPE(X) TT_##X, -LIST_TOKEN_TYPES -#undef TYPE - NUM_TOKEN_TYPES -}; - -/// \brief Determines the name of a token type. -const char *getTokenTypeName(TokenType Type); - -// Represents what type of block a set of braces open. -enum BraceBlockKind { BK_Unknown, BK_Block, BK_BracedInit }; - -// The packing kind of a function's parameters. -enum ParameterPackingKind { PPK_BinPacked, PPK_OnePerLine, PPK_Inconclusive }; - -enum FormatDecision { FD_Unformatted, FD_Continue, FD_Break }; - -class TokenRole; -class AnnotatedLine; - -/// \brief A wrapper around a \c Token storing information about the -/// whitespace characters preceding it. -struct FormatToken { - FormatToken() {} - - /// \brief The \c Token. - Token Tok; - - /// \brief The number of newlines immediately before the \c Token. - /// - /// This can be used to determine what the user wrote in the original code - /// and thereby e.g. leave an empty line between two function definitions. - unsigned NewlinesBefore = 0; - - /// \brief Whether there is at least one unescaped newline before the \c - /// Token. - bool HasUnescapedNewline = false; - - /// \brief The range of the whitespace immediately preceding the \c Token. - SourceRange WhitespaceRange; - - /// \brief The offset just past the last '\n' in this token's leading - /// whitespace (relative to \c WhiteSpaceStart). 0 if there is no '\n'. - unsigned LastNewlineOffset = 0; - - /// \brief The width of the non-whitespace parts of the token (or its first - /// line for multi-line tokens) in columns. - /// We need this to correctly measure number of columns a token spans. - unsigned ColumnWidth = 0; - - /// \brief Contains the width in columns of the last line of a multi-line - /// token. - unsigned LastLineColumnWidth = 0; - - /// \brief Whether the token text contains newlines (escaped or not). - bool IsMultiline = false; - - /// \brief Indicates that this is the first token of the file. - bool IsFirst = false; - - /// \brief Whether there must be a line break before this token. - /// - /// This happens for example when a preprocessor directive ended directly - /// before the token. - bool MustBreakBefore = false; - - /// \brief The raw text of the token. - /// - /// Contains the raw token text without leading whitespace and without leading - /// escaped newlines. - StringRef TokenText; - - /// \brief Set to \c true if this token is an unterminated literal. - bool IsUnterminatedLiteral = 0; - - /// \brief Contains the kind of block if this token is a brace. - BraceBlockKind BlockKind = BK_Unknown; - - TokenType Type = TT_Unknown; - - /// \brief The number of spaces that should be inserted before this token. - unsigned SpacesRequiredBefore = 0; - - /// \brief \c true if it is allowed to break before this token. - bool CanBreakBefore = false; - - /// \brief \c true if this is the ">" of "template<..>". - bool ClosesTemplateDeclaration = false; - - /// \brief Number of parameters, if this is "(", "[" or "<". - /// - /// This is initialized to 1 as we don't need to distinguish functions with - /// 0 parameters from functions with 1 parameter. Thus, we can simply count - /// the number of commas. - unsigned ParameterCount = 0; - - /// \brief Number of parameters that are nested blocks, - /// if this is "(", "[" or "<". - unsigned BlockParameterCount = 0; - - /// \brief If this is a bracket ("<", "(", "[" or "{"), contains the kind of - /// the surrounding bracket. - tok::TokenKind ParentBracket = tok::unknown; - - /// \brief A token can have a special role that can carry extra information - /// about the token's formatting. - std::unique_ptr Role; - - /// \brief If this is an opening parenthesis, how are the parameters packed? - ParameterPackingKind PackingKind = PPK_Inconclusive; - - /// \brief The total length of the unwrapped line up to and including this - /// token. - unsigned TotalLength = 0; - - /// \brief The original 0-based column of this token, including expanded tabs. - /// The configured TabWidth is used as tab width. - unsigned OriginalColumn = 0; - - /// \brief The length of following tokens until the next natural split point, - /// or the next token that can be broken. - unsigned UnbreakableTailLength = 0; - - // FIXME: Come up with a 'cleaner' concept. - /// \brief The binding strength of a token. This is a combined value of - /// operator precedence, parenthesis nesting, etc. - unsigned BindingStrength = 0; - - /// \brief The nesting level of this token, i.e. the number of surrounding (), - /// [], {} or <>. - unsigned NestingLevel = 0; - - /// \brief The indent level of this token. Copied from the surrounding line. - unsigned IndentLevel = 0; - - /// \brief Penalty for inserting a line break before this token. - unsigned SplitPenalty = 0; - - /// \brief If this is the first ObjC selector name in an ObjC method - /// definition or call, this contains the length of the longest name. - /// - /// This being set to 0 means that the selectors should not be colon-aligned, - /// e.g. because several of them are block-type. - unsigned LongestObjCSelectorName = 0; - - /// \brief Stores the number of required fake parentheses and the - /// corresponding operator precedence. - /// - /// If multiple fake parentheses start at a token, this vector stores them in - /// reverse order, i.e. inner fake parenthesis first. - SmallVector FakeLParens; - /// \brief Insert this many fake ) after this token for correct indentation. - unsigned FakeRParens = 0; - - /// \brief \c true if this token starts a binary expression, i.e. has at least - /// one fake l_paren with a precedence greater than prec::Unknown. - bool StartsBinaryExpression = false; - /// \brief \c true if this token ends a binary expression. - bool EndsBinaryExpression = false; - - /// \brief Is this is an operator (or "."/"->") in a sequence of operators - /// with the same precedence, contains the 0-based operator index. - unsigned OperatorIndex = 0; - - /// \brief If this is an operator (or "."/"->") in a sequence of operators - /// with the same precedence, points to the next operator. - FormatToken *NextOperator = nullptr; - - /// \brief Is this token part of a \c DeclStmt defining multiple variables? - /// - /// Only set if \c Type == \c TT_StartOfName. - bool PartOfMultiVariableDeclStmt = false; - - /// \brief Does this line comment continue a line comment section? - /// - /// Only set to true if \c Type == \c TT_LineComment. - bool ContinuesLineCommentSection = false; - - /// \brief If this is a bracket, this points to the matching one. - FormatToken *MatchingParen = nullptr; - - /// \brief The previous token in the unwrapped line. - FormatToken *Previous = nullptr; - - /// \brief The next token in the unwrapped line. - FormatToken *Next = nullptr; - - /// \brief If this token starts a block, this contains all the unwrapped lines - /// in it. - SmallVector Children; - - /// \brief Stores the formatting decision for the token once it was made. - FormatDecision Decision = FD_Unformatted; - - /// \brief If \c true, this token has been fully formatted (indented and - /// potentially re-formatted inside), and we do not allow further formatting - /// changes. - bool Finalized = false; - - bool is(tok::TokenKind Kind) const { return Tok.is(Kind); } - bool is(TokenType TT) const { return Type == TT; } - bool is(const IdentifierInfo *II) const { - return II && II == Tok.getIdentifierInfo(); - } - bool is(tok::PPKeywordKind Kind) const { - return Tok.getIdentifierInfo() && - Tok.getIdentifierInfo()->getPPKeywordID() == Kind; - } - template bool isOneOf(A K1, B K2) const { - return is(K1) || is(K2); - } - template - bool isOneOf(A K1, B K2, Ts... Ks) const { - return is(K1) || isOneOf(K2, Ks...); - } - template bool isNot(T Kind) const { return !is(Kind); } - - /// \c true if this token starts a sequence with the given tokens in order, - /// following the ``Next`` pointers, ignoring comments. - template - bool startsSequence(A K1, Ts... Tokens) const { - return startsSequenceInternal(K1, Tokens...); - } - - /// \c true if this token ends a sequence with the given tokens in order, - /// following the ``Previous`` pointers, ignoring comments. - template - bool endsSequence(A K1, Ts... Tokens) const { - return endsSequenceInternal(K1, Tokens...); - } - - bool isStringLiteral() const { return tok::isStringLiteral(Tok.getKind()); } - - bool isObjCAtKeyword(tok::ObjCKeywordKind Kind) const { - return Tok.isObjCAtKeyword(Kind); - } - - bool isAccessSpecifier(bool ColonRequired = true) const { - return isOneOf(tok::kw_public, tok::kw_protected, tok::kw_private) && - (!ColonRequired || (Next && Next->is(tok::colon))); - } - - /// \brief Determine whether the token is a simple-type-specifier. - bool isSimpleTypeSpecifier() const; - - bool isObjCAccessSpecifier() const { - return is(tok::at) && Next && (Next->isObjCAtKeyword(tok::objc_public) || - Next->isObjCAtKeyword(tok::objc_protected) || - Next->isObjCAtKeyword(tok::objc_package) || - Next->isObjCAtKeyword(tok::objc_private)); - } - - /// \brief Returns whether \p Tok is ([{ or a template opening <. - bool opensScope() const { - if (is(TT_TemplateString) && TokenText.endswith("${")) - return true; - return isOneOf(tok::l_paren, tok::l_brace, tok::l_square, - TT_TemplateOpener); - } - /// \brief Returns whether \p Tok is )]} or a template closing >. - bool closesScope() const { - if (is(TT_TemplateString) && TokenText.startswith("}")) - return true; - return isOneOf(tok::r_paren, tok::r_brace, tok::r_square, - TT_TemplateCloser); - } - - /// \brief Returns \c true if this is a "." or "->" accessing a member. - bool isMemberAccess() const { - return isOneOf(tok::arrow, tok::period, tok::arrowstar) && - !isOneOf(TT_DesignatedInitializerPeriod, TT_TrailingReturnArrow, - TT_LambdaArrow); - } - - bool isUnaryOperator() const { - switch (Tok.getKind()) { - case tok::plus: - case tok::plusplus: - case tok::minus: - case tok::minusminus: - case tok::exclaim: - case tok::tilde: - case tok::kw_sizeof: - case tok::kw_alignof: - return true; - default: - return false; - } - } - - bool isBinaryOperator() const { - // Comma is a binary operator, but does not behave as such wrt. formatting. - return getPrecedence() > prec::Comma; - } - - bool isTrailingComment() const { - return is(tok::comment) && - (is(TT_LineComment) || !Next || Next->NewlinesBefore > 0); - } - - /// \brief Returns \c true if this is a keyword that can be used - /// like a function call (e.g. sizeof, typeid, ...). - bool isFunctionLikeKeyword() const { - switch (Tok.getKind()) { - case tok::kw_throw: - case tok::kw_typeid: - case tok::kw_return: - case tok::kw_sizeof: - case tok::kw_alignof: - case tok::kw_alignas: - case tok::kw_decltype: - case tok::kw_noexcept: - case tok::kw_static_assert: - case tok::kw___attribute: - return true; - default: - return false; - } - } - - /// \brief Returns \c true if this is a string literal that's like a label, - /// e.g. ends with "=" or ":". - bool isLabelString() const { - if (!is(tok::string_literal)) - return false; - StringRef Content = TokenText; - if (Content.startswith("\"") || Content.startswith("'")) - Content = Content.drop_front(1); - if (Content.endswith("\"") || Content.endswith("'")) - Content = Content.drop_back(1); - Content = Content.trim(); - return Content.size() > 1 && - (Content.back() == ':' || Content.back() == '='); - } - - /// \brief Returns actual token start location without leading escaped - /// newlines and whitespace. - /// - /// This can be different to Tok.getLocation(), which includes leading escaped - /// newlines. - SourceLocation getStartOfNonWhitespace() const { - return WhitespaceRange.getEnd(); - } - - prec::Level getPrecedence() const { - return getBinOpPrecedence(Tok.getKind(), true, true); - } - - /// \brief Returns the previous token ignoring comments. - FormatToken *getPreviousNonComment() const { - FormatToken *Tok = Previous; - while (Tok && Tok->is(tok::comment)) - Tok = Tok->Previous; - return Tok; - } - - /// \brief Returns the next token ignoring comments. - const FormatToken *getNextNonComment() const { - const FormatToken *Tok = Next; - while (Tok && Tok->is(tok::comment)) - Tok = Tok->Next; - return Tok; - } - - /// \brief Returns \c true if this tokens starts a block-type list, i.e. a - /// list that should be indented with a block indent. - bool opensBlockOrBlockTypeList(const FormatStyle &Style) const { - if (is(TT_TemplateString) && opensScope()) - return true; - return is(TT_ArrayInitializerLSquare) || - (is(tok::l_brace) && - (BlockKind == BK_Block || is(TT_DictLiteral) || - (!Style.Cpp11BracedListStyle && NestingLevel == 0))) || - (is(tok::less) && (Style.Language == FormatStyle::LK_Proto || - Style.Language == FormatStyle::LK_TextProto)); - } - - /// \brief Same as opensBlockOrBlockTypeList, but for the closing token. - bool closesBlockOrBlockTypeList(const FormatStyle &Style) const { - if (is(TT_TemplateString) && closesScope()) - return true; - return MatchingParen && MatchingParen->opensBlockOrBlockTypeList(Style); - } - - /// \brief Return the actual namespace token, if this token starts a namespace - /// block. - const FormatToken *getNamespaceToken() const { - const FormatToken *NamespaceTok = this; - if (is(tok::comment)) - NamespaceTok = NamespaceTok->getNextNonComment(); - // Detect "(inline)? namespace" in the beginning of a line. - if (NamespaceTok && NamespaceTok->is(tok::kw_inline)) - NamespaceTok = NamespaceTok->getNextNonComment(); - return NamespaceTok && NamespaceTok->is(tok::kw_namespace) ? NamespaceTok - : nullptr; - } - -private: - // Disallow copying. - FormatToken(const FormatToken &) = delete; - void operator=(const FormatToken &) = delete; - - template - bool startsSequenceInternal(A K1, Ts... Tokens) const { - if (is(tok::comment) && Next) - return Next->startsSequenceInternal(K1, Tokens...); - return is(K1) && Next && Next->startsSequenceInternal(Tokens...); - } - - template - bool startsSequenceInternal(A K1) const { - if (is(tok::comment) && Next) - return Next->startsSequenceInternal(K1); - return is(K1); - } - - template - bool endsSequenceInternal(A K1) const { - if (is(tok::comment) && Previous) - return Previous->endsSequenceInternal(K1); - return is(K1); - } - - template - bool endsSequenceInternal(A K1, Ts... Tokens) const { - if (is(tok::comment) && Previous) - return Previous->endsSequenceInternal(K1, Tokens...); - return is(K1) && Previous && Previous->endsSequenceInternal(Tokens...); - } -}; - -class ContinuationIndenter; -struct LineState; - -class TokenRole { -public: - TokenRole(const FormatStyle &Style) : Style(Style) {} - virtual ~TokenRole(); - - /// \brief After the \c TokenAnnotator has finished annotating all the tokens, - /// this function precomputes required information for formatting. - virtual void precomputeFormattingInfos(const FormatToken *Token); - - /// \brief Apply the special formatting that the given role demands. - /// - /// Assumes that the token having this role is already formatted. - /// - /// Continues formatting from \p State leaving indentation to \p Indenter and - /// returns the total penalty that this formatting incurs. - virtual unsigned formatFromToken(LineState &State, - ContinuationIndenter *Indenter, - bool DryRun) { - return 0; - } - - /// \brief Same as \c formatFromToken, but assumes that the first token has - /// already been set thereby deciding on the first line break. - virtual unsigned formatAfterToken(LineState &State, - ContinuationIndenter *Indenter, - bool DryRun) { - return 0; - } - - /// \brief Notifies the \c Role that a comma was found. - virtual void CommaFound(const FormatToken *Token) {} - -protected: - const FormatStyle &Style; -}; - -class CommaSeparatedList : public TokenRole { -public: - CommaSeparatedList(const FormatStyle &Style) - : TokenRole(Style), HasNestedBracedList(false) {} - - void precomputeFormattingInfos(const FormatToken *Token) override; - - unsigned formatAfterToken(LineState &State, ContinuationIndenter *Indenter, - bool DryRun) override; - - unsigned formatFromToken(LineState &State, ContinuationIndenter *Indenter, - bool DryRun) override; - - /// \brief Adds \p Token as the next comma to the \c CommaSeparated list. - void CommaFound(const FormatToken *Token) override { - Commas.push_back(Token); - } - -private: - /// \brief A struct that holds information on how to format a given list with - /// a specific number of columns. - struct ColumnFormat { - /// \brief The number of columns to use. - unsigned Columns; - - /// \brief The total width in characters. - unsigned TotalWidth; - - /// \brief The number of lines required for this format. - unsigned LineCount; - - /// \brief The size of each column in characters. - SmallVector ColumnSizes; - }; - - /// \brief Calculate which \c ColumnFormat fits best into - /// \p RemainingCharacters. - const ColumnFormat *getColumnFormat(unsigned RemainingCharacters) const; - - /// \brief The ordered \c FormatTokens making up the commas of this list. - SmallVector Commas; - - /// \brief The length of each of the list's items in characters including the - /// trailing comma. - SmallVector ItemLengths; - - /// \brief Precomputed formats that can be used for this list. - SmallVector Formats; - - bool HasNestedBracedList; -}; - -/// \brief Encapsulates keywords that are context sensitive or for languages not -/// properly supported by Clang's lexer. -struct AdditionalKeywords { - AdditionalKeywords(IdentifierTable &IdentTable) { - kw_final = &IdentTable.get("final"); - kw_override = &IdentTable.get("override"); - kw_in = &IdentTable.get("in"); - kw_of = &IdentTable.get("of"); - kw_CF_ENUM = &IdentTable.get("CF_ENUM"); - kw_CF_OPTIONS = &IdentTable.get("CF_OPTIONS"); - kw_NS_ENUM = &IdentTable.get("NS_ENUM"); - kw_NS_OPTIONS = &IdentTable.get("NS_OPTIONS"); - - kw_as = &IdentTable.get("as"); - kw_async = &IdentTable.get("async"); - kw_await = &IdentTable.get("await"); - kw_declare = &IdentTable.get("declare"); - kw_finally = &IdentTable.get("finally"); - kw_from = &IdentTable.get("from"); - kw_function = &IdentTable.get("function"); - kw_get = &IdentTable.get("get"); - kw_import = &IdentTable.get("import"); - kw_is = &IdentTable.get("is"); - kw_let = &IdentTable.get("let"); - kw_module = &IdentTable.get("module"); - kw_readonly = &IdentTable.get("readonly"); - kw_set = &IdentTable.get("set"); - kw_type = &IdentTable.get("type"); - kw_typeof = &IdentTable.get("typeof"); - kw_var = &IdentTable.get("var"); - kw_yield = &IdentTable.get("yield"); - - kw_abstract = &IdentTable.get("abstract"); - kw_assert = &IdentTable.get("assert"); - kw_extends = &IdentTable.get("extends"); - kw_implements = &IdentTable.get("implements"); - kw_instanceof = &IdentTable.get("instanceof"); - kw_interface = &IdentTable.get("interface"); - kw_native = &IdentTable.get("native"); - kw_package = &IdentTable.get("package"); - kw_synchronized = &IdentTable.get("synchronized"); - kw_throws = &IdentTable.get("throws"); - kw___except = &IdentTable.get("__except"); - kw___has_include = &IdentTable.get("__has_include"); - kw___has_include_next = &IdentTable.get("__has_include_next"); - - kw_mark = &IdentTable.get("mark"); - - kw_extend = &IdentTable.get("extend"); - kw_option = &IdentTable.get("option"); - kw_optional = &IdentTable.get("optional"); - kw_repeated = &IdentTable.get("repeated"); - kw_required = &IdentTable.get("required"); - kw_returns = &IdentTable.get("returns"); - - kw_signals = &IdentTable.get("signals"); - kw_qsignals = &IdentTable.get("Q_SIGNALS"); - kw_slots = &IdentTable.get("slots"); - kw_qslots = &IdentTable.get("Q_SLOTS"); - - // Keep this at the end of the constructor to make sure everything here is - // already initialized. - JsExtraKeywords = std::unordered_set( - {kw_as, kw_async, kw_await, kw_declare, kw_finally, kw_from, - kw_function, kw_get, kw_import, kw_is, kw_let, kw_module, kw_readonly, - kw_set, kw_type, kw_typeof, kw_var, kw_yield, - // Keywords from the Java section. - kw_abstract, kw_extends, kw_implements, kw_instanceof, kw_interface}); - } - - // Context sensitive keywords. - IdentifierInfo *kw_final; - IdentifierInfo *kw_override; - IdentifierInfo *kw_in; - IdentifierInfo *kw_of; - IdentifierInfo *kw_CF_ENUM; - IdentifierInfo *kw_CF_OPTIONS; - IdentifierInfo *kw_NS_ENUM; - IdentifierInfo *kw_NS_OPTIONS; - IdentifierInfo *kw___except; - IdentifierInfo *kw___has_include; - IdentifierInfo *kw___has_include_next; - - // JavaScript keywords. - IdentifierInfo *kw_as; - IdentifierInfo *kw_async; - IdentifierInfo *kw_await; - IdentifierInfo *kw_declare; - IdentifierInfo *kw_finally; - IdentifierInfo *kw_from; - IdentifierInfo *kw_function; - IdentifierInfo *kw_get; - IdentifierInfo *kw_import; - IdentifierInfo *kw_is; - IdentifierInfo *kw_let; - IdentifierInfo *kw_module; - IdentifierInfo *kw_readonly; - IdentifierInfo *kw_set; - IdentifierInfo *kw_type; - IdentifierInfo *kw_typeof; - IdentifierInfo *kw_var; - IdentifierInfo *kw_yield; - - // Java keywords. - IdentifierInfo *kw_abstract; - IdentifierInfo *kw_assert; - IdentifierInfo *kw_extends; - IdentifierInfo *kw_implements; - IdentifierInfo *kw_instanceof; - IdentifierInfo *kw_interface; - IdentifierInfo *kw_native; - IdentifierInfo *kw_package; - IdentifierInfo *kw_synchronized; - IdentifierInfo *kw_throws; - - // Pragma keywords. - IdentifierInfo *kw_mark; - - // Proto keywords. - IdentifierInfo *kw_extend; - IdentifierInfo *kw_option; - IdentifierInfo *kw_optional; - IdentifierInfo *kw_repeated; - IdentifierInfo *kw_required; - IdentifierInfo *kw_returns; - - // QT keywords. - IdentifierInfo *kw_signals; - IdentifierInfo *kw_qsignals; - IdentifierInfo *kw_slots; - IdentifierInfo *kw_qslots; - - /// \brief Returns \c true if \p Tok is a true JavaScript identifier, returns - /// \c false if it is a keyword or a pseudo keyword. - bool IsJavaScriptIdentifier(const FormatToken &Tok) const { - return Tok.is(tok::identifier) && - JsExtraKeywords.find(Tok.Tok.getIdentifierInfo()) == - JsExtraKeywords.end(); - } - -private: - /// \brief The JavaScript keywords beyond the C++ keyword set. - std::unordered_set JsExtraKeywords; -}; - -} // namespace format -} // namespace clang - -#endif +//===--- FormatToken.h - Format C++ code ------------------------*- C++ -*-===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// +/// +/// \file +/// \brief This file contains the declaration of the FormatToken, a wrapper +/// around Token with additional information related to formatting. +/// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_CLANG_LIB_FORMAT_FORMATTOKEN_H +#define LLVM_CLANG_LIB_FORMAT_FORMATTOKEN_H + +#include "clang/Basic/IdentifierTable.h" +#include "clang/Basic/OperatorPrecedence.h" +#include "clang/Format/Format.h" +#include "clang/Lex/Lexer.h" +#include +#include + +namespace clang { +namespace format { + +#define LIST_TOKEN_TYPES \ + TYPE(ArrayInitializerLSquare) \ + TYPE(ArraySubscriptLSquare) \ + TYPE(AttributeParen) \ + TYPE(BinaryOperator) \ + TYPE(BitFieldColon) \ + TYPE(BlockComment) \ + TYPE(CastRParen) \ + TYPE(ConditionalExpr) \ + TYPE(ConflictAlternative) \ + TYPE(ConflictEnd) \ + TYPE(ConflictStart) \ + TYPE(CtorInitializerColon) \ + TYPE(CtorInitializerComma) \ + TYPE(DesignatedInitializerLSquare) \ + TYPE(DesignatedInitializerPeriod) \ + TYPE(DictLiteral) \ + TYPE(ForEachMacro) \ + TYPE(FunctionAnnotationRParen) \ + TYPE(FunctionDeclarationName) \ + TYPE(FunctionLBrace) \ + TYPE(FunctionTypeLParen) \ + TYPE(ImplicitStringLiteral) \ + TYPE(InheritanceColon) \ + TYPE(InheritanceComma) \ + TYPE(InlineASMBrace) \ + TYPE(InlineASMColon) \ + TYPE(JavaAnnotation) \ + TYPE(JsComputedPropertyName) \ + TYPE(JsExponentiation) \ + TYPE(JsExponentiationEqual) \ + TYPE(JsFatArrow) \ + TYPE(JsNonNullAssertion) \ + TYPE(JsTypeColon) \ + TYPE(JsTypeOperator) \ + TYPE(JsTypeOptionalQuestion) \ + TYPE(LambdaArrow) \ + TYPE(LambdaLSquare) \ + TYPE(LeadingJavaAnnotation) \ + TYPE(LineComment) \ + TYPE(MacroBlockBegin) \ + TYPE(MacroBlockEnd) \ + TYPE(ObjCBlockLBrace) \ + TYPE(ObjCBlockLParen) \ + TYPE(ObjCDecl) \ + TYPE(ObjCForIn) \ + TYPE(ObjCMethodExpr) \ + TYPE(ObjCMethodSpecifier) \ + TYPE(ObjCProperty) \ + TYPE(ObjCStringLiteral) \ + TYPE(OverloadedOperator) \ + TYPE(OverloadedOperatorLParen) \ + TYPE(PointerOrReference) \ + TYPE(PureVirtualSpecifier) \ + TYPE(RangeBasedForLoopColon) \ + TYPE(RegexLiteral) \ + TYPE(SelectorName) \ + TYPE(StartOfName) \ + TYPE(StructuredBindingLSquare) \ + TYPE(TemplateCloser) \ + TYPE(TemplateOpener) \ + TYPE(TemplateString) \ + TYPE(TrailingAnnotation) \ + TYPE(TrailingReturnArrow) \ + TYPE(TrailingUnaryOperator) \ + TYPE(UnaryOperator) \ + TYPE(Unknown) + +enum TokenType { +#define TYPE(X) TT_##X, +LIST_TOKEN_TYPES +#undef TYPE + NUM_TOKEN_TYPES +}; + +/// \brief Determines the name of a token type. +const char *getTokenTypeName(TokenType Type); + +// Represents what type of block a set of braces open. +enum BraceBlockKind { BK_Unknown, BK_Block, BK_BracedInit }; + +// The packing kind of a function's parameters. +enum ParameterPackingKind { PPK_BinPacked, PPK_OnePerLine, PPK_Inconclusive }; + +enum FormatDecision { FD_Unformatted, FD_Continue, FD_Break }; + +class TokenRole; +class AnnotatedLine; + +/// \brief A wrapper around a \c Token storing information about the +/// whitespace characters preceding it. +struct FormatToken { + FormatToken() {} + + /// \brief The \c Token. + Token Tok; + + /// \brief The number of newlines immediately before the \c Token. + /// + /// This can be used to determine what the user wrote in the original code + /// and thereby e.g. leave an empty line between two function definitions. + unsigned NewlinesBefore = 0; + + /// \brief Whether there is at least one unescaped newline before the \c + /// Token. + bool HasUnescapedNewline = false; + + /// \brief The range of the whitespace immediately preceding the \c Token. + SourceRange WhitespaceRange; + + /// \brief The offset just past the last '\n' in this token's leading + /// whitespace (relative to \c WhiteSpaceStart). 0 if there is no '\n'. + unsigned LastNewlineOffset = 0; + + /// \brief The width of the non-whitespace parts of the token (or its first + /// line for multi-line tokens) in columns. + /// We need this to correctly measure number of columns a token spans. + unsigned ColumnWidth = 0; + + /// \brief Contains the width in columns of the last line of a multi-line + /// token. + unsigned LastLineColumnWidth = 0; + + /// \brief Whether the token text contains newlines (escaped or not). + bool IsMultiline = false; + + /// \brief Indicates that this is the first token of the file. + bool IsFirst = false; + + /// \brief Whether there must be a line break before this token. + /// + /// This happens for example when a preprocessor directive ended directly + /// before the token. + bool MustBreakBefore = false; + + /// \brief The raw text of the token. + /// + /// Contains the raw token text without leading whitespace and without leading + /// escaped newlines. + StringRef TokenText; + + /// \brief Set to \c true if this token is an unterminated literal. + bool IsUnterminatedLiteral = 0; + + /// \brief Contains the kind of block if this token is a brace. + BraceBlockKind BlockKind = BK_Unknown; + + TokenType Type = TT_Unknown; + + /// \brief The number of spaces that should be inserted before this token. + unsigned SpacesRequiredBefore = 0; + + /// \brief \c true if it is allowed to break before this token. + bool CanBreakBefore = false; + + /// \brief \c true if this is the ">" of "template<..>". + bool ClosesTemplateDeclaration = false; + + /// \brief Number of parameters, if this is "(", "[" or "<". + /// + /// This is initialized to 1 as we don't need to distinguish functions with + /// 0 parameters from functions with 1 parameter. Thus, we can simply count + /// the number of commas. + unsigned ParameterCount = 0; + + /// \brief Number of parameters that are nested blocks, + /// if this is "(", "[" or "<". + unsigned BlockParameterCount = 0; + + /// \brief If this is a bracket ("<", "(", "[" or "{"), contains the kind of + /// the surrounding bracket. + tok::TokenKind ParentBracket = tok::unknown; + + /// \brief A token can have a special role that can carry extra information + /// about the token's formatting. + std::unique_ptr Role; + + /// \brief If this is an opening parenthesis, how are the parameters packed? + ParameterPackingKind PackingKind = PPK_Inconclusive; + + /// \brief The total length of the unwrapped line up to and including this + /// token. + unsigned TotalLength = 0; + + /// \brief The original 0-based column of this token, including expanded tabs. + /// The configured TabWidth is used as tab width. + unsigned OriginalColumn = 0; + + /// \brief The length of following tokens until the next natural split point, + /// or the next token that can be broken. + unsigned UnbreakableTailLength = 0; + + // FIXME: Come up with a 'cleaner' concept. + /// \brief The binding strength of a token. This is a combined value of + /// operator precedence, parenthesis nesting, etc. + unsigned BindingStrength = 0; + + /// \brief The nesting level of this token, i.e. the number of surrounding (), + /// [], {} or <>. + unsigned NestingLevel = 0; + + /// \brief The indent level of this token. Copied from the surrounding line. + unsigned IndentLevel = 0; + + /// \brief Penalty for inserting a line break before this token. + unsigned SplitPenalty = 0; + + /// \brief If this is the first ObjC selector name in an ObjC method + /// definition or call, this contains the length of the longest name. + /// + /// This being set to 0 means that the selectors should not be colon-aligned, + /// e.g. because several of them are block-type. + unsigned LongestObjCSelectorName = 0; + + /// \brief Stores the number of required fake parentheses and the + /// corresponding operator precedence. + /// + /// If multiple fake parentheses start at a token, this vector stores them in + /// reverse order, i.e. inner fake parenthesis first. + SmallVector FakeLParens; + /// \brief Insert this many fake ) after this token for correct indentation. + unsigned FakeRParens = 0; + + /// \brief \c true if this token starts a binary expression, i.e. has at least + /// one fake l_paren with a precedence greater than prec::Unknown. + bool StartsBinaryExpression = false; + /// \brief \c true if this token ends a binary expression. + bool EndsBinaryExpression = false; + + /// \brief Is this is an operator (or "."/"->") in a sequence of operators + /// with the same precedence, contains the 0-based operator index. + unsigned OperatorIndex = 0; + + /// \brief If this is an operator (or "."/"->") in a sequence of operators + /// with the same precedence, points to the next operator. + FormatToken *NextOperator = nullptr; + + /// \brief Is this token part of a \c DeclStmt defining multiple variables? + /// + /// Only set if \c Type == \c TT_StartOfName. + bool PartOfMultiVariableDeclStmt = false; + + /// \brief Does this line comment continue a line comment section? + /// + /// Only set to true if \c Type == \c TT_LineComment. + bool ContinuesLineCommentSection = false; + + /// \brief If this is a bracket, this points to the matching one. + FormatToken *MatchingParen = nullptr; + + /// \brief The previous token in the unwrapped line. + FormatToken *Previous = nullptr; + + /// \brief The next token in the unwrapped line. + FormatToken *Next = nullptr; + + /// \brief If this token starts a block, this contains all the unwrapped lines + /// in it. + SmallVector Children; + + /// \brief Stores the formatting decision for the token once it was made. + FormatDecision Decision = FD_Unformatted; + + /// \brief If \c true, this token has been fully formatted (indented and + /// potentially re-formatted inside), and we do not allow further formatting + /// changes. + bool Finalized = false; + + bool is(tok::TokenKind Kind) const { return Tok.is(Kind); } + bool is(TokenType TT) const { return Type == TT; } + bool is(const IdentifierInfo *II) const { + return II && II == Tok.getIdentifierInfo(); + } + bool is(tok::PPKeywordKind Kind) const { + return Tok.getIdentifierInfo() && + Tok.getIdentifierInfo()->getPPKeywordID() == Kind; + } + template bool isOneOf(A K1, B K2) const { + return is(K1) || is(K2); + } + template + bool isOneOf(A K1, B K2, Ts... Ks) const { + return is(K1) || isOneOf(K2, Ks...); + } + template bool isNot(T Kind) const { return !is(Kind); } + + /// \c true if this token starts a sequence with the given tokens in order, + /// following the ``Next`` pointers, ignoring comments. + template + bool startsSequence(A K1, Ts... Tokens) const { + return startsSequenceInternal(K1, Tokens...); + } + + /// \c true if this token ends a sequence with the given tokens in order, + /// following the ``Previous`` pointers, ignoring comments. + template + bool endsSequence(A K1, Ts... Tokens) const { + return endsSequenceInternal(K1, Tokens...); + } + + bool isStringLiteral() const { return tok::isStringLiteral(Tok.getKind()); } + + bool isObjCAtKeyword(tok::ObjCKeywordKind Kind) const { + return Tok.isObjCAtKeyword(Kind); + } + + bool isAccessSpecifier(bool ColonRequired = true) const { + return isOneOf(tok::kw_public, tok::kw_protected, tok::kw_private) && + (!ColonRequired || (Next && Next->is(tok::colon))); + } + + /// \brief Determine whether the token is a simple-type-specifier. + bool isSimpleTypeSpecifier() const; + + bool isObjCAccessSpecifier() const { + return is(tok::at) && Next && (Next->isObjCAtKeyword(tok::objc_public) || + Next->isObjCAtKeyword(tok::objc_protected) || + Next->isObjCAtKeyword(tok::objc_package) || + Next->isObjCAtKeyword(tok::objc_private)); + } + + /// \brief Returns whether \p Tok is ([{ or a template opening <. + bool opensScope() const { + if (is(TT_TemplateString) && TokenText.endswith("${")) + return true; + return isOneOf(tok::l_paren, tok::l_brace, tok::l_square, + TT_TemplateOpener); + } + /// \brief Returns whether \p Tok is )]} or a template closing >. + bool closesScope() const { + if (is(TT_TemplateString) && TokenText.startswith("}")) + return true; + return isOneOf(tok::r_paren, tok::r_brace, tok::r_square, + TT_TemplateCloser); + } + + /// \brief Returns \c true if this is a "." or "->" accessing a member. + bool isMemberAccess() const { + return isOneOf(tok::arrow, tok::period, tok::arrowstar) && + !isOneOf(TT_DesignatedInitializerPeriod, TT_TrailingReturnArrow, + TT_LambdaArrow); + } + + bool isUnaryOperator() const { + switch (Tok.getKind()) { + case tok::plus: + case tok::plusplus: + case tok::minus: + case tok::minusminus: + case tok::exclaim: + case tok::tilde: + case tok::kw_sizeof: + case tok::kw_alignof: + return true; + default: + return false; + } + } + + bool isBinaryOperator() const { + // Comma is a binary operator, but does not behave as such wrt. formatting. + return getPrecedence() > prec::Comma; + } + + bool isTrailingComment() const { + return is(tok::comment) && + (is(TT_LineComment) || !Next || Next->NewlinesBefore > 0); + } + + /// \brief Returns \c true if this is a keyword that can be used + /// like a function call (e.g. sizeof, typeid, ...). + bool isFunctionLikeKeyword() const { + switch (Tok.getKind()) { + case tok::kw_throw: + case tok::kw_typeid: + case tok::kw_return: + case tok::kw_sizeof: + case tok::kw_alignof: + case tok::kw_alignas: + case tok::kw_decltype: + case tok::kw_noexcept: + case tok::kw_static_assert: + case tok::kw___attribute: + return true; + default: + return false; + } + } + + /// \brief Returns \c true if this is a string literal that's like a label, + /// e.g. ends with "=" or ":". + bool isLabelString() const { + if (!is(tok::string_literal)) + return false; + StringRef Content = TokenText; + if (Content.startswith("\"") || Content.startswith("'")) + Content = Content.drop_front(1); + if (Content.endswith("\"") || Content.endswith("'")) + Content = Content.drop_back(1); + Content = Content.trim(); + return Content.size() > 1 && + (Content.back() == ':' || Content.back() == '='); + } + + /// \brief Returns actual token start location without leading escaped + /// newlines and whitespace. + /// + /// This can be different to Tok.getLocation(), which includes leading escaped + /// newlines. + SourceLocation getStartOfNonWhitespace() const { + return WhitespaceRange.getEnd(); + } + + prec::Level getPrecedence() const { + return getBinOpPrecedence(Tok.getKind(), true, true); + } + + /// \brief Returns the previous token ignoring comments. + FormatToken *getPreviousNonComment() const { + FormatToken *Tok = Previous; + while (Tok && Tok->is(tok::comment)) + Tok = Tok->Previous; + return Tok; + } + + /// \brief Returns the next token ignoring comments. + const FormatToken *getNextNonComment() const { + const FormatToken *Tok = Next; + while (Tok && Tok->is(tok::comment)) + Tok = Tok->Next; + return Tok; + } + + /// \brief Returns \c true if this tokens starts a block-type list, i.e. a + /// list that should be indented with a block indent. + bool opensBlockOrBlockTypeList(const FormatStyle &Style) const { + if (is(TT_TemplateString) && opensScope()) + return true; + return is(TT_ArrayInitializerLSquare) || + (is(tok::l_brace) && + (BlockKind == BK_Block || is(TT_DictLiteral) || + (!Style.Cpp11BracedListStyle && NestingLevel == 0))) || + (is(tok::less) && (Style.Language == FormatStyle::LK_Proto || + Style.Language == FormatStyle::LK_TextProto)); + } + + /// \brief Same as opensBlockOrBlockTypeList, but for the closing token. + bool closesBlockOrBlockTypeList(const FormatStyle &Style) const { + if (is(TT_TemplateString) && closesScope()) + return true; + return MatchingParen && MatchingParen->opensBlockOrBlockTypeList(Style); + } + + /// \brief Return the actual namespace token, if this token starts a namespace + /// block. + const FormatToken *getNamespaceToken() const { + const FormatToken *NamespaceTok = this; + if (is(tok::comment)) + NamespaceTok = NamespaceTok->getNextNonComment(); + // Detect "(inline)? namespace" in the beginning of a line. + if (NamespaceTok && NamespaceTok->is(tok::kw_inline)) + NamespaceTok = NamespaceTok->getNextNonComment(); + return NamespaceTok && NamespaceTok->is(tok::kw_namespace) ? NamespaceTok + : nullptr; + } + +private: + // Disallow copying. + FormatToken(const FormatToken &) = delete; + void operator=(const FormatToken &) = delete; + + template + bool startsSequenceInternal(A K1, Ts... Tokens) const { + if (is(tok::comment) && Next) + return Next->startsSequenceInternal(K1, Tokens...); + return is(K1) && Next && Next->startsSequenceInternal(Tokens...); + } + + template + bool startsSequenceInternal(A K1) const { + if (is(tok::comment) && Next) + return Next->startsSequenceInternal(K1); + return is(K1); + } + + template + bool endsSequenceInternal(A K1) const { + if (is(tok::comment) && Previous) + return Previous->endsSequenceInternal(K1); + return is(K1); + } + + template + bool endsSequenceInternal(A K1, Ts... Tokens) const { + if (is(tok::comment) && Previous) + return Previous->endsSequenceInternal(K1, Tokens...); + return is(K1) && Previous && Previous->endsSequenceInternal(Tokens...); + } +}; + +class ContinuationIndenter; +struct LineState; + +class TokenRole { +public: + TokenRole(const FormatStyle &Style) : Style(Style) {} + virtual ~TokenRole(); + + /// \brief After the \c TokenAnnotator has finished annotating all the tokens, + /// this function precomputes required information for formatting. + virtual void precomputeFormattingInfos(const FormatToken *Token); + + /// \brief Apply the special formatting that the given role demands. + /// + /// Assumes that the token having this role is already formatted. + /// + /// Continues formatting from \p State leaving indentation to \p Indenter and + /// returns the total penalty that this formatting incurs. + virtual unsigned formatFromToken(LineState &State, + ContinuationIndenter *Indenter, + bool DryRun) { + return 0; + } + + /// \brief Same as \c formatFromToken, but assumes that the first token has + /// already been set thereby deciding on the first line break. + virtual unsigned formatAfterToken(LineState &State, + ContinuationIndenter *Indenter, + bool DryRun) { + return 0; + } + + /// \brief Notifies the \c Role that a comma was found. + virtual void CommaFound(const FormatToken *Token) {} + +protected: + const FormatStyle &Style; +}; + +class CommaSeparatedList : public TokenRole { +public: + CommaSeparatedList(const FormatStyle &Style) + : TokenRole(Style), HasNestedBracedList(false) {} + + void precomputeFormattingInfos(const FormatToken *Token) override; + + unsigned formatAfterToken(LineState &State, ContinuationIndenter *Indenter, + bool DryRun) override; + + unsigned formatFromToken(LineState &State, ContinuationIndenter *Indenter, + bool DryRun) override; + + /// \brief Adds \p Token as the next comma to the \c CommaSeparated list. + void CommaFound(const FormatToken *Token) override { + Commas.push_back(Token); + } + +private: + /// \brief A struct that holds information on how to format a given list with + /// a specific number of columns. + struct ColumnFormat { + /// \brief The number of columns to use. + unsigned Columns; + + /// \brief The total width in characters. + unsigned TotalWidth; + + /// \brief The number of lines required for this format. + unsigned LineCount; + + /// \brief The size of each column in characters. + SmallVector ColumnSizes; + }; + + /// \brief Calculate which \c ColumnFormat fits best into + /// \p RemainingCharacters. + const ColumnFormat *getColumnFormat(unsigned RemainingCharacters) const; + + /// \brief The ordered \c FormatTokens making up the commas of this list. + SmallVector Commas; + + /// \brief The length of each of the list's items in characters including the + /// trailing comma. + SmallVector ItemLengths; + + /// \brief Precomputed formats that can be used for this list. + SmallVector Formats; + + bool HasNestedBracedList; +}; + +/// \brief Encapsulates keywords that are context sensitive or for languages not +/// properly supported by Clang's lexer. +struct AdditionalKeywords { + AdditionalKeywords(IdentifierTable &IdentTable) { + kw_final = &IdentTable.get("final"); + kw_override = &IdentTable.get("override"); + kw_in = &IdentTable.get("in"); + kw_of = &IdentTable.get("of"); + kw_CF_ENUM = &IdentTable.get("CF_ENUM"); + kw_CF_OPTIONS = &IdentTable.get("CF_OPTIONS"); + kw_NS_ENUM = &IdentTable.get("NS_ENUM"); + kw_NS_OPTIONS = &IdentTable.get("NS_OPTIONS"); + + kw_as = &IdentTable.get("as"); + kw_async = &IdentTable.get("async"); + kw_await = &IdentTable.get("await"); + kw_declare = &IdentTable.get("declare"); + kw_finally = &IdentTable.get("finally"); + kw_from = &IdentTable.get("from"); + kw_function = &IdentTable.get("function"); + kw_get = &IdentTable.get("get"); + kw_import = &IdentTable.get("import"); + kw_is = &IdentTable.get("is"); + kw_let = &IdentTable.get("let"); + kw_module = &IdentTable.get("module"); + kw_readonly = &IdentTable.get("readonly"); + kw_set = &IdentTable.get("set"); + kw_type = &IdentTable.get("type"); + kw_typeof = &IdentTable.get("typeof"); + kw_var = &IdentTable.get("var"); + kw_yield = &IdentTable.get("yield"); + + kw_abstract = &IdentTable.get("abstract"); + kw_assert = &IdentTable.get("assert"); + kw_extends = &IdentTable.get("extends"); + kw_implements = &IdentTable.get("implements"); + kw_instanceof = &IdentTable.get("instanceof"); + kw_interface = &IdentTable.get("interface"); + kw_native = &IdentTable.get("native"); + kw_package = &IdentTable.get("package"); + kw_synchronized = &IdentTable.get("synchronized"); + kw_throws = &IdentTable.get("throws"); + kw___except = &IdentTable.get("__except"); + kw___has_include = &IdentTable.get("__has_include"); + kw___has_include_next = &IdentTable.get("__has_include_next"); + + kw_mark = &IdentTable.get("mark"); + + kw_extend = &IdentTable.get("extend"); + kw_option = &IdentTable.get("option"); + kw_optional = &IdentTable.get("optional"); + kw_repeated = &IdentTable.get("repeated"); + kw_required = &IdentTable.get("required"); + kw_returns = &IdentTable.get("returns"); + + kw_signals = &IdentTable.get("signals"); + kw_qsignals = &IdentTable.get("Q_SIGNALS"); + kw_slots = &IdentTable.get("slots"); + kw_qslots = &IdentTable.get("Q_SLOTS"); + + // Keep this at the end of the constructor to make sure everything here is + // already initialized. + JsExtraKeywords = std::unordered_set( + {kw_as, kw_async, kw_await, kw_declare, kw_finally, kw_from, + kw_function, kw_get, kw_import, kw_is, kw_let, kw_module, kw_readonly, + kw_set, kw_type, kw_typeof, kw_var, kw_yield, + // Keywords from the Java section. + kw_abstract, kw_extends, kw_implements, kw_instanceof, kw_interface}); + } + + // Context sensitive keywords. + IdentifierInfo *kw_final; + IdentifierInfo *kw_override; + IdentifierInfo *kw_in; + IdentifierInfo *kw_of; + IdentifierInfo *kw_CF_ENUM; + IdentifierInfo *kw_CF_OPTIONS; + IdentifierInfo *kw_NS_ENUM; + IdentifierInfo *kw_NS_OPTIONS; + IdentifierInfo *kw___except; + IdentifierInfo *kw___has_include; + IdentifierInfo *kw___has_include_next; + + // JavaScript keywords. + IdentifierInfo *kw_as; + IdentifierInfo *kw_async; + IdentifierInfo *kw_await; + IdentifierInfo *kw_declare; + IdentifierInfo *kw_finally; + IdentifierInfo *kw_from; + IdentifierInfo *kw_function; + IdentifierInfo *kw_get; + IdentifierInfo *kw_import; + IdentifierInfo *kw_is; + IdentifierInfo *kw_let; + IdentifierInfo *kw_module; + IdentifierInfo *kw_readonly; + IdentifierInfo *kw_set; + IdentifierInfo *kw_type; + IdentifierInfo *kw_typeof; + IdentifierInfo *kw_var; + IdentifierInfo *kw_yield; + + // Java keywords. + IdentifierInfo *kw_abstract; + IdentifierInfo *kw_assert; + IdentifierInfo *kw_extends; + IdentifierInfo *kw_implements; + IdentifierInfo *kw_instanceof; + IdentifierInfo *kw_interface; + IdentifierInfo *kw_native; + IdentifierInfo *kw_package; + IdentifierInfo *kw_synchronized; + IdentifierInfo *kw_throws; + + // Pragma keywords. + IdentifierInfo *kw_mark; + + // Proto keywords. + IdentifierInfo *kw_extend; + IdentifierInfo *kw_option; + IdentifierInfo *kw_optional; + IdentifierInfo *kw_repeated; + IdentifierInfo *kw_required; + IdentifierInfo *kw_returns; + + // QT keywords. + IdentifierInfo *kw_signals; + IdentifierInfo *kw_qsignals; + IdentifierInfo *kw_slots; + IdentifierInfo *kw_qslots; + + /// \brief Returns \c true if \p Tok is a true JavaScript identifier, returns + /// \c false if it is a keyword or a pseudo keyword. + bool IsJavaScriptIdentifier(const FormatToken &Tok) const { + return Tok.is(tok::identifier) && + JsExtraKeywords.find(Tok.Tok.getIdentifierInfo()) == + JsExtraKeywords.end(); + } + +private: + /// \brief The JavaScript keywords beyond the C++ keyword set. + std::unordered_set JsExtraKeywords; +}; + +} // namespace format +} // namespace clang + +#endif Index: lib/Format/TokenAnnotator.cpp =================================================================== --- lib/Format/TokenAnnotator.cpp +++ lib/Format/TokenAnnotator.cpp @@ -1,2885 +1,2901 @@ -//===--- TokenAnnotator.cpp - Format C++ code -----------------------------===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// -/// -/// \file -/// \brief This file implements a token annotator, i.e. creates -/// \c AnnotatedTokens out of \c FormatTokens with required extra information. -/// -//===----------------------------------------------------------------------===// - -#include "TokenAnnotator.h" -#include "clang/Basic/SourceManager.h" -#include "llvm/ADT/SmallPtrSet.h" -#include "llvm/Support/Debug.h" - -#define DEBUG_TYPE "format-token-annotator" - -namespace clang { -namespace format { - -namespace { - -/// \brief A parser that gathers additional information about tokens. -/// -/// The \c TokenAnnotator tries to match parenthesis and square brakets and -/// store a parenthesis levels. It also tries to resolve matching "<" and ">" -/// into template parameter lists. -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, /*IsExpression=*/false)); - resetTokenMetadata(CurrentToken); - } - -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); - - // If this angle is in the context of an expression, we need to be more - // hesitant to detect it as opening template parameters. - bool InExprContext = Contexts.back().IsExpression; - - Contexts.back().IsExpression = false; - // If there's a template keyword before the opening angle bracket, this is a - // template parameter, not an argument. - Contexts.back().InTemplateArgument = - Left->Previous && Left->Previous->Tok.isNot(tok::kw_template); - - if (Style.Language == FormatStyle::LK_Java && - CurrentToken->is(tok::question)) - next(); - - while (CurrentToken) { - if (CurrentToken->is(tok::greater)) { - Left->MatchingParen = CurrentToken; - CurrentToken->MatchingParen = Left; - CurrentToken->Type = 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.Language != FormatStyle::LK_Proto && - Style.Language != FormatStyle::LK_TextProto)) - return false; - // If a && or || is found and interpreted as a binary operator, this set - // of angles is likely part of something like "a < b && c > d". If the - // angles are inside an expression, the ||/&& might also be a binary - // operator that was misinterpreted because we are parsing template - // parameters. - // FIXME: This is getting out of hand, write a decent parser. - 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->Type = TT_SelectorName; - } - } - if (!consumeToken()) - return false; - } - return false; - } - - bool parseParens(bool LookForDecls = false) { - if (!CurrentToken) - return false; - FormatToken *Left = CurrentToken->Previous; - Left->ParentBracket = Contexts.back().ContextKind; - ScopedContextCreator ContextCreator(*this, tok::l_paren, 1); - - // FIXME: This is a bit of a hack. Do better. - Contexts.back().ColonIsForRangeExpr = - Contexts.size() == 2 && Contexts[0].ColonIsForRangeExpr; - - bool StartsObjCMethodExpr = false; - if (CurrentToken->is(tok::caret)) { - // (^ can start a block type. - Left->Type = TT_ObjCBlockLParen; - } else if (FormatToken *MaybeSel = Left->Previous) { - // @selector( starts a selector. - if (MaybeSel->isObjCAtKeyword(tok::objc_selector) && MaybeSel->Previous && - MaybeSel->Previous->is(tok::at)) { - StartsObjCMethodExpr = true; - } - } - - if (Left->is(TT_OverloadedOperatorLParen)) { - Contexts.back().IsExpression = false; - } else if (Style.Language == FormatStyle::LK_JavaScript && - (Line.startsWith(Keywords.kw_type, tok::identifier) || - Line.startsWith(tok::kw_export, Keywords.kw_type, - tok::identifier))) { - // type X = (...); - // export type X = (...); - Contexts.back().IsExpression = false; - } else if (Left->Previous && - (Left->Previous->isOneOf(tok::kw_static_assert, tok::kw_decltype, - tok::kw_if, tok::kw_while, tok::l_paren, - tok::comma) || - Left->Previous->endsSequence(tok::kw_constexpr, tok::kw_if) || - Left->Previous->is(TT_BinaryOperator))) { - // static_assert, if and while usually contain expressions. - Contexts.back().IsExpression = true; - } else if (Style.Language == FormatStyle::LK_JavaScript && Left->Previous && - (Left->Previous->is(Keywords.kw_function) || - (Left->Previous->endsSequence(tok::identifier, - Keywords.kw_function)))) { - // function(...) or function f(...) - Contexts.back().IsExpression = false; - } else if (Style.Language == FormatStyle::LK_JavaScript && Left->Previous && - Left->Previous->is(TT_JsTypeColon)) { - // let x: (SomeType); - Contexts.back().IsExpression = false; - } else if (Left->Previous && Left->Previous->is(tok::r_square) && - Left->Previous->MatchingParen && - Left->Previous->MatchingParen->is(TT_LambdaLSquare)) { - // This is a parameter list of a lambda expression. - Contexts.back().IsExpression = false; - } else if (Line.InPPDirective && - (!Left->Previous || !Left->Previous->is(tok::identifier))) { - Contexts.back().IsExpression = true; - } else if (Contexts[Contexts.size() - 2].CaretFound) { - // This is the parameter list of an ObjC block. - Contexts.back().IsExpression = false; - } else if (Left->Previous && Left->Previous->is(tok::kw___attribute)) { - Left->Type = TT_AttributeParen; - } else if (Left->Previous && Left->Previous->is(TT_ForEachMacro)) { - // The first argument to a foreach macro is a declaration. - Contexts.back().IsForEachMacro = true; - Contexts.back().IsExpression = false; - } else if (Left->Previous && Left->Previous->MatchingParen && - Left->Previous->MatchingParen->is(TT_ObjCBlockLParen)) { - Contexts.back().IsExpression = false; - } else if (!Line.MustBeDeclaration && !Line.InPPDirective) { - bool IsForOrCatch = - Left->Previous && Left->Previous->isOneOf(tok::kw_for, tok::kw_catch); - Contexts.back().IsExpression = !IsForOrCatch; - } - - if (StartsObjCMethodExpr) { - Contexts.back().ColonIsObjCMethodExpr = true; - Left->Type = TT_ObjCMethodExpr; - } - - bool MightBeFunctionType = !Contexts[Contexts.size() - 2].IsExpression; - bool ProbablyFunctionType = CurrentToken->isOneOf(tok::star, tok::amp); - bool HasMultipleLines = false; - bool HasMultipleParametersOnALine = false; - bool MightBeObjCForRangeLoop = - Left->Previous && Left->Previous->is(tok::kw_for); - while (CurrentToken) { - // LookForDecls is set when "if (" has been seen. Check for - // 'identifier' '*' 'identifier' followed by not '=' -- this - // '*' has to be a binary operator but determineStarAmpUsage() will - // categorize it as an unary operator, so set the right type here. - 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->Type = 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 (MightBeFunctionType && ProbablyFunctionType && CurrentToken->Next && - (CurrentToken->Next->is(tok::l_paren) || - (CurrentToken->Next->is(tok::l_square) && Line.MustBeDeclaration))) - Left->Type = TT_FunctionTypeLParen; - Left->MatchingParen = CurrentToken; - CurrentToken->MatchingParen = Left; - - if (CurrentToken->Next && CurrentToken->Next->is(tok::l_brace) && - Left->Previous && Left->Previous->is(tok::l_paren)) { - // Detect the case where macros are used to generate lambdas or - // function bodies, e.g.: - // auto my_lambda = MARCO((Type *type, int i) { .. body .. }); - for (FormatToken *Tok = Left; Tok != CurrentToken; Tok = Tok->Next) { - if (Tok->is(TT_BinaryOperator) && - Tok->isOneOf(tok::star, tok::amp, tok::ampamp)) - Tok->Type = TT_PointerOrReference; - } - } - - if (StartsObjCMethodExpr) { - CurrentToken->Type = TT_ObjCMethodExpr; - if (Contexts.back().FirstObjCSelectorName) { - Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName = - Contexts.back().LongestObjCSelectorName; - } - } - - if (Left->is(TT_AttributeParen)) - CurrentToken->Type = TT_AttributeParen; - if (Left->Previous && Left->Previous->is(TT_JavaAnnotation)) - CurrentToken->Type = TT_JavaAnnotation; - if (Left->Previous && Left->Previous->is(TT_LeadingJavaAnnotation)) - CurrentToken->Type = TT_LeadingJavaAnnotation; - - if (!HasMultipleLines) - Left->PackingKind = PPK_Inconclusive; - else if (HasMultipleParametersOnALine) - Left->PackingKind = PPK_BinPacked; - else - Left->PackingKind = PPK_OnePerLine; - - next(); - return true; - } - if (CurrentToken->isOneOf(tok::r_square, tok::r_brace)) - return false; - - if (CurrentToken->is(tok::l_brace)) - Left->Type = TT_Unknown; // Not TT_ObjCBlockLParen - if (CurrentToken->is(tok::comma) && CurrentToken->Next && - !CurrentToken->Next->HasUnescapedNewline && - !CurrentToken->Next->isTrailingComment()) - HasMultipleParametersOnALine = true; - if ((CurrentToken->Previous->isOneOf(tok::kw_const, tok::kw_auto) || - CurrentToken->Previous->isSimpleTypeSpecifier()) && - !CurrentToken->is(tok::l_brace)) - Contexts.back().IsExpression = false; - if (CurrentToken->isOneOf(tok::semi, tok::colon)) - MightBeObjCForRangeLoop = false; - if (MightBeObjCForRangeLoop && CurrentToken->is(Keywords.kw_in)) - CurrentToken->Type = TT_ObjCForIn; - // When we discover a 'new', we set CanBeExpression to 'false' in order to - // parse the type correctly. Reset that after a comma. - if (CurrentToken->is(tok::comma)) - Contexts.back().CanBeExpression = true; - - FormatToken *Tok = CurrentToken; - if (!consumeToken()) - return false; - updateParameterCount(Left, Tok); - if (CurrentToken && CurrentToken->HasUnescapedNewline) - HasMultipleLines = true; - } - return false; - } - - bool parseSquare() { - if (!CurrentToken) - return false; - - // A '[' could be an index subscript (after an identifier or after - // ')' or ']'), it could be the start of an Objective-C method - // expression, or it could the start of an Objective-C array literal. - FormatToken *Left = CurrentToken->Previous; - Left->ParentBracket = Contexts.back().ContextKind; - FormatToken *Parent = Left->getPreviousNonComment(); - - // Cases where '>' is followed by '['. - // In C++, this can happen either in array of templates (foo[10]) - // or when array is a nested template type (unique_ptr[]>). - bool CppArrayTemplates = - Style.isCpp() && Parent && - Parent->is(TT_TemplateCloser) && - (Contexts.back().CanBeExpression || Contexts.back().IsExpression || - Contexts.back().InTemplateArgument); - - bool StartsObjCMethodExpr = - !CppArrayTemplates && Style.isCpp() && - Contexts.back().CanBeExpression && Left->isNot(TT_LambdaLSquare) && - CurrentToken->isNot(tok::l_brace) && - (!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 (Left->is(TT_Unknown)) { - if (StartsObjCMethodExpr) { - Left->Type = TT_ObjCMethodExpr; - } else if (Style.Language == FormatStyle::LK_JavaScript && Parent && - Contexts.back().ContextKind == tok::l_brace && - Parent->isOneOf(tok::l_brace, tok::comma)) { - Left->Type = TT_JsComputedPropertyName; - } else if (Style.isCpp() && Contexts.back().ContextKind == tok::l_brace && - Parent && Parent->isOneOf(tok::l_brace, tok::comma)) { - Left->Type = TT_DesignatedInitializerLSquare; - } else if (CurrentToken->is(tok::r_square) && Parent && - Parent->is(TT_TemplateCloser)) { - Left->Type = TT_ArraySubscriptLSquare; - } else if (Style.Language == FormatStyle::LK_Proto || - (!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, - // Should only be relevant to JavaScript: - tok::kw_default))) { - Left->Type = TT_ArrayInitializerLSquare; - } else { - BindingIncrease = 10; - Left->Type = TT_ArraySubscriptLSquare; - } - } - - ScopedContextCreator ContextCreator(*this, tok::l_square, BindingIncrease); - Contexts.back().IsExpression = true; - if (Style.Language == FormatStyle::LK_JavaScript && Parent && - Parent->is(TT_JsTypeColon)) - Contexts.back().IsExpression = false; - - Contexts.back().ColonIsObjCMethodExpr = StartsObjCMethodExpr; - - while (CurrentToken) { - if (CurrentToken->is(tok::r_square)) { - if (CurrentToken->Next && CurrentToken->Next->is(tok::l_paren) && - Left->is(TT_ObjCMethodExpr)) { - // An ObjC method call is rarely followed by an open parenthesis. - // FIXME: Do we incorrectly label ":" with this? - StartsObjCMethodExpr = false; - Left->Type = TT_Unknown; - } - if (StartsObjCMethodExpr && CurrentToken->Previous != Left) { - CurrentToken->Type = TT_ObjCMethodExpr; - // determineStarAmpUsage() thinks that '*' '[' is allocating an - // array of pointers, but if '[' starts a selector then '*' is a - // binary operator. - if (Parent && Parent->is(TT_PointerOrReference)) - Parent->Type = TT_BinaryOperator; - } - Left->MatchingParen = CurrentToken; - CurrentToken->MatchingParen = Left; - 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 (Left->isOneOf(TT_ArraySubscriptLSquare, - TT_DesignatedInitializerLSquare)) { - Left->Type = TT_ObjCMethodExpr; - StartsObjCMethodExpr = true; - Contexts.back().ColonIsObjCMethodExpr = true; - if (Parent && Parent->is(tok::r_paren)) - Parent->Type = TT_CastRParen; - } - ColonFound = true; - } - if (CurrentToken->is(tok::comma) && Left->is(TT_ObjCMethodExpr) && - !ColonFound) - Left->Type = TT_ArrayInitializerLSquare; - FormatToken *Tok = CurrentToken; - if (!consumeToken()) - return false; - updateParameterCount(Left, Tok); - } - return false; - } - - bool parseBrace() { - if (CurrentToken) { - FormatToken *Left = CurrentToken->Previous; - Left->ParentBracket = Contexts.back().ContextKind; - - if (Contexts.back().CaretFound) - Left->Type = TT_ObjCBlockLBrace; - Contexts.back().CaretFound = false; - - ScopedContextCreator ContextCreator(*this, tok::l_brace, 1); - Contexts.back().ColonIsDictLiteral = true; - if (Left->BlockKind == BK_BracedInit) - Contexts.back().IsExpression = true; - if (Style.Language == FormatStyle::LK_JavaScript && Left->Previous && - Left->Previous->is(TT_JsTypeColon)) - Contexts.back().IsExpression = false; - - while (CurrentToken) { - if (CurrentToken->is(tok::r_brace)) { - Left->MatchingParen = CurrentToken; - CurrentToken->MatchingParen = Left; - next(); - return true; - } - if (CurrentToken->isOneOf(tok::r_paren, tok::r_square)) - return false; - updateParameterCount(Left, 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) && - (Previous->Tok.getIdentifierInfo() || - Previous->is(tok::string_literal))) - Previous->Type = TT_SelectorName; - if (CurrentToken->is(tok::colon) || - Style.Language == FormatStyle::LK_JavaScript) - Left->Type = TT_DictLiteral; - } - if (CurrentToken->is(tok::comma) && - Style.Language == FormatStyle::LK_JavaScript) - Left->Type = TT_DictLiteral; - if (!consumeToken()) - return false; - } - } - return true; - } - - void updateParameterCount(FormatToken *Left, FormatToken *Current) { - if (Current->is(tok::l_brace) && Current->BlockKind == 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->Type = TT_ConditionalExpr; - next(); - return true; - } - if (!consumeToken()) - return false; - } - return false; - } - - bool parseTemplateDeclaration() { - if (CurrentToken && CurrentToken->is(tok::less)) { - CurrentToken->Type = 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->Type = TT_ObjCMethodSpecifier; - break; - case tok::colon: - if (!Tok->Previous) - return false; - // Colons from ?: are handled in parseConditional(). - if (Style.Language == FormatStyle::LK_JavaScript) { - if (Contexts.back().ColonIsForRangeExpr || // colon in for loop - (Contexts.size() == 1 && // switch/case labels - !Line.First->isOneOf(tok::kw_enum, tok::kw_case)) || - Contexts.back().ContextKind == tok::l_paren || // function params - Contexts.back().ContextKind == tok::l_square || // array type - (!Contexts.back().IsExpression && - Contexts.back().ContextKind == tok::l_brace) || // object type - (Contexts.size() == 1 && - Line.MustBeDeclaration)) { // method/property declaration - Contexts.back().IsExpression = false; - Tok->Type = TT_JsTypeColon; - break; - } - } - if (Contexts.back().ColonIsDictLiteral || - Style.Language == FormatStyle::LK_Proto || - Style.Language == FormatStyle::LK_TextProto) { - Tok->Type = TT_DictLiteral; - if (Style.Language == FormatStyle::LK_TextProto) { - if (FormatToken *Previous = Tok->getPreviousNonComment()) - Previous->Type = TT_SelectorName; - } - } else if (Contexts.back().ColonIsObjCMethodExpr || - Line.startsWith(TT_ObjCMethodSpecifier)) { - Tok->Type = TT_ObjCMethodExpr; - const FormatToken *BeforePrevious = Tok->Previous->Previous; - if (!BeforePrevious || - !(BeforePrevious->is(TT_CastRParen) || - (BeforePrevious->is(TT_ObjCMethodExpr) && - BeforePrevious->is(tok::colon))) || - BeforePrevious->is(tok::r_square) || - Contexts.back().LongestObjCSelectorName == 0) { - Tok->Previous->Type = TT_SelectorName; - if (Tok->Previous->ColumnWidth > - Contexts.back().LongestObjCSelectorName) - Contexts.back().LongestObjCSelectorName = - Tok->Previous->ColumnWidth; - if (!Contexts.back().FirstObjCSelectorName) - Contexts.back().FirstObjCSelectorName = Tok->Previous; - } - } else if (Contexts.back().ColonIsForRangeExpr) { - Tok->Type = TT_RangeBasedForLoopColon; - } else if (CurrentToken && CurrentToken->is(tok::numeric_constant)) { - Tok->Type = TT_BitFieldColon; - } else if (Contexts.size() == 1 && - !Line.First->isOneOf(tok::kw_enum, tok::kw_case)) { - if (Tok->getPreviousNonComment()->isOneOf(tok::r_paren, - tok::kw_noexcept)) - Tok->Type = TT_CtorInitializerColon; - else - Tok->Type = TT_InheritanceColon; - } else if (Tok->Previous->is(tok::identifier) && Tok->Next && - Tok->Next->isOneOf(tok::r_paren, tok::comma)) { - // This handles a special macro in ObjC code where selectors including - // the colon are passed as macro arguments. - Tok->Type = TT_ObjCMethodExpr; - } else if (Contexts.back().ContextKind == tok::l_paren) { - Tok->Type = TT_InlineASMColon; - } - break; - case tok::pipe: - case tok::amp: - // | and & in declarations/type expressions represent union and - // intersection types, respectively. - if (Style.Language == FormatStyle::LK_JavaScript && - !Contexts.back().IsExpression) - Tok->Type = TT_JsTypeOperator; - break; - case tok::kw_if: - case tok::kw_while: - if (Tok->is(tok::kw_if) && CurrentToken && CurrentToken->is(tok::kw_constexpr)) - next(); - if (CurrentToken && CurrentToken->is(tok::l_paren)) { - next(); - if (!parseParens(/*LookForDecls=*/true)) - return false; - } - break; - case tok::kw_for: - if (Style.Language == FormatStyle::LK_JavaScript) { - if (Tok->Previous && Tok->Previous->is(tok::period)) - break; - // JS' for await ( ... - if (CurrentToken && CurrentToken->is(Keywords.kw_await)) - next(); - } - Contexts.back().ColonIsForRangeExpr = true; - next(); - if (!parseParens()) - return false; - break; - case tok::l_paren: - // When faced with 'operator()()', the kw_operator handler incorrectly - // marks the first l_paren as a OverloadedOperatorLParen. Here, we make - // the first two parens OverloadedOperators and the second l_paren an - // OverloadedOperatorLParen. - if (Tok->Previous && - Tok->Previous->is(tok::r_paren) && - Tok->Previous->MatchingParen && - Tok->Previous->MatchingParen->is(TT_OverloadedOperatorLParen)) { - Tok->Previous->Type = TT_OverloadedOperator; - Tok->Previous->MatchingParen->Type = TT_OverloadedOperator; - Tok->Type = TT_OverloadedOperatorLParen; - } - - if (!parseParens()) - return false; - if (Line.MustBeDeclaration && Contexts.size() == 1 && - !Contexts.back().IsExpression && !Line.startsWith(TT_ObjCProperty) && - (!Tok->Previous || - !Tok->Previous->isOneOf(tok::kw_decltype, 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->Type != TT_DictLiteral) - Previous->Type = TT_SelectorName; - } - if (!parseBrace()) - return false; - break; - case tok::less: - if (parseAngle()) { - Tok->Type = TT_TemplateOpener; - if (Style.Language == FormatStyle::LK_TextProto) { - FormatToken *Previous = Tok->getPreviousNonComment(); - if (Previous && Previous->Type != TT_DictLiteral) - Previous->Type = TT_SelectorName; - } - } else { - Tok->Type = TT_BinaryOperator; - NonTemplateLess.insert(Tok); - CurrentToken = Tok; - next(); - } - break; - case tok::r_paren: - case tok::r_square: - return false; - case tok::r_brace: - // Lines can start with '}'. - if (Tok->Previous) - return false; - break; - case tok::greater: - Tok->Type = TT_BinaryOperator; - break; - case tok::kw_operator: - while (CurrentToken && - !CurrentToken->isOneOf(tok::l_paren, tok::semi, tok::r_paren)) { - if (CurrentToken->isOneOf(tok::star, tok::amp)) - CurrentToken->Type = TT_PointerOrReference; - consumeToken(); - if (CurrentToken && - CurrentToken->Previous->isOneOf(TT_BinaryOperator, tok::comma)) - CurrentToken->Previous->Type = TT_OverloadedOperator; - } - if (CurrentToken) { - CurrentToken->Type = TT_OverloadedOperatorLParen; - if (CurrentToken->Previous->is(TT_BinaryOperator)) - CurrentToken->Previous->Type = TT_OverloadedOperator; - } - break; - case tok::question: - if (Style.Language == FormatStyle::LK_JavaScript && Tok->Next && - Tok->Next->isOneOf(tok::semi, tok::comma, tok::colon, tok::r_paren, - tok::r_brace)) { - // Question marks before semicolons, colons, etc. indicate optional - // types (fields, parameters), e.g. - // function(x?: string, y?) {...} - // class X { y?; } - Tok->Type = TT_JsTypeOptionalQuestion; - break; - } - // Declarations cannot be conditional expressions, this can only be part - // of a type declaration. - if (Line.MustBeDeclaration && !Contexts.back().IsExpression && - Style.Language == FormatStyle::LK_JavaScript) - break; - parseConditional(); - break; - case tok::kw_template: - parseTemplateDeclaration(); - break; - case tok::comma: - if (Contexts.back().InCtorInitializer) - Tok->Type = TT_CtorInitializerComma; - else if (Contexts.back().InInheritanceList) - Tok->Type = TT_InheritanceComma; - else if (Contexts.back().FirstStartOfName && - (Contexts.size() == 1 || Line.startsWith(tok::kw_for))) { - Contexts.back().FirstStartOfName->PartOfMultiVariableDeclStmt = true; - Line.IsMultiVariableDeclStmt = true; - } - if (Contexts.back().IsForEachMacro) - Contexts.back().IsExpression = true; - break; - case tok::identifier: - if (Tok->isOneOf(Keywords.kw___has_include, - Keywords.kw___has_include_next)) { - parseHasInclude(); - } - break; - default: - break; - } - return true; - } - - void parseIncludeDirective() { - if (CurrentToken && CurrentToken->is(tok::less)) { - next(); - while (CurrentToken) { - // Mark tokens up to the trailing line comments as implicit string - // literals. - if (CurrentToken->isNot(tok::comment) && - !CurrentToken->TokenText.startswith("//")) - CurrentToken->Type = TT_ImplicitStringLiteral; - next(); - } - } - } - - void parseWarningOrError() { - next(); - // We still want to format the whitespace left of the first token of the - // warning or error. - next(); - while (CurrentToken) { - CurrentToken->Type = TT_ImplicitStringLiteral; - next(); - } - } - - void parsePragma() { - next(); // Consume "pragma". - if (CurrentToken && - CurrentToken->isOneOf(Keywords.kw_mark, Keywords.kw_option)) { - bool IsMark = CurrentToken->is(Keywords.kw_mark); - next(); // Consume "mark". - next(); // Consume first token (so we fix leading whitespace). - while (CurrentToken) { - if (IsMark || CurrentToken->Previous->is(TT_BinaryOperator)) - CurrentToken->Type = 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.Language == FormatStyle::LK_JavaScript && IsFirstToken) { - // JavaScript files can contain shebang lines of the form: - // #!/usr/bin/env node - // Treat these like C++ #include directives. - while (CurrentToken) { - // Tokens cannot be comments here. - CurrentToken->Type = TT_ImplicitStringLiteral; - next(); - } - return LT_ImportStatement; - } - - if (CurrentToken->Tok.is(tok::numeric_constant)) { - CurrentToken->SpacesRequiredBefore = 1; - return Type; - } - // Hashes in the middle of a line can lead to any strange token - // sequence. - if (!CurrentToken->Tok.getIdentifierInfo()) - return Type; - 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; - 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() { - NonTemplateLess.clear(); - if (CurrentToken->is(tok::hash)) - return parsePreprocessorDirective(); - - // Directly allow to 'import ' to support protocol buffer - // definitions (code.google.com/p/protobuf) or missing "#" (either way we - // should not break the line). - 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 this line starts and ends in '<' and '>', respectively, it is likely - // part of "#define ". - if (CurrentToken->is(tok::less) && Line.Last->is(tok::greater)) { - parseIncludeDirective(); - return LT_ImportStatement; - } - - // In .proto files, top-level options are very similar to import statements - // and should not be line-wrapped. - if (Style.Language == FormatStyle::LK_Proto && Line.Level == 0 && - CurrentToken->is(Keywords.kw_option)) { - next(); - if (CurrentToken && CurrentToken->is(tok::identifier)) - return LT_ImportStatement; - } - - bool KeywordVirtualFound = false; - bool ImportStatement = false; - - // import {...} from '...'; - if (Style.Language == FormatStyle::LK_JavaScript && - CurrentToken->is(Keywords.kw_import)) - ImportStatement = true; - - while (CurrentToken) { - if (CurrentToken->is(tok::kw_virtual)) - KeywordVirtualFound = true; - if (Style.Language == FormatStyle::LK_JavaScript) { - // export {...} from '...'; - // An export followed by "from 'some string';" is a re-export from - // another module identified by a URI and is treated as a - // LT_ImportStatement (i.e. prevent wraps on it for long URIs). - // Just "export {...};" or "export class ..." should not be treated as - // an import in this sense. - 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; - } - - return LT_Other; - } - -private: - bool isClosureImportStatement(const FormatToken &Tok) { - // FIXME: Closure-library specific stuff should not be hard-coded but be - // configurable. - 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 == "setTestOnly" || - Tok.Next->Next->TokenText == "forwardDeclare") && - Tok.Next->Next->Next && Tok.Next->Next->Next->is(tok::l_paren); - } - - void resetTokenMetadata(FormatToken *Token) { - if (!Token) - return; - - // Reset token type in case we have already looked at it and then - // recovered from an error (e.g. failure to find the matching >). - if (!CurrentToken->isOneOf(TT_LambdaLSquare, TT_ForEachMacro, - TT_FunctionLBrace, TT_ImplicitStringLiteral, - TT_InlineASMBrace, TT_JsFatArrow, TT_LambdaArrow, - TT_OverloadedOperator, TT_RegexLiteral, - TT_TemplateString, TT_ObjCStringLiteral)) - CurrentToken->Type = TT_Unknown; - CurrentToken->Role.reset(); - CurrentToken->MatchingParen = nullptr; - CurrentToken->FakeLParens.clear(); - CurrentToken->FakeRParens = 0; - } - - void next() { - if (CurrentToken) { - CurrentToken->NestingLevel = Contexts.size() - 1; - CurrentToken->BindingStrength = Contexts.back().BindingStrength; - modifyContext(*CurrentToken); - determineTokenType(*CurrentToken); - CurrentToken = CurrentToken->Next; - } - - resetTokenMetadata(CurrentToken); - } - - /// \brief A struct to hold information valid in a specific context, e.g. - /// a pair of parenthesis. - 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 InTemplateArgument = false; - bool InCtorInitializer = false; - bool InInheritanceList = false; - bool CaretFound = false; - bool IsForEachMacro = false; - }; - - /// \brief Puts a new \c Context onto the stack \c Contexts for the lifetime - /// of each instance. - 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() { P.Contexts.pop_back(); } - }; - - void modifyContext(const FormatToken &Current) { - if (Current.getPrecedence() == prec::Assignment && - !Line.First->isOneOf(tok::kw_template, tok::kw_using, tok::kw_return) && - // Type aliases use `type X = ...;` in TypeScript and can be exported - // using `export type ...`. - !(Style.Language == FormatStyle::LK_JavaScript && - (Line.startsWith(Keywords.kw_type, tok::identifier) || - Line.startsWith(tok::kw_export, Keywords.kw_type, - tok::identifier))) && - (!Current.Previous || Current.Previous->isNot(tok::kw_operator))) { - 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->Type = 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().InCtorInitializer = true; - } else if (Current.Previous && - Current.Previous->is(TT_InheritanceColon)) { - Contexts.back().InInheritanceList = true; - } 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->Type = TT_PointerOrReference; - if (Line.MustBeDeclaration && !Contexts.front().InCtorInitializer) - Contexts.back().IsExpression = false; - } else if (Current.is(tok::kw_new)) { - Contexts.back().CanBeExpression = false; - } else if (Current.isOneOf(tok::semi, tok::exclaim)) { - // This should be the condition or increment in a for-loop. - Contexts.back().IsExpression = true; - } - } - - void determineTokenType(FormatToken &Current) { - if (!Current.is(TT_Unknown)) - // The token type is already known. - return; - - if (Style.Language == FormatStyle::LK_JavaScript) { - if (Current.is(tok::exclaim)) { - if (Current.Previous && - (Current.Previous->isOneOf(tok::identifier, tok::kw_namespace, - tok::r_paren, tok::r_square, - tok::r_brace) || - Current.Previous->Tok.isLiteral())) { - Current.Type = TT_JsNonNullAssertion; - return; - } - if (Current.Next && - Current.Next->isOneOf(TT_BinaryOperator, Keywords.kw_as)) { - Current.Type = TT_JsNonNullAssertion; - return; - } - } - } - - // Line.MightBeFunctionDecl can only be true after the parentheses of a - // function declaration have been found. In this case, 'Current' is a - // trailing token of this declaration and thus cannot be a name. - if (Current.is(Keywords.kw_instanceof)) { - Current.Type = TT_BinaryOperator; - } else if (isStartOfName(Current) && - (!Line.MightBeFunctionDecl || Current.NestingLevel != 0)) { - Contexts.back().FirstStartOfName = &Current; - Current.Type = TT_StartOfName; - } 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.Type = TT_LambdaArrow; - } else if (Current.is(tok::arrow) && AutoFound && Line.MustBeDeclaration && - Current.NestingLevel == 0) { - Current.Type = TT_TrailingReturnArrow; - } else if (Current.isOneOf(tok::star, tok::amp, tok::ampamp)) { - Current.Type = - determineStarAmpUsage(Current, Contexts.back().CanBeExpression && - Contexts.back().IsExpression, - Contexts.back().InTemplateArgument); - } else if (Current.isOneOf(tok::minus, tok::plus, tok::caret)) { - Current.Type = determinePlusMinusCaretUsage(Current); - if (Current.is(TT_UnaryOperator) && Current.is(tok::caret)) - Contexts.back().CaretFound = true; - } else if (Current.isOneOf(tok::minusminus, tok::plusplus)) { - Current.Type = determineIncrementUsage(Current); - } else if (Current.isOneOf(tok::exclaim, tok::tilde)) { - Current.Type = TT_UnaryOperator; - } else if (Current.is(tok::question)) { - if (Style.Language == FormatStyle::LK_JavaScript && - Line.MustBeDeclaration && !Contexts.back().IsExpression) { - // In JavaScript, `interface X { foo?(): bar; }` is an optional method - // on the interface, not a ternary expression. - Current.Type = TT_JsTypeOptionalQuestion; - } else { - Current.Type = TT_ConditionalExpr; - } - } else if (Current.isBinaryOperator() && - (!Current.Previous || Current.Previous->isNot(tok::l_square))) { - Current.Type = TT_BinaryOperator; - } else if (Current.is(tok::comment)) { - if (Current.TokenText.startswith("/*")) { - if (Current.TokenText.endswith("*/")) - Current.Type = TT_BlockComment; - else - // The lexer has for some reason determined a comment here. But we - // cannot really handle it, if it isn't properly terminated. - Current.Tok.setKind(tok::unknown); - } else { - Current.Type = TT_LineComment; - } - } else if (Current.is(tok::r_paren)) { - if (rParenEndsCast(Current)) - Current.Type = 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) { - // Make sure this isn't the return type of an Obj-C block declaration - if (AfterParen->Tok.isNot(tok::caret)) { - if (FormatToken *BeforeParen = Current.MatchingParen->Previous) - if (BeforeParen->is(tok::identifier) && - BeforeParen->TokenText == BeforeParen->TokenText.upper() && - (!BeforeParen->Previous || - BeforeParen->Previous->ClosesTemplateDeclaration)) - Current.Type = TT_FunctionAnnotationRParen; - } - } - } else if (Current.is(tok::at) && Current.Next && - Style.Language != FormatStyle::LK_JavaScript && - Style.Language != FormatStyle::LK_Java) { - // In Java & JavaScript, "@..." is a decorator or annotation. In ObjC, it - // marks declarations and properties that need special formatting. - switch (Current.Next->Tok.getObjCKeywordID()) { - case tok::objc_interface: - case tok::objc_implementation: - case tok::objc_protocol: - Current.Type = TT_ObjCDecl; - break; - case tok::objc_property: - Current.Type = 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.Type = TT_DesignatedInitializerPeriod; - else if (Style.Language == FormatStyle::LK_Java && Current.Previous && - Current.Previous->isOneOf(TT_JavaAnnotation, - TT_LeadingJavaAnnotation)) { - Current.Type = Current.Previous->Type; - } - } else if (Current.isOneOf(tok::identifier, tok::kw_const) && - Current.Previous && - !Current.Previous->isOneOf(tok::equal, tok::at) && - Line.MightBeFunctionDecl && Contexts.size() == 1) { - // Line.MightBeFunctionDecl can only be true after the parentheses of a - // function declaration have been found. - Current.Type = TT_TrailingAnnotation; - } else if ((Style.Language == FormatStyle::LK_Java || - Style.Language == FormatStyle::LK_JavaScript) && - 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.Type = TT_LeadingJavaAnnotation; - else - Current.Type = TT_JavaAnnotation; - } else if (Current.Previous->is(tok::period) && - Current.Previous->isOneOf(TT_JavaAnnotation, - TT_LeadingJavaAnnotation)) { - Current.Type = Current.Previous->Type; - } - } - } - - /// \brief Take a guess at whether \p Tok starts a name of a function or - /// variable declaration. - /// - /// This is a heuristic based on whether \p Tok is an identifier following - /// something that is likely a type. - 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.Language == FormatStyle::LK_JavaScript && - Tok.Previous->is(Keywords.kw_in)) - return false; - - // Skip "const" as it does not have an influence on whether this is a name. - FormatToken *PreviousNotConst = Tok.getPreviousNonComment(); - while (PreviousNotConst && PreviousNotConst->is(tok::kw_const)) - PreviousNotConst = PreviousNotConst->getPreviousNonComment(); - - if (!PreviousNotConst) - 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->MatchingParen && - PreviousNotConst->MatchingParen->Previous && - PreviousNotConst->MatchingParen->Previous->is(tok::kw_decltype)) - return true; - - return (!IsPPKeyword && - PreviousNotConst->isOneOf(tok::identifier, tok::kw_auto)) || - PreviousNotConst->is(TT_PointerOrReference) || - PreviousNotConst->isSimpleTypeSpecifier(); - } - - /// \brief Determine whether ')' is ending a cast. - bool rParenEndsCast(const FormatToken &Tok) { - // C-style casts are only used in C++ and Java. - if (!Style.isCpp() && Style.Language != FormatStyle::LK_Java) - return false; - - // Empty parens aren't casts and there are no casts at the end of the line. - if (Tok.Previous == Tok.MatchingParen || !Tok.Next || !Tok.MatchingParen) - return false; - - FormatToken *LeftOfParens = Tok.MatchingParen->getPreviousNonComment(); - if (LeftOfParens) { - // If there is a closing parenthesis left of the current parentheses, - // look past it as these might be chained casts. - if (LeftOfParens->is(tok::r_paren)) { - if (!LeftOfParens->MatchingParen || - !LeftOfParens->MatchingParen->Previous) - return false; - LeftOfParens = LeftOfParens->MatchingParen->Previous; - } - - // If there is an identifier (or with a few exceptions a keyword) right - // before the parentheses, this is unlikely to be a cast. - if (LeftOfParens->Tok.getIdentifierInfo() && - !LeftOfParens->isOneOf(Keywords.kw_in, tok::kw_return, tok::kw_case, - tok::kw_delete)) - return false; - - // Certain other tokens right before the parentheses are also signals that - // this cannot be a cast. - if (LeftOfParens->isOneOf(tok::at, tok::r_square, TT_OverloadedOperator, - TT_TemplateCloser, tok::ellipsis)) - return false; - } - - if (Tok.Next->is(tok::question)) - return false; - - // As Java has no function types, a "(" after the ")" likely means that this - // is a cast. - if (Style.Language == FormatStyle::LK_Java && Tok.Next->is(tok::l_paren)) - return true; - - // If a (non-string) literal follows, this is likely a cast. - if (Tok.Next->isNot(tok::string_literal) && - (Tok.Next->Tok.isLiteral() || - Tok.Next->isOneOf(tok::kw_sizeof, tok::kw_alignof))) - return true; - - // Heuristically try to determine whether the parentheses contain a type. - bool ParensAreType = - !Tok.Previous || - Tok.Previous->isOneOf(TT_PointerOrReference, TT_TemplateCloser) || - Tok.Previous->isSimpleTypeSpecifier(); - bool ParensCouldEndDecl = - Tok.Next->isOneOf(tok::equal, tok::semi, tok::l_brace, tok::greater); - if (ParensAreType && !ParensCouldEndDecl) - return true; - - // At this point, we heuristically assume that there are no casts at the - // start of the line. We assume that we have found most cases where there - // are by the logic above, e.g. "(void)x;". - if (!LeftOfParens) - return false; - - // Certain token types inside the parentheses mean that this can't be a - // cast. - for (const FormatToken *Token = Tok.MatchingParen->Next; Token != &Tok; - Token = Token->Next) - if (Token->is(TT_BinaryOperator)) - return false; - - // If the following token is an identifier or 'this', this is a cast. All - // cases where this can be something else are handled above. - if (Tok.Next->isOneOf(tok::identifier, tok::kw_this)) - return true; - - if (!Tok.Next->Next) - return false; - - // If the next token after the parenthesis is a unary operator, assume - // that this is cast, unless there are unexpected tokens inside the - // parenthesis. - 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; - // Search for unexpected tokens. - 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; - } - - /// \brief Return the type of the given token assuming it is * or &. - TokenType determineStarAmpUsage(const FormatToken &Tok, bool IsExpression, - bool InTemplateArgument) { - if (Style.Language == FormatStyle::LK_JavaScript) - return TT_BinaryOperator; - - const FormatToken *PrevToken = Tok.getPreviousNonComment(); - if (!PrevToken) - return TT_UnaryOperator; - - const FormatToken *NextToken = Tok.getNextNonComment(); - if (!NextToken || - NextToken->isOneOf(tok::arrow, tok::equal, tok::kw_const) || - (NextToken->is(tok::l_brace) && !NextToken->getNextNonComment())) - return TT_PointerOrReference; - - if (PrevToken->is(tok::coloncolon)) - return TT_PointerOrReference; - - if (PrevToken->isOneOf(tok::l_paren, tok::l_square, tok::l_brace, - tok::comma, tok::semi, tok::kw_return, tok::colon, - tok::equal, tok::kw_delete, tok::kw_sizeof, - tok::kw_throw) || - PrevToken->isOneOf(TT_BinaryOperator, TT_ConditionalExpr, - TT_UnaryOperator, TT_CastRParen)) - 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_paren) && PrevToken->MatchingParen) { - FormatToken *TokenBeforeMatchingParen = - PrevToken->MatchingParen->getPreviousNonComment(); - if (TokenBeforeMatchingParen && - TokenBeforeMatchingParen->isOneOf(tok::kw_typeof, tok::kw_decltype)) - return TT_PointerOrReference; - } - - if (PrevToken->Tok.isLiteral() || - PrevToken->isOneOf(tok::r_paren, tok::r_square, tok::kw_true, - tok::kw_false, tok::r_brace) || - NextToken->Tok.isLiteral() || - NextToken->isOneOf(tok::kw_true, tok::kw_false) || - NextToken->isUnaryOperator() || - // If we know we're in a template argument, there are no named - // declarations. Thus, having an identifier on the right-hand side - // indicates a binary operator. - (InTemplateArgument && NextToken->Tok.isAnyIdentifier())) - return TT_BinaryOperator; - - // "&&(" is quite unlikely to be two successive unary "&". - if (Tok.is(tok::ampamp) && NextToken && NextToken->is(tok::l_paren)) - return TT_BinaryOperator; - - // This catches some cases where evaluation order is used as control flow: - // aaa && aaa->f(); - const FormatToken *NextNextToken = NextToken->getNextNonComment(); - if (NextNextToken && NextNextToken->is(tok::arrow)) - return TT_BinaryOperator; - - // It is very unlikely that we are going to find a pointer or reference type - // definition on the RHS of an assignment. - if (IsExpression && !Contexts.back().CaretFound) - return TT_BinaryOperator; - - return TT_PointerOrReference; - } - - TokenType determinePlusMinusCaretUsage(const FormatToken &Tok) { - const FormatToken *PrevToken = Tok.getPreviousNonComment(); - if (!PrevToken) - return TT_UnaryOperator; - - if (PrevToken->isOneOf(TT_CastRParen, TT_UnaryOperator) && - !PrevToken->is(tok::exclaim)) - // There aren't any trailing unary operators except for TypeScript's - // non-null operator (!). Thus, this must be squence of leading operators. - return TT_UnaryOperator; - - // Use heuristics to recognize unary operators. - if (PrevToken->isOneOf(tok::equal, tok::l_paren, tok::comma, tok::l_square, - tok::question, tok::colon, tok::kw_return, - tok::kw_case, tok::at, tok::l_brace)) - return TT_UnaryOperator; - - // There can't be two consecutive binary operators. - if (PrevToken->is(TT_BinaryOperator)) - return TT_UnaryOperator; - - // Fall back to marking the token as binary operator. - return TT_BinaryOperator; - } - - /// \brief Determine whether ++/-- are pre- or post-increments/-decrements. - 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 Contexts; - - const FormatStyle &Style; - AnnotatedLine &Line; - FormatToken *CurrentToken; - bool AutoFound; - const AdditionalKeywords &Keywords; - - // Set of "<" tokens that do not open a template parameter list. If parseAngle - // determines that a specific token can't be a template opener, it will make - // same decision irrespective of the decisions for tokens leading up to it. - // Store this information to prevent this from causing exponential runtime. - llvm::SmallPtrSet NonTemplateLess; -}; - -static const int PrecedenceUnaryOperator = prec::PointerToMember + 1; -static const int PrecedenceArrowAndPeriod = prec::PointerToMember + 2; - -/// \brief Parses binary expressions by inserting fake parenthesis based on -/// operator precedence. -class ExpressionParser { -public: - ExpressionParser(const FormatStyle &Style, const AdditionalKeywords &Keywords, - AnnotatedLine &Line) - : Style(Style), Keywords(Keywords), Current(Line.First) {} - - /// \brief Parse expressions with the given operatore precedence. - void parse(int Precedence = 0) { - // Skip 'return' and ObjC selector colons as they are not part of a binary - // expression. - while (Current && (Current->is(tok::kw_return) || - (Current->is(tok::colon) && - Current->isOneOf(TT_ObjCMethodExpr, TT_DictLiteral)))) - next(); - - if (!Current || Precedence > PrecedenceArrowAndPeriod) - return; - - // Conditional expressions need to be parsed separately for proper nesting. - if (Precedence == prec::Conditional) { - parseConditionalExpr(); - return; - } - - // Parse unary operators, which all have a higher precedence than binary - // operators. - if (Precedence == PrecedenceUnaryOperator) { - parseUnaryOperator(); - return; - } - - FormatToken *Start = Current; - FormatToken *LatestOperator = nullptr; - unsigned OperatorIndex = 0; - - while (Current) { - // Consume operators with higher precedence. - parse(Precedence + 1); - - int CurrentPrecedence = getCurrentPrecedence(); - - if (Current && Current->is(TT_SelectorName) && - Precedence == CurrentPrecedence) { - if (LatestOperator) - addFakeParenthesis(Start, prec::Level(Precedence)); - Start = Current; - } - - // At the end of the line or when an operator with higher precedence is - // found, insert fake parenthesis and return. - 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; - } - - // Consume scopes: (), [], <> and {} - if (Current->opensScope()) { - // In fragment of a JavaScript template string can look like '}..${' and - // thus close a scope and open a new one at the same time. - while (Current && (!Current->closesScope() || Current->opensScope())) { - next(); - parse(); - } - next(); - } else { - // Operator found. - if (CurrentPrecedence == Precedence) { - if (LatestOperator) - LatestOperator->NextOperator = Current; - LatestOperator = Current; - Current->OperatorIndex = OperatorIndex; - ++OperatorIndex; - } - next(/*SkipPastLeadingComments=*/Precedence > 0); - } - } - - if (LatestOperator && (Current || Precedence > 0)) { - // LatestOperator->LastOperator = true; - if (Precedence == PrecedenceArrowAndPeriod) { - // Call expressions don't have a binary operator precedence. - addFakeParenthesis(Start, prec::Unknown); - } else { - addFakeParenthesis(Start, prec::Level(Precedence)); - } - } - } - -private: - /// \brief Gets the precedence (+1) of the given token for binary operators - /// and other tokens that we treat like binary operators. - 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_JsFatArrow)) - 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.Language == FormatStyle::LK_JavaScript) && - Current->is(Keywords.kw_instanceof)) - return prec::Relational; - if (Style.Language == FormatStyle::LK_JavaScript && - 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.Language == FormatStyle::LK_JavaScript) && - Current->isOneOf(Keywords.kw_extends, Keywords.kw_implements, - Keywords.kw_throws)) - return 0; - } - return -1; - } - - void addFakeParenthesis(FormatToken *Start, prec::Level Precedence) { - Start->FakeLParens.push_back(Precedence); - if (Precedence > prec::Unknown) - Start->StartsBinaryExpression = true; - if (Current) { - FormatToken *Previous = Current->Previous; - while (Previous->is(tok::comment) && Previous->Previous) - Previous = Previous->Previous; - ++Previous->FakeRParens; - if (Precedence > prec::Unknown) - Previous->EndsBinaryExpression = true; - } - } - - /// \brief Parse unary operator expressions and surround them with fake - /// parentheses if appropriate. - void parseUnaryOperator() { - if (!Current || Current->isNot(TT_UnaryOperator)) { - parse(PrecedenceArrowAndPeriod); - return; - } - - FormatToken *Start = Current; - next(); - parseUnaryOperator(); - - // The actual precedence doesn't matter. - addFakeParenthesis(Start, 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; - FormatToken *Current; -}; - -} // end anonymous namespace - -void TokenAnnotator::setCommentLineLevels( - SmallVectorImpl &Lines) { - const AnnotatedLine *NextNonCommentLine = nullptr; - for (SmallVectorImpl::reverse_iterator I = Lines.rbegin(), - E = Lines.rend(); - I != E; ++I) { - bool CommentLine = true; - for (const FormatToken *Tok = (*I)->First; Tok; Tok = Tok->Next) { - if (!Tok->is(tok::comment)) { - CommentLine = false; - break; - } - } - - if (NextNonCommentLine && CommentLine) { - // If the comment is currently aligned with the line immediately following - // it, that's probably intentional and we should keep it. - bool AlignedWithNextLine = - NextNonCommentLine->First->NewlinesBefore <= 1 && - NextNonCommentLine->First->OriginalColumn == - (*I)->First->OriginalColumn; - if (AlignedWithNextLine) - (*I)->Level = NextNonCommentLine->Level; - } else { - NextNonCommentLine = (*I)->First->isNot(tok::r_brace) ? (*I) : nullptr; - } - - setCommentLineLevels((*I)->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) { - for (SmallVectorImpl::iterator I = Line.Children.begin(), - E = Line.Children.end(); - I != E; ++I) { - annotate(**I); - } - AnnotatingParser Parser(Style, Line, Keywords); - Line.Type = Parser.parseLine(); - - // With very deep nesting, ExpressionParser uses lots of stack and the - // formatting algorithm is very slow. We're not going to do a good job here - // anyway - it's probably generated code being formatted by mistake. - // Just skip the whole line. - 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; -} - -// This function heuristically determines whether 'Current' starts the name of a -// function declaration. -static bool isFunctionDeclarationName(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)) { - // For 'new[]' and 'delete[]'. - if (Next->Next && Next->Next->is(tok::l_square) && - Next->Next->Next && Next->Next->Next->is(tok::r_square)) - Next = Next->Next->Next; - continue; - } - - break; - } - return nullptr; - }; - - // Find parentheses of parameter list. - 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; - } - } - } - - // Check whether parameter list can belong to a function declaration. - if (!Next || !Next->is(tok::l_paren) || !Next->MatchingParen) - return false; - // If the lines ends with "{", this is likely an function definition. - if (Line.Last->is(tok::l_brace)) - return true; - if (Next->Next == Next->MatchingParen) - return true; // Empty parentheses. - // If there is an &/&& after the r_paren, this is likely a function. - if (Next->MatchingParen->Next && - Next->MatchingParen->Next->is(TT_PointerOrReference)) - return true; - for (const FormatToken *Tok = Next->Next; Tok && Tok != Next->MatchingParen; - Tok = Tok->Next) { - if (Tok->is(tok::l_paren) && 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) { - for (SmallVectorImpl::iterator I = Line.Children.begin(), - E = Line.Children.end(); - I != E; ++I) { - calculateFormattingInformation(**I); - } - - Line.First->TotalLength = - Line.First->IsMultiline ? Style.ColumnLimit : Line.First->ColumnWidth; - FormatToken *Current = Line.First->Next; - bool InFunctionDecl = Line.MightBeFunctionDecl; - while (Current) { - if (isFunctionDeclarationName(*Current, Line)) - Current->Type = TT_FunctionDeclarationName; - if (Current->is(TT_LineComment)) { - if (Current->Previous->BlockKind == BK_BracedInit && - Current->Previous->opensScope()) - Current->SpacesRequiredBefore = Style.Cpp11BracedListStyle ? 0 : 1; - else - Current->SpacesRequiredBefore = Style.SpacesBeforeTrailingComments; - - // If we find a trailing comment, iterate backwards to determine whether - // it seems to relate to a specific parameter. If so, break before that - // parameter to avoid changing the comment's meaning. E.g. don't move 'b' - // to the previous line in: - // SomeFunction(a, - // b, // comment - // c); - 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; - } - - 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 (Current->Previous->Children.size() == 1) { - FormatToken &LastOfChild = *Current->Previous->Children[0]->Last; - ChildSize = LastOfChild.isTrailingComment() ? Style.ColumnLimit - : LastOfChild.TotalLength + 1; - } - const FormatToken *Prev = Current->Previous; - 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; - - // FIXME: Only calculate this if CanBreakBefore is true once static - // initializers etc. are sorted out. - // FIXME: Move magic numbers to a better place. - Current->SplitPenalty = 20 * Current->BindingStrength + - splitPenalty(Line, *Current, InFunctionDecl); - - 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)) { - assert(IndentLevel > 0); - --IndentLevel; - } - Current->IndentLevel = IndentLevel; - if (Current->opensBlockOrBlockTypeList(Style)) - ++IndentLevel; - } - - DEBUG({ printDebugInfo(Line); }); -} - -void TokenAnnotator::calculateUnbreakableTailLengths(AnnotatedLine &Line) { - 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; - } -} - -unsigned TokenAnnotator::splitPenalty(const AnnotatedLine &Line, - const FormatToken &Tok, - bool InFunctionDecl) { - 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.Language == FormatStyle::LK_JavaScript) { - 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; - // Prefer breaking call chains (".foo") over empty "{}", "[]" or "()". - 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; - // Slightly prefer formatting local lambda definitions like functions. - if (Right.is(TT_LambdaLSquare) && Left.is(tok::equal)) - return 35; - if (!Right.isOneOf(TT_ObjCMethodExpr, TT_LambdaLSquare, - TT_ArrayInitializerLSquare, - TT_DesignatedInitializerLSquare)) - 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.is(tok::coloncolon) || - (Right.is(tok::period) && Style.Language == FormatStyle::LK_Proto)) - return 500; - 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()) { - // Breaking before the "./->" of a chained call/member access is reasonably - // cheap, as formatting those with one call per line is generally - // desirable. In particular, it should be cheaper to break before the call - // than it is to break inside a call's parameters, which could lead to weird - // "hanging" indents. The exception is the very last "./->" to support this - // frequent pattern: - // - // aaaaaaaa.aaaaaaaa.bbbbbbb().ccccccccccccccccccccc( - // dddddddd); - // - // which might otherwise be blown up onto many lines. Here, clang-format - // won't produce "hanging" indents anyway as there is no other trailing - // call. - // - // Also apply higher penalty is not a call as that might lead to a wrapping - // like: - // - // aaaaaaa - // .aaaaaaaaa.bbbbbbbb(cccccccc); - return !Right.NextOperator || !Right.NextOperator->Previous->closesScope() - ? 150 - : 35; - } - - if (Right.is(TT_TrailingAnnotation) && - (!Right.Next || Right.Next->isNot(tok::l_paren))) { - // Moving trailing annotations to the next line is fine for ObjC method - // declarations. - if (Line.startsWith(TT_ObjCMethodSpecifier)) - return 10; - // Generally, breaking before a trailing annotation is bad unless it is - // function-like. It seems to be especially preferable to keep standard - // annotations (i.e. "const", "final" and "override") on the same line. - // Use a slightly higher penalty after ")" so that annotations like - // "const override" are kept together. - bool is_short_annotation = Right.TokenText.size() < 10; - return (Left.is(tok::r_paren) ? 100 : 120) + (is_short_annotation ? 50 : 0); - } - - // In for-loops, prefer breaking at ',' and ';'. - if (Line.startsWith(tok::kw_for) && Left.is(tok::equal)) - return 4; - - // In Objective-C method expressions, prefer breaking before "param:" over - // breaking after it. - if (Right.is(TT_SelectorName)) - return 0; - if (Left.is(tok::colon) && Left.is(TT_ObjCMethodExpr)) - return Line.MightBeFunctionDecl ? 50 : 500; - - if (Left.is(tok::l_paren) && InFunctionDecl && - Style.AlignAfterOpenBracket != FormatStyle::BAS_DontAlign) - return 100; - if (Left.is(tok::l_paren) && Left.Previous && - (Left.Previous->isOneOf(tok::kw_if, tok::kw_for) - || Left.Previous->endsSequence(tok::kw_constexpr, tok::kw_if))) - 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) - return 0; - return Left.ParameterCount > 1 ? Style.PenaltyBreakBeforeFirstCallParameter - : 19; - } - if (Left.is(TT_JavaAnnotation)) - return 50; - - if (Left.isOneOf(tok::plus, tok::comma) && Left.Previous && - Left.Previous->isLabelString() && - (Left.NextOperator || Left.OperatorIndex != 0)) - return 45; - 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)) { - // Breaking at a << is really cheap. - if (!Left.is(tok::r_paren) || Right.OperatorIndex > 0) - // Slightly prefer to break before the first one in log-like statements. - return 2; - return 1; - } - if (Left.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::spaceRequiredBetween(const AnnotatedLine &Line, - const FormatToken &Left, - const FormatToken &Right) { - if (Left.is(tok::kw_return) && Right.isNot(tok::semi)) - 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)) - return Style.SpaceInEmptyParentheses; - 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 && Style.ObjCSpaceBeforeProtocolList) - return true; - 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)) - 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 false; - 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 || - !TokenBeforeMatchingParen->isOneOf(tok::kw_typeof, tok::kw_decltype)) - return true; - } - return (Left.Tok.isLiteral() || - (!Left.isOneOf(TT_PointerOrReference, tok::l_paren) && - (Style.PointerAlignment != FormatStyle::PAS_Left || - (Line.IsMultiVariableDeclStmt && - (Left.NestingLevel == 0 || - (Left.NestingLevel == 1 && Line.First->is(tok::kw_for))))))); - } - if (Right.is(TT_FunctionTypeLParen) && Left.isNot(tok::l_paren) && - (!Left.is(TT_PointerOrReference) || - (Style.PointerAlignment != FormatStyle::PAS_Right && - !Line.IsMultiVariableDeclStmt))) - return true; - if (Left.is(TT_PointerOrReference)) - return Right.Tok.isLiteral() || Right.is(TT_BlockComment) || - (Right.isOneOf(Keywords.kw_override, Keywords.kw_final) && - !Right.is(TT_StartOfName)) || - (Right.is(tok::l_brace) && Right.BlockKind == BK_Block) || - (!Right.isOneOf(TT_PointerOrReference, TT_ArraySubscriptLSquare, - tok::l_paren) && - (Style.PointerAlignment != FormatStyle::PAS_Right && - !Line.IsMultiVariableDeclStmt) && - Left.Previous && - !Left.Previous->isOneOf(tok::l_paren, tok::coloncolon)); - if (Right.is(tok::star) && Left.is(tok::l_paren)) - return false; - if (Left.is(tok::l_square)) - return (Left.is(TT_ArrayInitializerLSquare) && - Style.SpacesInContainerLiterals && Right.isNot(tok::r_square)) || - (Left.is(TT_ArraySubscriptLSquare) && Style.SpacesInSquareBrackets && - Right.isNot(tok::r_square)); - if (Right.is(tok::r_square)) - return Right.MatchingParen && - ((Style.SpacesInContainerLiterals && - Right.MatchingParen->is(TT_ArrayInitializerLSquare)) || - (Style.SpacesInSquareBrackets && - Right.MatchingParen->is(TT_ArraySubscriptLSquare))); - if (Right.is(tok::l_square) && - !Right.isOneOf(TT_ObjCMethodExpr, TT_LambdaLSquare, - TT_DesignatedInitializerLSquare) && - !Left.isOneOf(tok::numeric_constant, TT_DictLiteral)) - return false; - if (Left.is(tok::l_brace) && Right.is(tok::r_brace)) - return !Left.Children.empty(); // No spaces in "{}". - if ((Left.is(tok::l_brace) && Left.BlockKind != BK_Block) || - (Right.is(tok::r_brace) && Right.MatchingParen && - Right.MatchingParen->BlockKind != BK_Block)) - return !Style.Cpp11BracedListStyle; - if (Left.is(TT_BlockComment)) - return !Left.TokenText.endswith("=*/"); - if (Right.is(tok::l_paren)) { - if (Left.is(tok::r_paren) && Left.is(TT_AttributeParen)) - return true; - return Line.Type == LT_ObjCDecl || Left.is(tok::semi) || - (Style.SpaceBeforeParens != FormatStyle::SBPO_Never && - (Left.isOneOf(tok::kw_if, tok::pp_elif, tok::kw_for, tok::kw_while, - tok::kw_switch, tok::kw_case, TT_ForEachMacro, - TT_ObjCForIn) || - Left.endsSequence(tok::kw_constexpr, tok::kw_if) || - (Left.isOneOf(tok::kw_try, Keywords.kw___except, tok::kw_catch, - tok::kw_new, tok::kw_delete) && - (!Left.Previous || Left.Previous->isNot(tok::period))))) || - (Style.SpaceBeforeParens == FormatStyle::SBPO_Always && - (Left.is(tok::identifier) || Left.isFunctionLikeKeyword() || - Left.is(tok::r_paren)) && - Line.Type != LT_PreprocessorDirective); - } - 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.BlockKind != 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") - return false; - if (Left.is(TT_TemplateCloser) && Left.MatchingParen && - Left.MatchingParen->Previous && - Left.MatchingParen->Previous->is(tok::period)) - // A.DoSomething(); - return false; - if (Left.is(TT_TemplateCloser) && Right.is(tok::l_square)) - return false; - return true; -} - -bool TokenAnnotator::spaceRequiredBefore(const AnnotatedLine &Line, - const FormatToken &Right) { - const FormatToken &Left = *Right.Previous; - if (Right.Tok.getIdentifierInfo() && Left.Tok.getIdentifierInfo()) - return true; // Never ever merge two identifiers. - if (Style.isCpp()) { - if (Left.is(tok::kw_operator)) - return Right.is(tok::coloncolon); - } 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; - } else if (Style.Language == FormatStyle::LK_JavaScript) { - if (Left.is(TT_JsFatArrow)) - return true; - // for await ( ... - 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(); - // An async arrow function, for example: `x = async () => foo();`, - // as opposed to calling a function called async: `x = async();` - if (Next && Next->is(TT_JsFatArrow)) - return true; - } - if ((Left.is(TT_TemplateString) && Left.TokenText.endswith("${")) || - (Right.is(TT_TemplateString) && Right.TokenText.startswith("}"))) - return false; - // In tagged template literals ("html`bar baz`"), there is no space between - // the tag identifier and the template string. getIdentifierInfo makes sure - // that the identifier is not a pseudo keyword like `yield`, either. - if (Left.is(tok::identifier) && Keywords.IsJavaScriptIdentifier(Left) && - 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)) { - // JS methods can use some keywords as names (e.g. `delete()`). - if (Line.MustBeDeclaration && Left.Tok.getIdentifierInfo()) - return false; - // Valid JS method names can include keywords, e.g. `foo.delete()` or - // `bar.instanceof()`. Recognize call positions by preceding period. - if (Left.Previous && Left.Previous->is(tok::period) && - Left.Tok.getIdentifierInfo()) - return false; - // Additional unary JavaScript operators that need a space after. - if (Left.isOneOf(tok::kw_throw, Keywords.kw_await, Keywords.kw_typeof, - tok::kw_void)) - return true; - } - if ((Left.isOneOf(Keywords.kw_let, Keywords.kw_var, Keywords.kw_in, - tok::kw_const) || - // "of" is only a keyword if it appears after another identifier - // (e.g. as "const x of y" in a for loop). - (Left.is(Keywords.kw_of) && Left.Previous && - Left.Previous->Tok.getIdentifierInfo())) && - (!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)) - // Type assertions ('expr') are not followed by whitespace. Other - // locations that should have whitespace following are identified by the - // above set of follower tokens. - return false; - if (Right.is(TT_JsNonNullAssertion)) - return false; - if (Left.is(TT_JsNonNullAssertion) && Right.is(Keywords.kw_as)) - return true; // "x! as string" - } 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.SpaceBeforeParens != FormatStyle::SBPO_Never; - 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; - } - if (Left.is(TT_ImplicitStringLiteral)) - return Right.WhitespaceRange.getBegin() != Right.WhitespaceRange.getEnd(); - if (Line.Type == LT_ObjCMethodDecl) { - if (Left.is(TT_ObjCMethodSpecifier)) - return true; - if (Left.is(tok::r_paren) && Right.is(tok::identifier)) - // Don't space between ')' and - 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 (Right.is(TT_OverloadedOperatorLParen)) - return Style.SpaceBeforeParens == FormatStyle::SBPO_Always; - if (Left.is(tok::comma)) - return true; - if (Right.is(tok::comma)) - return false; - if (Right.isOneOf(TT_CtorInitializerColon, TT_ObjCBlockLParen)) - return true; - if (Right.is(tok::colon)) { - if (Line.First->isOneOf(tok::kw_case, tok::kw_default) || - !Right.getNextNonComment() || Right.getNextNonComment()->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; - return true; - } - if (Left.is(TT_UnaryOperator)) - return Right.is(TT_BinaryOperator); - - // If the next token is a binary operator or a selector name, we have - // incorrectly classified the parenthesis as a cast. FIXME: Detect correctly. - if (Left.is(TT_CastRParen)) - return Style.SpaceAfterCStyleCast || - Right.isOneOf(TT_BinaryOperator, TT_SelectorName); - - if (Left.is(tok::greater) && Right.is(tok::greater)) - return Right.is(TT_TemplateCloser) && Left.is(TT_TemplateCloser) && - (Style.Standard != FormatStyle::LS_Cpp11 || Style.SpacesInAngles); - 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 && - Right.getPrecedence() == prec::Assignment) - return false; - if (Right.is(tok::coloncolon) && Left.is(tok::identifier)) - // Generally don't remove existing spaces between an identifier and "::". - // The identifier might actually be a macro name such as ALWAYS_INLINE. If - // this turns out to be too lenient, add analysis of the identifier itself. - return Right.WhitespaceRange.getBegin() != Right.WhitespaceRange.getEnd(); - if (Right.is(tok::coloncolon) && !Left.isOneOf(tok::l_brace, tok::comment)) - return (Left.is(TT_TemplateOpener) && - Style.Standard == FormatStyle::LS_Cpp03) || - !(Left.isOneOf(tok::l_paren, tok::r_paren, tok::l_square, - tok::kw___super, TT_TemplateCloser, TT_TemplateOpener)); - if ((Left.is(TT_TemplateOpener)) != (Right.is(TT_TemplateCloser))) - return Style.SpacesInAngles; - if ((Right.is(TT_BinaryOperator) && !Left.is(tok::l_paren)) || - (Left.isOneOf(TT_BinaryOperator, TT_ConditionalExpr) && - !Right.is(tok::r_paren))) - return true; - if (Left.is(TT_TemplateCloser) && Right.is(tok::l_paren) && - Right.isNot(TT_FunctionTypeLParen)) - return Style.SpaceBeforeParens == FormatStyle::SBPO_Always; - 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); -} - -// Returns 'true' if 'Tok' is a brace we'd want to break before in Allman style. -static bool isAllmanBrace(const FormatToken &Tok) { - return Tok.is(tok::l_brace) && Tok.BlockKind == BK_Block && - !Tok.isOneOf(TT_ObjCBlockLBrace, TT_DictLiteral); -} - -bool TokenAnnotator::mustBreakBefore(const AnnotatedLine &Line, - const FormatToken &Right) { - const FormatToken &Left = *Right.Previous; - if (Right.NewlinesBefore > 1 && Style.MaxEmptyLinesToKeep > 0) - return true; - - if (Style.Language == FormatStyle::LK_JavaScript) { - // FIXME: This might apply to other languages and token kinds. - if (Right.is(tok::string_literal) && Left.is(tok::plus) && Left.Previous && - Left.Previous->is(tok::string_literal)) - return true; - if (Left.is(TT_DictLiteral) && Left.is(tok::l_brace) && Line.Level == 0 && - Left.Previous && Left.Previous->is(tok::equal) && - Line.First->isOneOf(tok::identifier, Keywords.kw_import, tok::kw_export, - tok::kw_const) && - // kw_var/kw_let are pseudo-tokens that are tok::identifier, so match - // above. - !Line.First->isOneOf(Keywords.kw_var, Keywords.kw_let)) - // Object literals on the top level of a file are treated as "enum-style". - // Each key/value pair is put on a separate line, instead of bin-packing. - return true; - if (Left.is(tok::l_brace) && Line.Level == 0 && - (Line.startsWith(tok::kw_enum) || - Line.startsWith(tok::kw_const, tok::kw_enum) || - Line.startsWith(tok::kw_export, tok::kw_enum) || - Line.startsWith(tok::kw_export, tok::kw_const, tok::kw_enum))) - // JavaScript top-level enum key/value pairs are put on separate lines - // instead of bin-packing. - return true; - if (Right.is(tok::r_brace) && Left.is(tok::l_brace) && - !Left.Children.empty()) - // Support AllowShortFunctionsOnASingleLine for JavaScript. - return Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_None || - Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_Empty || - (Left.NestingLevel == 0 && Line.Level == 0 && - Style.AllowShortFunctionsOnASingleLine & - FormatStyle::SFS_InlineOnly); - } else if (Style.Language == FormatStyle::LK_Java) { - if (Right.is(tok::plus) && Left.is(tok::string_literal) && Right.Next && - Right.Next->is(tok::string_literal)) - return true; - } else if (Style.Language == FormatStyle::LK_Cpp || - Style.Language == FormatStyle::LK_ObjC || - Style.Language == FormatStyle::LK_Proto) { - if (Left.isStringLiteral() && Right.isStringLiteral()) - return true; - } - - // If the last token before a '}', ']', or ')' is a comma or a trailing - // comment, the intention is to insert a line break after it in order to make - // shuffling around entries easier. Import statements, especially in - // JavaScript, can be an exception to this rule. - if (Style.JavaScriptWrapImports || Line.Type != LT_ImportStatement) { - const FormatToken *BeforeClosingBrace = nullptr; - if ((Left.isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) || - (Style.Language == FormatStyle::LK_JavaScript && - Left.is(tok::l_paren))) && - Left.BlockKind != BK_Block && Left.MatchingParen) - BeforeClosingBrace = Left.MatchingParen->Previous; - else if (Right.MatchingParen && - (Right.MatchingParen->isOneOf(tok::l_brace, - TT_ArrayInitializerLSquare) || - (Style.Language == FormatStyle::LK_JavaScript && - 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.BlockKind != BK_BracedInit && - Left.isNot(TT_CtorInitializerColon) && - (Right.NewlinesBefore > 0 && Right.HasUnescapedNewline); - if (Left.isTrailingComment()) - return true; - if (Right.Previous->IsUnterminatedLiteral) - return true; - if (Right.is(tok::lessless) && Right.Next && - Right.Previous->is(tok::string_literal) && - Right.Next->is(tok::string_literal)) - return true; - if (Right.Previous->ClosesTemplateDeclaration && - Right.Previous->MatchingParen && - Right.Previous->MatchingParen->NestingLevel == 0 && - Style.AlwaysBreakTemplateDeclarations) - return true; - if (Right.is(TT_CtorInitializerComma) && - Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma && - !Style.ConstructorInitializerAllOnOneLineOrOnePerLine) - return true; - if (Right.is(TT_CtorInitializerColon) && - Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma && - !Style.ConstructorInitializerAllOnOneLineOrOnePerLine) - return true; - // Break only if we have multiple inheritance. - if (Style.BreakBeforeInheritanceComma && - Right.is(TT_InheritanceComma)) - return true; - if (Right.is(tok::string_literal) && Right.TokenText.startswith("R\"")) - // Raw string literals are special wrt. line breaks. The author has made a - // deliberate choice and might have aligned the contents of the string - // literal accordingly. Thus, we try keep existing line breaks. - return Right.NewlinesBefore > 0; - if ((Right.Previous->is(tok::l_brace) || - (Right.Previous->is(tok::less) && - Right.Previous->Previous && - Right.Previous->Previous->is(tok::equal)) - ) && - Right.NestingLevel == 1 && Style.Language == FormatStyle::LK_Proto) { - // Don't put enums or option definitions onto single lines in protocol - // buffers. - return true; - } - if (Right.is(TT_InlineASMBrace)) - return Right.HasUnescapedNewline; - if (isAllmanBrace(Left) || isAllmanBrace(Right)) - return (Line.startsWith(tok::kw_enum) && Style.BraceWrapping.AfterEnum) || - (Line.startsWith(tok::kw_class) && Style.BraceWrapping.AfterClass) || - (Line.startsWith(tok::kw_struct) && Style.BraceWrapping.AfterStruct); - if (Left.is(TT_ObjCBlockLBrace) && !Style.AllowShortBlocksOnASingleLine) - return true; - - if ((Style.Language == FormatStyle::LK_Java || - Style.Language == FormatStyle::LK_JavaScript) && - Left.is(TT_LeadingJavaAnnotation) && - Right.isNot(TT_LeadingJavaAnnotation) && Right.isNot(tok::l_paren) && - (Line.Last->is(tok::l_brace) || Style.BreakAfterJavaFieldAnnotations)) - return true; - - return false; -} - -bool TokenAnnotator::canBreakBefore(const AnnotatedLine &Line, - const FormatToken &Right) { - const FormatToken &Left = *Right.Previous; - - // Language-specific stuff. - 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.Language == FormatStyle::LK_JavaScript) { - const FormatToken *NonComment = Right.getPreviousNonComment(); - if (NonComment && - NonComment->isOneOf(tok::kw_return, 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_abstract, - Keywords.kw_get, Keywords.kw_set)) - return false; // Otherwise automatic semicolon insertion would trigger. - if (Left.is(TT_JsFatArrow) && Right.is(tok::l_brace)) - return false; - if (Left.is(TT_JsTypeColon)) - return true; - if (Right.NestingLevel == 0 && Right.is(Keywords.kw_is)) - 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; // must not break before as in 'x as type' casts - if (Left.is(Keywords.kw_as)) - return true; - if (Left.is(TT_JsNonNullAssertion)) - 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)) - // See grammar for 'declare' statements at: - // https://github.com/Microsoft/TypeScript/blob/master/doc/spec.md#A.10 - return false; - if (Left.isOneOf(Keywords.kw_module, tok::kw_namespace) && - Right.isOneOf(tok::identifier, tok::string_literal)) - return false; // must not break in "module foo { ...}" - if (Right.is(TT_TemplateString) && Right.closesScope()) - 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 || - (Style.PointerAlignment == 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()) - // We rely on MustBreakBefore being set correctly here as we should not - // change the "binding" behavior of a comment. - // The first comment in a braced lists is always interpreted as belonging to - // the first list element. Otherwise, it should be placed outside of the - // list. - return Left.BlockKind == BK_BracedInit || - (Left.is(TT_CtorInitializerColon) && - Style.BreakConstructorInitializers == - FormatStyle::BCIS_AfterColon); - if (Left.is(tok::question) && Right.is(tok::colon)) - return false; - if (Right.is(TT_ConditionalExpr) || Right.is(tok::question)) - return Style.BreakBeforeTernaryOperators; - if (Left.is(TT_ConditionalExpr) || Left.is(tok::question)) - return !Style.BreakBeforeTernaryOperators; - if (Right.is(TT_InheritanceColon)) - return true; - 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)) - return true; - if (Right.is(TT_SelectorName) || (Right.is(tok::identifier) && Right.Next && - Right.Next->is(TT_ObjCMethodExpr))) - return Left.isNot(tok::period); // FIXME: Properly parse ObjC calls. - if (Left.is(tok::r_paren) && Line.Type == LT_ObjCProperty) - return true; - if (Left.ClosesTemplateDeclaration || Left.is(TT_FunctionAnnotationRParen)) - 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.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::l_paren) && Left.is(TT_AttributeParen)) - 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(tok::r_paren) || Right.is(TT_TemplateCloser)) - return false; - if (Right.is(tok::r_square) && Right.MatchingParen && - Right.MatchingParen->is(TT_LambdaLSquare)) - return false; - - // We only break before r_brace if there was a corresponding break before - // the l_brace, which is tracked by BreakBeforeClosingBrace. - if (Right.is(tok::r_brace)) - return Right.MatchingParen && Right.MatchingParen->BlockKind == BK_Block; - - // Allow breaking after a trailing annotation, e.g. after a method - // declaration. - 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)) - return true; - - 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; - 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.BreakBeforeInheritanceComma) - return false; - if (Right.is(TT_InheritanceComma) && Style.BreakBeforeInheritanceComma) - 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.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; - 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) { - 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->Type) - << " S=" << Tok->SpacesRequiredBefore - << " B=" << Tok->BlockParameterCount - << " BK=" << Tok->BlockKind - << " P=" << Tok->SplitPenalty << " Name=" << Tok->Tok.getName() - << " L=" << Tok->TotalLength << " PPK=" << Tok->PackingKind - << " FakeLParens="; - for (unsigned i = 0, e = Tok->FakeLParens.size(); i != e; ++i) - llvm::errs() << Tok->FakeLParens[i] << "/"; - llvm::errs() << " FakeRParens=" << Tok->FakeRParens; - llvm::errs() << " Text='" << Tok->TokenText << "'\n"; - if (!Tok->Next) - assert(Tok == Line.Last); - Tok = Tok->Next; - } - llvm::errs() << "----\n"; -} - -} // namespace format -} // namespace clang +//===--- TokenAnnotator.cpp - Format C++ code -----------------------------===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// +/// +/// \file +/// \brief This file implements a token annotator, i.e. creates +/// \c AnnotatedTokens out of \c FormatTokens with required extra information. +/// +//===----------------------------------------------------------------------===// + +#include "TokenAnnotator.h" +#include "clang/Basic/SourceManager.h" +#include "llvm/ADT/SmallPtrSet.h" +#include "llvm/Support/Debug.h" + +#define DEBUG_TYPE "format-token-annotator" + +namespace clang { +namespace format { + +namespace { + +/// \brief A parser that gathers additional information about tokens. +/// +/// The \c TokenAnnotator tries to match parenthesis and square brakets and +/// store a parenthesis levels. It also tries to resolve matching "<" and ">" +/// into template parameter lists. +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, /*IsExpression=*/false)); + resetTokenMetadata(CurrentToken); + } + +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); + + // If this angle is in the context of an expression, we need to be more + // hesitant to detect it as opening template parameters. + bool InExprContext = Contexts.back().IsExpression; + + Contexts.back().IsExpression = false; + // If there's a template keyword before the opening angle bracket, this is a + // template parameter, not an argument. + Contexts.back().InTemplateArgument = + Left->Previous && Left->Previous->Tok.isNot(tok::kw_template); + + if (Style.Language == FormatStyle::LK_Java && + CurrentToken->is(tok::question)) + next(); + + while (CurrentToken) { + if (CurrentToken->is(tok::greater)) { + Left->MatchingParen = CurrentToken; + CurrentToken->MatchingParen = Left; + CurrentToken->Type = 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.Language != FormatStyle::LK_Proto && + Style.Language != FormatStyle::LK_TextProto)) + return false; + // If a && or || is found and interpreted as a binary operator, this set + // of angles is likely part of something like "a < b && c > d". If the + // angles are inside an expression, the ||/&& might also be a binary + // operator that was misinterpreted because we are parsing template + // parameters. + // FIXME: This is getting out of hand, write a decent parser. + 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->Type = TT_SelectorName; + } + } + if (!consumeToken()) + return false; + } + return false; + } + + bool parseParens(bool LookForDecls = false) { + if (!CurrentToken) + return false; + FormatToken *Left = CurrentToken->Previous; + Left->ParentBracket = Contexts.back().ContextKind; + ScopedContextCreator ContextCreator(*this, tok::l_paren, 1); + + // FIXME: This is a bit of a hack. Do better. + Contexts.back().ColonIsForRangeExpr = + Contexts.size() == 2 && Contexts[0].ColonIsForRangeExpr; + + bool StartsObjCMethodExpr = false; + if (CurrentToken->is(tok::caret)) { + // (^ can start a block type. + Left->Type = TT_ObjCBlockLParen; + } else if (FormatToken *MaybeSel = Left->Previous) { + // @selector( starts a selector. + if (MaybeSel->isObjCAtKeyword(tok::objc_selector) && MaybeSel->Previous && + MaybeSel->Previous->is(tok::at)) { + StartsObjCMethodExpr = true; + } + } + + if (Left->is(TT_OverloadedOperatorLParen)) { + Contexts.back().IsExpression = false; + } else if (Style.Language == FormatStyle::LK_JavaScript && + (Line.startsWith(Keywords.kw_type, tok::identifier) || + Line.startsWith(tok::kw_export, Keywords.kw_type, + tok::identifier))) { + // type X = (...); + // export type X = (...); + Contexts.back().IsExpression = false; + } else if (Left->Previous && + (Left->Previous->isOneOf(tok::kw_static_assert, tok::kw_decltype, + tok::kw_if, tok::kw_while, tok::l_paren, + tok::comma) || + Left->Previous->endsSequence(tok::kw_constexpr, tok::kw_if) || + Left->Previous->is(TT_BinaryOperator))) { + // static_assert, if and while usually contain expressions. + Contexts.back().IsExpression = true; + } else if (Style.Language == FormatStyle::LK_JavaScript && Left->Previous && + (Left->Previous->is(Keywords.kw_function) || + (Left->Previous->endsSequence(tok::identifier, + Keywords.kw_function)))) { + // function(...) or function f(...) + Contexts.back().IsExpression = false; + } else if (Style.Language == FormatStyle::LK_JavaScript && Left->Previous && + Left->Previous->is(TT_JsTypeColon)) { + // let x: (SomeType); + Contexts.back().IsExpression = false; + } else if (Left->Previous && Left->Previous->is(tok::r_square) && + Left->Previous->MatchingParen && + Left->Previous->MatchingParen->is(TT_LambdaLSquare)) { + // This is a parameter list of a lambda expression. + Contexts.back().IsExpression = false; + } else if (Line.InPPDirective && + (!Left->Previous || !Left->Previous->is(tok::identifier))) { + Contexts.back().IsExpression = true; + } else if (Contexts[Contexts.size() - 2].CaretFound) { + // This is the parameter list of an ObjC block. + Contexts.back().IsExpression = false; + } else if (Left->Previous && Left->Previous->is(tok::kw___attribute)) { + Left->Type = TT_AttributeParen; + } else if (Left->Previous && Left->Previous->is(TT_ForEachMacro)) { + // The first argument to a foreach macro is a declaration. + Contexts.back().IsForEachMacro = true; + Contexts.back().IsExpression = false; + } else if (Left->Previous && Left->Previous->MatchingParen && + Left->Previous->MatchingParen->is(TT_ObjCBlockLParen)) { + Contexts.back().IsExpression = false; + } else if (!Line.MustBeDeclaration && !Line.InPPDirective) { + bool IsForOrCatch = + Left->Previous && Left->Previous->isOneOf(tok::kw_for, tok::kw_catch); + Contexts.back().IsExpression = !IsForOrCatch; + } + + if (StartsObjCMethodExpr) { + Contexts.back().ColonIsObjCMethodExpr = true; + Left->Type = TT_ObjCMethodExpr; + } + + bool MightBeFunctionType = !Contexts[Contexts.size() - 2].IsExpression; + bool ProbablyFunctionType = CurrentToken->isOneOf(tok::star, tok::amp); + bool HasMultipleLines = false; + bool HasMultipleParametersOnALine = false; + bool MightBeObjCForRangeLoop = + Left->Previous && Left->Previous->is(tok::kw_for); + while (CurrentToken) { + // LookForDecls is set when "if (" has been seen. Check for + // 'identifier' '*' 'identifier' followed by not '=' -- this + // '*' has to be a binary operator but determineStarAmpUsage() will + // categorize it as an unary operator, so set the right type here. + 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->Type = 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 (MightBeFunctionType && ProbablyFunctionType && CurrentToken->Next && + (CurrentToken->Next->is(tok::l_paren) || + (CurrentToken->Next->is(tok::l_square) && Line.MustBeDeclaration))) + Left->Type = TT_FunctionTypeLParen; + Left->MatchingParen = CurrentToken; + CurrentToken->MatchingParen = Left; + + if (CurrentToken->Next && CurrentToken->Next->is(tok::l_brace) && + Left->Previous && Left->Previous->is(tok::l_paren)) { + // Detect the case where macros are used to generate lambdas or + // function bodies, e.g.: + // auto my_lambda = MARCO((Type *type, int i) { .. body .. }); + for (FormatToken *Tok = Left; Tok != CurrentToken; Tok = Tok->Next) { + if (Tok->is(TT_BinaryOperator) && + Tok->isOneOf(tok::star, tok::amp, tok::ampamp)) + Tok->Type = TT_PointerOrReference; + } + } + + if (StartsObjCMethodExpr) { + CurrentToken->Type = TT_ObjCMethodExpr; + if (Contexts.back().FirstObjCSelectorName) { + Contexts.back().FirstObjCSelectorName->LongestObjCSelectorName = + Contexts.back().LongestObjCSelectorName; + } + } + + if (Left->is(TT_AttributeParen)) + CurrentToken->Type = TT_AttributeParen; + if (Left->Previous && Left->Previous->is(TT_JavaAnnotation)) + CurrentToken->Type = TT_JavaAnnotation; + if (Left->Previous && Left->Previous->is(TT_LeadingJavaAnnotation)) + CurrentToken->Type = TT_LeadingJavaAnnotation; + + if (!HasMultipleLines) + Left->PackingKind = PPK_Inconclusive; + else if (HasMultipleParametersOnALine) + Left->PackingKind = PPK_BinPacked; + else + Left->PackingKind = PPK_OnePerLine; + + next(); + return true; + } + if (CurrentToken->isOneOf(tok::r_square, tok::r_brace)) + return false; + + if (CurrentToken->is(tok::l_brace)) + Left->Type = TT_Unknown; // Not TT_ObjCBlockLParen + if (CurrentToken->is(tok::comma) && CurrentToken->Next && + !CurrentToken->Next->HasUnescapedNewline && + !CurrentToken->Next->isTrailingComment()) + HasMultipleParametersOnALine = true; + if ((CurrentToken->Previous->isOneOf(tok::kw_const, tok::kw_auto) || + CurrentToken->Previous->isSimpleTypeSpecifier()) && + !CurrentToken->is(tok::l_brace)) + Contexts.back().IsExpression = false; + if (CurrentToken->isOneOf(tok::semi, tok::colon)) + MightBeObjCForRangeLoop = false; + if (MightBeObjCForRangeLoop && CurrentToken->is(Keywords.kw_in)) + CurrentToken->Type = TT_ObjCForIn; + // When we discover a 'new', we set CanBeExpression to 'false' in order to + // parse the type correctly. Reset that after a comma. + if (CurrentToken->is(tok::comma)) + Contexts.back().CanBeExpression = true; + + FormatToken *Tok = CurrentToken; + if (!consumeToken()) + return false; + updateParameterCount(Left, Tok); + if (CurrentToken && CurrentToken->HasUnescapedNewline) + HasMultipleLines = true; + } + return false; + } + + bool parseSquare() { + if (!CurrentToken) + return false; + + // A '[' could be an index subscript (after an identifier or after + // ')' or ']'), it could be the start of an Objective-C method + // expression, or it could the start of an Objective-C array literal. + FormatToken *Left = CurrentToken->Previous; + Left->ParentBracket = Contexts.back().ContextKind; + FormatToken *Parent = Left->getPreviousNonComment(); + + // Cases where '>' is followed by '['. + // In C++, this can happen either in array of templates (foo[10]) + // or when array is a nested template type (unique_ptr[]>). + bool CppArrayTemplates = + Style.isCpp() && Parent && + Parent->is(TT_TemplateCloser) && + (Contexts.back().CanBeExpression || Contexts.back().IsExpression || + Contexts.back().InTemplateArgument); + + bool StartsObjCMethodExpr = + !CppArrayTemplates && Style.isCpp() && + Contexts.back().CanBeExpression && Left->isNot(TT_LambdaLSquare) && + CurrentToken->isNot(tok::l_brace) && + (!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; + + FormatToken *PreviousNoneOfConstVolatileReference = Parent; + while (PreviousNoneOfConstVolatileReference && + PreviousNoneOfConstVolatileReference->isOneOf( + tok::kw_const, tok::kw_volatile, tok::amp, tok::ampamp)) + PreviousNoneOfConstVolatileReference = + PreviousNoneOfConstVolatileReference->getPreviousNonComment(); + + bool CppStructuredBindings = + Style.isCpp() && PreviousNoneOfConstVolatileReference && + PreviousNoneOfConstVolatileReference->is(tok::kw_auto); + + unsigned BindingIncrease = 1; + if (Left->is(TT_Unknown)) { + if (CppStructuredBindings) { + Left->Type = TT_StructuredBindingLSquare; + } else if (StartsObjCMethodExpr) { + Left->Type = TT_ObjCMethodExpr; + } else if (Style.Language == FormatStyle::LK_JavaScript && Parent && + Contexts.back().ContextKind == tok::l_brace && + Parent->isOneOf(tok::l_brace, tok::comma)) { + Left->Type = TT_JsComputedPropertyName; + } else if (Style.isCpp() && Contexts.back().ContextKind == tok::l_brace && + Parent && Parent->isOneOf(tok::l_brace, tok::comma)) { + Left->Type = TT_DesignatedInitializerLSquare; + } else if (CurrentToken->is(tok::r_square) && Parent && + Parent->is(TT_TemplateCloser)) { + Left->Type = TT_ArraySubscriptLSquare; + } else if (Style.Language == FormatStyle::LK_Proto || + (!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, + // Should only be relevant to JavaScript: + tok::kw_default))) { + Left->Type = TT_ArrayInitializerLSquare; + } else { + BindingIncrease = 10; + Left->Type = TT_ArraySubscriptLSquare; + } + } + + ScopedContextCreator ContextCreator(*this, tok::l_square, BindingIncrease); + Contexts.back().IsExpression = true; + if (Style.Language == FormatStyle::LK_JavaScript && Parent && + Parent->is(TT_JsTypeColon)) + Contexts.back().IsExpression = false; + + Contexts.back().ColonIsObjCMethodExpr = StartsObjCMethodExpr; + + while (CurrentToken) { + if (CurrentToken->is(tok::r_square)) { + if (CurrentToken->Next && CurrentToken->Next->is(tok::l_paren) && + Left->is(TT_ObjCMethodExpr)) { + // An ObjC method call is rarely followed by an open parenthesis. + // FIXME: Do we incorrectly label ":" with this? + StartsObjCMethodExpr = false; + Left->Type = TT_Unknown; + } + if (StartsObjCMethodExpr && CurrentToken->Previous != Left) { + CurrentToken->Type = TT_ObjCMethodExpr; + // determineStarAmpUsage() thinks that '*' '[' is allocating an + // array of pointers, but if '[' starts a selector then '*' is a + // binary operator. + if (Parent && Parent->is(TT_PointerOrReference)) + Parent->Type = TT_BinaryOperator; + } + Left->MatchingParen = CurrentToken; + CurrentToken->MatchingParen = Left; + 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 (Left->isOneOf(TT_ArraySubscriptLSquare, + TT_DesignatedInitializerLSquare)) { + Left->Type = TT_ObjCMethodExpr; + StartsObjCMethodExpr = true; + Contexts.back().ColonIsObjCMethodExpr = true; + if (Parent && Parent->is(tok::r_paren)) + Parent->Type = TT_CastRParen; + } + ColonFound = true; + } + if (CurrentToken->is(tok::comma) && Left->is(TT_ObjCMethodExpr) && + !ColonFound) + Left->Type = TT_ArrayInitializerLSquare; + FormatToken *Tok = CurrentToken; + if (!consumeToken()) + return false; + updateParameterCount(Left, Tok); + } + return false; + } + + bool parseBrace() { + if (CurrentToken) { + FormatToken *Left = CurrentToken->Previous; + Left->ParentBracket = Contexts.back().ContextKind; + + if (Contexts.back().CaretFound) + Left->Type = TT_ObjCBlockLBrace; + Contexts.back().CaretFound = false; + + ScopedContextCreator ContextCreator(*this, tok::l_brace, 1); + Contexts.back().ColonIsDictLiteral = true; + if (Left->BlockKind == BK_BracedInit) + Contexts.back().IsExpression = true; + if (Style.Language == FormatStyle::LK_JavaScript && Left->Previous && + Left->Previous->is(TT_JsTypeColon)) + Contexts.back().IsExpression = false; + + while (CurrentToken) { + if (CurrentToken->is(tok::r_brace)) { + Left->MatchingParen = CurrentToken; + CurrentToken->MatchingParen = Left; + next(); + return true; + } + if (CurrentToken->isOneOf(tok::r_paren, tok::r_square)) + return false; + updateParameterCount(Left, 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) && + (Previous->Tok.getIdentifierInfo() || + Previous->is(tok::string_literal))) + Previous->Type = TT_SelectorName; + if (CurrentToken->is(tok::colon) || + Style.Language == FormatStyle::LK_JavaScript) + Left->Type = TT_DictLiteral; + } + if (CurrentToken->is(tok::comma) && + Style.Language == FormatStyle::LK_JavaScript) + Left->Type = TT_DictLiteral; + if (!consumeToken()) + return false; + } + } + return true; + } + + void updateParameterCount(FormatToken *Left, FormatToken *Current) { + if (Current->is(tok::l_brace) && Current->BlockKind == 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->Type = TT_ConditionalExpr; + next(); + return true; + } + if (!consumeToken()) + return false; + } + return false; + } + + bool parseTemplateDeclaration() { + if (CurrentToken && CurrentToken->is(tok::less)) { + CurrentToken->Type = 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->Type = TT_ObjCMethodSpecifier; + break; + case tok::colon: + if (!Tok->Previous) + return false; + // Colons from ?: are handled in parseConditional(). + if (Style.Language == FormatStyle::LK_JavaScript) { + if (Contexts.back().ColonIsForRangeExpr || // colon in for loop + (Contexts.size() == 1 && // switch/case labels + !Line.First->isOneOf(tok::kw_enum, tok::kw_case)) || + Contexts.back().ContextKind == tok::l_paren || // function params + Contexts.back().ContextKind == tok::l_square || // array type + (!Contexts.back().IsExpression && + Contexts.back().ContextKind == tok::l_brace) || // object type + (Contexts.size() == 1 && + Line.MustBeDeclaration)) { // method/property declaration + Contexts.back().IsExpression = false; + Tok->Type = TT_JsTypeColon; + break; + } + } + if (Contexts.back().ColonIsDictLiteral || + Style.Language == FormatStyle::LK_Proto || + Style.Language == FormatStyle::LK_TextProto) { + Tok->Type = TT_DictLiteral; + if (Style.Language == FormatStyle::LK_TextProto) { + if (FormatToken *Previous = Tok->getPreviousNonComment()) + Previous->Type = TT_SelectorName; + } + } else if (Contexts.back().ColonIsObjCMethodExpr || + Line.startsWith(TT_ObjCMethodSpecifier)) { + Tok->Type = TT_ObjCMethodExpr; + const FormatToken *BeforePrevious = Tok->Previous->Previous; + if (!BeforePrevious || + !(BeforePrevious->is(TT_CastRParen) || + (BeforePrevious->is(TT_ObjCMethodExpr) && + BeforePrevious->is(tok::colon))) || + BeforePrevious->is(tok::r_square) || + Contexts.back().LongestObjCSelectorName == 0) { + Tok->Previous->Type = TT_SelectorName; + if (Tok->Previous->ColumnWidth > + Contexts.back().LongestObjCSelectorName) + Contexts.back().LongestObjCSelectorName = + Tok->Previous->ColumnWidth; + if (!Contexts.back().FirstObjCSelectorName) + Contexts.back().FirstObjCSelectorName = Tok->Previous; + } + } else if (Contexts.back().ColonIsForRangeExpr) { + Tok->Type = TT_RangeBasedForLoopColon; + } else if (CurrentToken && CurrentToken->is(tok::numeric_constant)) { + Tok->Type = TT_BitFieldColon; + } else if (Contexts.size() == 1 && + !Line.First->isOneOf(tok::kw_enum, tok::kw_case)) { + if (Tok->getPreviousNonComment()->isOneOf(tok::r_paren, + tok::kw_noexcept)) + Tok->Type = TT_CtorInitializerColon; + else + Tok->Type = TT_InheritanceColon; + } else if (Tok->Previous->is(tok::identifier) && Tok->Next && + Tok->Next->isOneOf(tok::r_paren, tok::comma)) { + // This handles a special macro in ObjC code where selectors including + // the colon are passed as macro arguments. + Tok->Type = TT_ObjCMethodExpr; + } else if (Contexts.back().ContextKind == tok::l_paren) { + Tok->Type = TT_InlineASMColon; + } + break; + case tok::pipe: + case tok::amp: + // | and & in declarations/type expressions represent union and + // intersection types, respectively. + if (Style.Language == FormatStyle::LK_JavaScript && + !Contexts.back().IsExpression) + Tok->Type = TT_JsTypeOperator; + break; + case tok::kw_if: + case tok::kw_while: + if (Tok->is(tok::kw_if) && CurrentToken && CurrentToken->is(tok::kw_constexpr)) + next(); + if (CurrentToken && CurrentToken->is(tok::l_paren)) { + next(); + if (!parseParens(/*LookForDecls=*/true)) + return false; + } + break; + case tok::kw_for: + if (Style.Language == FormatStyle::LK_JavaScript) { + if (Tok->Previous && Tok->Previous->is(tok::period)) + break; + // JS' for await ( ... + if (CurrentToken && CurrentToken->is(Keywords.kw_await)) + next(); + } + Contexts.back().ColonIsForRangeExpr = true; + next(); + if (!parseParens()) + return false; + break; + case tok::l_paren: + // When faced with 'operator()()', the kw_operator handler incorrectly + // marks the first l_paren as a OverloadedOperatorLParen. Here, we make + // the first two parens OverloadedOperators and the second l_paren an + // OverloadedOperatorLParen. + if (Tok->Previous && + Tok->Previous->is(tok::r_paren) && + Tok->Previous->MatchingParen && + Tok->Previous->MatchingParen->is(TT_OverloadedOperatorLParen)) { + Tok->Previous->Type = TT_OverloadedOperator; + Tok->Previous->MatchingParen->Type = TT_OverloadedOperator; + Tok->Type = TT_OverloadedOperatorLParen; + } + + if (!parseParens()) + return false; + if (Line.MustBeDeclaration && Contexts.size() == 1 && + !Contexts.back().IsExpression && !Line.startsWith(TT_ObjCProperty) && + (!Tok->Previous || + !Tok->Previous->isOneOf(tok::kw_decltype, 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->Type != TT_DictLiteral) + Previous->Type = TT_SelectorName; + } + if (!parseBrace()) + return false; + break; + case tok::less: + if (parseAngle()) { + Tok->Type = TT_TemplateOpener; + if (Style.Language == FormatStyle::LK_TextProto) { + FormatToken *Previous = Tok->getPreviousNonComment(); + if (Previous && Previous->Type != TT_DictLiteral) + Previous->Type = TT_SelectorName; + } + } else { + Tok->Type = TT_BinaryOperator; + NonTemplateLess.insert(Tok); + CurrentToken = Tok; + next(); + } + break; + case tok::r_paren: + case tok::r_square: + return false; + case tok::r_brace: + // Lines can start with '}'. + if (Tok->Previous) + return false; + break; + case tok::greater: + Tok->Type = TT_BinaryOperator; + break; + case tok::kw_operator: + while (CurrentToken && + !CurrentToken->isOneOf(tok::l_paren, tok::semi, tok::r_paren)) { + if (CurrentToken->isOneOf(tok::star, tok::amp)) + CurrentToken->Type = TT_PointerOrReference; + consumeToken(); + if (CurrentToken && + CurrentToken->Previous->isOneOf(TT_BinaryOperator, tok::comma)) + CurrentToken->Previous->Type = TT_OverloadedOperator; + } + if (CurrentToken) { + CurrentToken->Type = TT_OverloadedOperatorLParen; + if (CurrentToken->Previous->is(TT_BinaryOperator)) + CurrentToken->Previous->Type = TT_OverloadedOperator; + } + break; + case tok::question: + if (Style.Language == FormatStyle::LK_JavaScript && Tok->Next && + Tok->Next->isOneOf(tok::semi, tok::comma, tok::colon, tok::r_paren, + tok::r_brace)) { + // Question marks before semicolons, colons, etc. indicate optional + // types (fields, parameters), e.g. + // function(x?: string, y?) {...} + // class X { y?; } + Tok->Type = TT_JsTypeOptionalQuestion; + break; + } + // Declarations cannot be conditional expressions, this can only be part + // of a type declaration. + if (Line.MustBeDeclaration && !Contexts.back().IsExpression && + Style.Language == FormatStyle::LK_JavaScript) + break; + parseConditional(); + break; + case tok::kw_template: + parseTemplateDeclaration(); + break; + case tok::comma: + if (Contexts.back().InCtorInitializer) + Tok->Type = TT_CtorInitializerComma; + else if (Contexts.back().InInheritanceList) + Tok->Type = TT_InheritanceComma; + else if (Contexts.back().FirstStartOfName && + (Contexts.size() == 1 || Line.startsWith(tok::kw_for))) { + Contexts.back().FirstStartOfName->PartOfMultiVariableDeclStmt = true; + Line.IsMultiVariableDeclStmt = true; + } + if (Contexts.back().IsForEachMacro) + Contexts.back().IsExpression = true; + break; + case tok::identifier: + if (Tok->isOneOf(Keywords.kw___has_include, + Keywords.kw___has_include_next)) { + parseHasInclude(); + } + break; + default: + break; + } + return true; + } + + void parseIncludeDirective() { + if (CurrentToken && CurrentToken->is(tok::less)) { + next(); + while (CurrentToken) { + // Mark tokens up to the trailing line comments as implicit string + // literals. + if (CurrentToken->isNot(tok::comment) && + !CurrentToken->TokenText.startswith("//")) + CurrentToken->Type = TT_ImplicitStringLiteral; + next(); + } + } + } + + void parseWarningOrError() { + next(); + // We still want to format the whitespace left of the first token of the + // warning or error. + next(); + while (CurrentToken) { + CurrentToken->Type = TT_ImplicitStringLiteral; + next(); + } + } + + void parsePragma() { + next(); // Consume "pragma". + if (CurrentToken && + CurrentToken->isOneOf(Keywords.kw_mark, Keywords.kw_option)) { + bool IsMark = CurrentToken->is(Keywords.kw_mark); + next(); // Consume "mark". + next(); // Consume first token (so we fix leading whitespace). + while (CurrentToken) { + if (IsMark || CurrentToken->Previous->is(TT_BinaryOperator)) + CurrentToken->Type = 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.Language == FormatStyle::LK_JavaScript && IsFirstToken) { + // JavaScript files can contain shebang lines of the form: + // #!/usr/bin/env node + // Treat these like C++ #include directives. + while (CurrentToken) { + // Tokens cannot be comments here. + CurrentToken->Type = TT_ImplicitStringLiteral; + next(); + } + return LT_ImportStatement; + } + + if (CurrentToken->Tok.is(tok::numeric_constant)) { + CurrentToken->SpacesRequiredBefore = 1; + return Type; + } + // Hashes in the middle of a line can lead to any strange token + // sequence. + if (!CurrentToken->Tok.getIdentifierInfo()) + return Type; + 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; + 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() { + NonTemplateLess.clear(); + if (CurrentToken->is(tok::hash)) + return parsePreprocessorDirective(); + + // Directly allow to 'import ' to support protocol buffer + // definitions (code.google.com/p/protobuf) or missing "#" (either way we + // should not break the line). + 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 this line starts and ends in '<' and '>', respectively, it is likely + // part of "#define ". + if (CurrentToken->is(tok::less) && Line.Last->is(tok::greater)) { + parseIncludeDirective(); + return LT_ImportStatement; + } + + // In .proto files, top-level options are very similar to import statements + // and should not be line-wrapped. + if (Style.Language == FormatStyle::LK_Proto && Line.Level == 0 && + CurrentToken->is(Keywords.kw_option)) { + next(); + if (CurrentToken && CurrentToken->is(tok::identifier)) + return LT_ImportStatement; + } + + bool KeywordVirtualFound = false; + bool ImportStatement = false; + + // import {...} from '...'; + if (Style.Language == FormatStyle::LK_JavaScript && + CurrentToken->is(Keywords.kw_import)) + ImportStatement = true; + + while (CurrentToken) { + if (CurrentToken->is(tok::kw_virtual)) + KeywordVirtualFound = true; + if (Style.Language == FormatStyle::LK_JavaScript) { + // export {...} from '...'; + // An export followed by "from 'some string';" is a re-export from + // another module identified by a URI and is treated as a + // LT_ImportStatement (i.e. prevent wraps on it for long URIs). + // Just "export {...};" or "export class ..." should not be treated as + // an import in this sense. + 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; + } + + return LT_Other; + } + +private: + bool isClosureImportStatement(const FormatToken &Tok) { + // FIXME: Closure-library specific stuff should not be hard-coded but be + // configurable. + 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 == "setTestOnly" || + Tok.Next->Next->TokenText == "forwardDeclare") && + Tok.Next->Next->Next && Tok.Next->Next->Next->is(tok::l_paren); + } + + void resetTokenMetadata(FormatToken *Token) { + if (!Token) + return; + + // Reset token type in case we have already looked at it and then + // recovered from an error (e.g. failure to find the matching >). + if (!CurrentToken->isOneOf(TT_LambdaLSquare, TT_ForEachMacro, + TT_FunctionLBrace, TT_ImplicitStringLiteral, + TT_InlineASMBrace, TT_JsFatArrow, TT_LambdaArrow, + TT_OverloadedOperator, TT_RegexLiteral, + TT_TemplateString, TT_ObjCStringLiteral)) + CurrentToken->Type = TT_Unknown; + CurrentToken->Role.reset(); + CurrentToken->MatchingParen = nullptr; + CurrentToken->FakeLParens.clear(); + CurrentToken->FakeRParens = 0; + } + + void next() { + if (CurrentToken) { + CurrentToken->NestingLevel = Contexts.size() - 1; + CurrentToken->BindingStrength = Contexts.back().BindingStrength; + modifyContext(*CurrentToken); + determineTokenType(*CurrentToken); + CurrentToken = CurrentToken->Next; + } + + resetTokenMetadata(CurrentToken); + } + + /// \brief A struct to hold information valid in a specific context, e.g. + /// a pair of parenthesis. + 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 InTemplateArgument = false; + bool InCtorInitializer = false; + bool InInheritanceList = false; + bool CaretFound = false; + bool IsForEachMacro = false; + }; + + /// \brief Puts a new \c Context onto the stack \c Contexts for the lifetime + /// of each instance. + 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() { P.Contexts.pop_back(); } + }; + + void modifyContext(const FormatToken &Current) { + if (Current.getPrecedence() == prec::Assignment && + !Line.First->isOneOf(tok::kw_template, tok::kw_using, tok::kw_return) && + // Type aliases use `type X = ...;` in TypeScript and can be exported + // using `export type ...`. + !(Style.Language == FormatStyle::LK_JavaScript && + (Line.startsWith(Keywords.kw_type, tok::identifier) || + Line.startsWith(tok::kw_export, Keywords.kw_type, + tok::identifier))) && + (!Current.Previous || Current.Previous->isNot(tok::kw_operator))) { + 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->Type = 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().InCtorInitializer = true; + } else if (Current.Previous && + Current.Previous->is(TT_InheritanceColon)) { + Contexts.back().InInheritanceList = true; + } 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->Type = TT_PointerOrReference; + if (Line.MustBeDeclaration && !Contexts.front().InCtorInitializer) + Contexts.back().IsExpression = false; + } else if (Current.is(tok::kw_new)) { + Contexts.back().CanBeExpression = false; + } else if (Current.isOneOf(tok::semi, tok::exclaim)) { + // This should be the condition or increment in a for-loop. + Contexts.back().IsExpression = true; + } + } + + void determineTokenType(FormatToken &Current) { + if (!Current.is(TT_Unknown)) + // The token type is already known. + return; + + if (Style.Language == FormatStyle::LK_JavaScript) { + if (Current.is(tok::exclaim)) { + if (Current.Previous && + (Current.Previous->isOneOf(tok::identifier, tok::kw_namespace, + tok::r_paren, tok::r_square, + tok::r_brace) || + Current.Previous->Tok.isLiteral())) { + Current.Type = TT_JsNonNullAssertion; + return; + } + if (Current.Next && + Current.Next->isOneOf(TT_BinaryOperator, Keywords.kw_as)) { + Current.Type = TT_JsNonNullAssertion; + return; + } + } + } + + // Line.MightBeFunctionDecl can only be true after the parentheses of a + // function declaration have been found. In this case, 'Current' is a + // trailing token of this declaration and thus cannot be a name. + if (Current.is(Keywords.kw_instanceof)) { + Current.Type = TT_BinaryOperator; + } else if (isStartOfName(Current) && + (!Line.MightBeFunctionDecl || Current.NestingLevel != 0)) { + Contexts.back().FirstStartOfName = &Current; + Current.Type = TT_StartOfName; + } 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.Type = TT_LambdaArrow; + } else if (Current.is(tok::arrow) && AutoFound && Line.MustBeDeclaration && + Current.NestingLevel == 0) { + Current.Type = TT_TrailingReturnArrow; + } else if (Current.isOneOf(tok::star, tok::amp, tok::ampamp)) { + Current.Type = + determineStarAmpUsage(Current, Contexts.back().CanBeExpression && + Contexts.back().IsExpression, + Contexts.back().InTemplateArgument); + } else if (Current.isOneOf(tok::minus, tok::plus, tok::caret)) { + Current.Type = determinePlusMinusCaretUsage(Current); + if (Current.is(TT_UnaryOperator) && Current.is(tok::caret)) + Contexts.back().CaretFound = true; + } else if (Current.isOneOf(tok::minusminus, tok::plusplus)) { + Current.Type = determineIncrementUsage(Current); + } else if (Current.isOneOf(tok::exclaim, tok::tilde)) { + Current.Type = TT_UnaryOperator; + } else if (Current.is(tok::question)) { + if (Style.Language == FormatStyle::LK_JavaScript && + Line.MustBeDeclaration && !Contexts.back().IsExpression) { + // In JavaScript, `interface X { foo?(): bar; }` is an optional method + // on the interface, not a ternary expression. + Current.Type = TT_JsTypeOptionalQuestion; + } else { + Current.Type = TT_ConditionalExpr; + } + } else if (Current.isBinaryOperator() && + (!Current.Previous || Current.Previous->isNot(tok::l_square))) { + Current.Type = TT_BinaryOperator; + } else if (Current.is(tok::comment)) { + if (Current.TokenText.startswith("/*")) { + if (Current.TokenText.endswith("*/")) + Current.Type = TT_BlockComment; + else + // The lexer has for some reason determined a comment here. But we + // cannot really handle it, if it isn't properly terminated. + Current.Tok.setKind(tok::unknown); + } else { + Current.Type = TT_LineComment; + } + } else if (Current.is(tok::r_paren)) { + if (rParenEndsCast(Current)) + Current.Type = 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) { + // Make sure this isn't the return type of an Obj-C block declaration + if (AfterParen->Tok.isNot(tok::caret)) { + if (FormatToken *BeforeParen = Current.MatchingParen->Previous) + if (BeforeParen->is(tok::identifier) && + BeforeParen->TokenText == BeforeParen->TokenText.upper() && + (!BeforeParen->Previous || + BeforeParen->Previous->ClosesTemplateDeclaration)) + Current.Type = TT_FunctionAnnotationRParen; + } + } + } else if (Current.is(tok::at) && Current.Next && + Style.Language != FormatStyle::LK_JavaScript && + Style.Language != FormatStyle::LK_Java) { + // In Java & JavaScript, "@..." is a decorator or annotation. In ObjC, it + // marks declarations and properties that need special formatting. + switch (Current.Next->Tok.getObjCKeywordID()) { + case tok::objc_interface: + case tok::objc_implementation: + case tok::objc_protocol: + Current.Type = TT_ObjCDecl; + break; + case tok::objc_property: + Current.Type = 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.Type = TT_DesignatedInitializerPeriod; + else if (Style.Language == FormatStyle::LK_Java && Current.Previous && + Current.Previous->isOneOf(TT_JavaAnnotation, + TT_LeadingJavaAnnotation)) { + Current.Type = Current.Previous->Type; + } + } else if (Current.isOneOf(tok::identifier, tok::kw_const) && + Current.Previous && + !Current.Previous->isOneOf(tok::equal, tok::at) && + Line.MightBeFunctionDecl && Contexts.size() == 1) { + // Line.MightBeFunctionDecl can only be true after the parentheses of a + // function declaration have been found. + Current.Type = TT_TrailingAnnotation; + } else if ((Style.Language == FormatStyle::LK_Java || + Style.Language == FormatStyle::LK_JavaScript) && + 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.Type = TT_LeadingJavaAnnotation; + else + Current.Type = TT_JavaAnnotation; + } else if (Current.Previous->is(tok::period) && + Current.Previous->isOneOf(TT_JavaAnnotation, + TT_LeadingJavaAnnotation)) { + Current.Type = Current.Previous->Type; + } + } + } + + /// \brief Take a guess at whether \p Tok starts a name of a function or + /// variable declaration. + /// + /// This is a heuristic based on whether \p Tok is an identifier following + /// something that is likely a type. + 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.Language == FormatStyle::LK_JavaScript && + Tok.Previous->is(Keywords.kw_in)) + return false; + + // Skip "const" as it does not have an influence on whether this is a name. + FormatToken *PreviousNotConst = Tok.getPreviousNonComment(); + while (PreviousNotConst && PreviousNotConst->is(tok::kw_const)) + PreviousNotConst = PreviousNotConst->getPreviousNonComment(); + + if (!PreviousNotConst) + 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->MatchingParen && + PreviousNotConst->MatchingParen->Previous && + PreviousNotConst->MatchingParen->Previous->is(tok::kw_decltype)) + return true; + + return (!IsPPKeyword && + PreviousNotConst->isOneOf(tok::identifier, tok::kw_auto)) || + PreviousNotConst->is(TT_PointerOrReference) || + PreviousNotConst->isSimpleTypeSpecifier(); + } + + /// \brief Determine whether ')' is ending a cast. + bool rParenEndsCast(const FormatToken &Tok) { + // C-style casts are only used in C++ and Java. + if (!Style.isCpp() && Style.Language != FormatStyle::LK_Java) + return false; + + // Empty parens aren't casts and there are no casts at the end of the line. + if (Tok.Previous == Tok.MatchingParen || !Tok.Next || !Tok.MatchingParen) + return false; + + FormatToken *LeftOfParens = Tok.MatchingParen->getPreviousNonComment(); + if (LeftOfParens) { + // If there is a closing parenthesis left of the current parentheses, + // look past it as these might be chained casts. + if (LeftOfParens->is(tok::r_paren)) { + if (!LeftOfParens->MatchingParen || + !LeftOfParens->MatchingParen->Previous) + return false; + LeftOfParens = LeftOfParens->MatchingParen->Previous; + } + + // If there is an identifier (or with a few exceptions a keyword) right + // before the parentheses, this is unlikely to be a cast. + if (LeftOfParens->Tok.getIdentifierInfo() && + !LeftOfParens->isOneOf(Keywords.kw_in, tok::kw_return, tok::kw_case, + tok::kw_delete)) + return false; + + // Certain other tokens right before the parentheses are also signals that + // this cannot be a cast. + if (LeftOfParens->isOneOf(tok::at, tok::r_square, TT_OverloadedOperator, + TT_TemplateCloser, tok::ellipsis)) + return false; + } + + if (Tok.Next->is(tok::question)) + return false; + + // As Java has no function types, a "(" after the ")" likely means that this + // is a cast. + if (Style.Language == FormatStyle::LK_Java && Tok.Next->is(tok::l_paren)) + return true; + + // If a (non-string) literal follows, this is likely a cast. + if (Tok.Next->isNot(tok::string_literal) && + (Tok.Next->Tok.isLiteral() || + Tok.Next->isOneOf(tok::kw_sizeof, tok::kw_alignof))) + return true; + + // Heuristically try to determine whether the parentheses contain a type. + bool ParensAreType = + !Tok.Previous || + Tok.Previous->isOneOf(TT_PointerOrReference, TT_TemplateCloser) || + Tok.Previous->isSimpleTypeSpecifier(); + bool ParensCouldEndDecl = + Tok.Next->isOneOf(tok::equal, tok::semi, tok::l_brace, tok::greater); + if (ParensAreType && !ParensCouldEndDecl) + return true; + + // At this point, we heuristically assume that there are no casts at the + // start of the line. We assume that we have found most cases where there + // are by the logic above, e.g. "(void)x;". + if (!LeftOfParens) + return false; + + // Certain token types inside the parentheses mean that this can't be a + // cast. + for (const FormatToken *Token = Tok.MatchingParen->Next; Token != &Tok; + Token = Token->Next) + if (Token->is(TT_BinaryOperator)) + return false; + + // If the following token is an identifier or 'this', this is a cast. All + // cases where this can be something else are handled above. + if (Tok.Next->isOneOf(tok::identifier, tok::kw_this)) + return true; + + if (!Tok.Next->Next) + return false; + + // If the next token after the parenthesis is a unary operator, assume + // that this is cast, unless there are unexpected tokens inside the + // parenthesis. + 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; + // Search for unexpected tokens. + 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; + } + + /// \brief Return the type of the given token assuming it is * or &. + TokenType determineStarAmpUsage(const FormatToken &Tok, bool IsExpression, + bool InTemplateArgument) { + if (Style.Language == FormatStyle::LK_JavaScript) + return TT_BinaryOperator; + + const FormatToken *PrevToken = Tok.getPreviousNonComment(); + if (!PrevToken) + return TT_UnaryOperator; + + const FormatToken *NextToken = Tok.getNextNonComment(); + if (!NextToken || + NextToken->isOneOf(tok::arrow, tok::equal, tok::kw_const) || + (NextToken->is(tok::l_brace) && !NextToken->getNextNonComment())) + return TT_PointerOrReference; + + if (PrevToken->is(tok::coloncolon)) + return TT_PointerOrReference; + + if (PrevToken->isOneOf(tok::l_paren, tok::l_square, tok::l_brace, + tok::comma, tok::semi, tok::kw_return, tok::colon, + tok::equal, tok::kw_delete, tok::kw_sizeof, + tok::kw_throw) || + PrevToken->isOneOf(TT_BinaryOperator, TT_ConditionalExpr, + TT_UnaryOperator, TT_CastRParen)) + 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_paren) && PrevToken->MatchingParen) { + FormatToken *TokenBeforeMatchingParen = + PrevToken->MatchingParen->getPreviousNonComment(); + if (TokenBeforeMatchingParen && + TokenBeforeMatchingParen->isOneOf(tok::kw_typeof, tok::kw_decltype)) + return TT_PointerOrReference; + } + + if (PrevToken->Tok.isLiteral() || + PrevToken->isOneOf(tok::r_paren, tok::r_square, tok::kw_true, + tok::kw_false, tok::r_brace) || + NextToken->Tok.isLiteral() || + NextToken->isOneOf(tok::kw_true, tok::kw_false) || + NextToken->isUnaryOperator() || + // If we know we're in a template argument, there are no named + // declarations. Thus, having an identifier on the right-hand side + // indicates a binary operator. + (InTemplateArgument && NextToken->Tok.isAnyIdentifier())) + return TT_BinaryOperator; + + // "&&(" is quite unlikely to be two successive unary "&". + if (Tok.is(tok::ampamp) && NextToken && NextToken->is(tok::l_paren)) + return TT_BinaryOperator; + + // This catches some cases where evaluation order is used as control flow: + // aaa && aaa->f(); + const FormatToken *NextNextToken = NextToken->getNextNonComment(); + if (NextNextToken && NextNextToken->is(tok::arrow)) + return TT_BinaryOperator; + + // It is very unlikely that we are going to find a pointer or reference type + // definition on the RHS of an assignment. + if (IsExpression && !Contexts.back().CaretFound) + return TT_BinaryOperator; + + return TT_PointerOrReference; + } + + TokenType determinePlusMinusCaretUsage(const FormatToken &Tok) { + const FormatToken *PrevToken = Tok.getPreviousNonComment(); + if (!PrevToken) + return TT_UnaryOperator; + + if (PrevToken->isOneOf(TT_CastRParen, TT_UnaryOperator) && + !PrevToken->is(tok::exclaim)) + // There aren't any trailing unary operators except for TypeScript's + // non-null operator (!). Thus, this must be squence of leading operators. + return TT_UnaryOperator; + + // Use heuristics to recognize unary operators. + if (PrevToken->isOneOf(tok::equal, tok::l_paren, tok::comma, tok::l_square, + tok::question, tok::colon, tok::kw_return, + tok::kw_case, tok::at, tok::l_brace)) + return TT_UnaryOperator; + + // There can't be two consecutive binary operators. + if (PrevToken->is(TT_BinaryOperator)) + return TT_UnaryOperator; + + // Fall back to marking the token as binary operator. + return TT_BinaryOperator; + } + + /// \brief Determine whether ++/-- are pre- or post-increments/-decrements. + 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 Contexts; + + const FormatStyle &Style; + AnnotatedLine &Line; + FormatToken *CurrentToken; + bool AutoFound; + const AdditionalKeywords &Keywords; + + // Set of "<" tokens that do not open a template parameter list. If parseAngle + // determines that a specific token can't be a template opener, it will make + // same decision irrespective of the decisions for tokens leading up to it. + // Store this information to prevent this from causing exponential runtime. + llvm::SmallPtrSet NonTemplateLess; +}; + +static const int PrecedenceUnaryOperator = prec::PointerToMember + 1; +static const int PrecedenceArrowAndPeriod = prec::PointerToMember + 2; + +/// \brief Parses binary expressions by inserting fake parenthesis based on +/// operator precedence. +class ExpressionParser { +public: + ExpressionParser(const FormatStyle &Style, const AdditionalKeywords &Keywords, + AnnotatedLine &Line) + : Style(Style), Keywords(Keywords), Current(Line.First) {} + + /// \brief Parse expressions with the given operatore precedence. + void parse(int Precedence = 0) { + // Skip 'return' and ObjC selector colons as they are not part of a binary + // expression. + while (Current && (Current->is(tok::kw_return) || + (Current->is(tok::colon) && + Current->isOneOf(TT_ObjCMethodExpr, TT_DictLiteral)))) + next(); + + if (!Current || Precedence > PrecedenceArrowAndPeriod) + return; + + // Conditional expressions need to be parsed separately for proper nesting. + if (Precedence == prec::Conditional) { + parseConditionalExpr(); + return; + } + + // Parse unary operators, which all have a higher precedence than binary + // operators. + if (Precedence == PrecedenceUnaryOperator) { + parseUnaryOperator(); + return; + } + + FormatToken *Start = Current; + FormatToken *LatestOperator = nullptr; + unsigned OperatorIndex = 0; + + while (Current) { + // Consume operators with higher precedence. + parse(Precedence + 1); + + int CurrentPrecedence = getCurrentPrecedence(); + + if (Current && Current->is(TT_SelectorName) && + Precedence == CurrentPrecedence) { + if (LatestOperator) + addFakeParenthesis(Start, prec::Level(Precedence)); + Start = Current; + } + + // At the end of the line or when an operator with higher precedence is + // found, insert fake parenthesis and return. + 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; + } + + // Consume scopes: (), [], <> and {} + if (Current->opensScope()) { + // In fragment of a JavaScript template string can look like '}..${' and + // thus close a scope and open a new one at the same time. + while (Current && (!Current->closesScope() || Current->opensScope())) { + next(); + parse(); + } + next(); + } else { + // Operator found. + if (CurrentPrecedence == Precedence) { + if (LatestOperator) + LatestOperator->NextOperator = Current; + LatestOperator = Current; + Current->OperatorIndex = OperatorIndex; + ++OperatorIndex; + } + next(/*SkipPastLeadingComments=*/Precedence > 0); + } + } + + if (LatestOperator && (Current || Precedence > 0)) { + // LatestOperator->LastOperator = true; + if (Precedence == PrecedenceArrowAndPeriod) { + // Call expressions don't have a binary operator precedence. + addFakeParenthesis(Start, prec::Unknown); + } else { + addFakeParenthesis(Start, prec::Level(Precedence)); + } + } + } + +private: + /// \brief Gets the precedence (+1) of the given token for binary operators + /// and other tokens that we treat like binary operators. + 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_JsFatArrow)) + 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.Language == FormatStyle::LK_JavaScript) && + Current->is(Keywords.kw_instanceof)) + return prec::Relational; + if (Style.Language == FormatStyle::LK_JavaScript && + 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.Language == FormatStyle::LK_JavaScript) && + Current->isOneOf(Keywords.kw_extends, Keywords.kw_implements, + Keywords.kw_throws)) + return 0; + } + return -1; + } + + void addFakeParenthesis(FormatToken *Start, prec::Level Precedence) { + Start->FakeLParens.push_back(Precedence); + if (Precedence > prec::Unknown) + Start->StartsBinaryExpression = true; + if (Current) { + FormatToken *Previous = Current->Previous; + while (Previous->is(tok::comment) && Previous->Previous) + Previous = Previous->Previous; + ++Previous->FakeRParens; + if (Precedence > prec::Unknown) + Previous->EndsBinaryExpression = true; + } + } + + /// \brief Parse unary operator expressions and surround them with fake + /// parentheses if appropriate. + void parseUnaryOperator() { + if (!Current || Current->isNot(TT_UnaryOperator)) { + parse(PrecedenceArrowAndPeriod); + return; + } + + FormatToken *Start = Current; + next(); + parseUnaryOperator(); + + // The actual precedence doesn't matter. + addFakeParenthesis(Start, 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; + FormatToken *Current; +}; + +} // end anonymous namespace + +void TokenAnnotator::setCommentLineLevels( + SmallVectorImpl &Lines) { + const AnnotatedLine *NextNonCommentLine = nullptr; + for (SmallVectorImpl::reverse_iterator I = Lines.rbegin(), + E = Lines.rend(); + I != E; ++I) { + bool CommentLine = true; + for (const FormatToken *Tok = (*I)->First; Tok; Tok = Tok->Next) { + if (!Tok->is(tok::comment)) { + CommentLine = false; + break; + } + } + + if (NextNonCommentLine && CommentLine) { + // If the comment is currently aligned with the line immediately following + // it, that's probably intentional and we should keep it. + bool AlignedWithNextLine = + NextNonCommentLine->First->NewlinesBefore <= 1 && + NextNonCommentLine->First->OriginalColumn == + (*I)->First->OriginalColumn; + if (AlignedWithNextLine) + (*I)->Level = NextNonCommentLine->Level; + } else { + NextNonCommentLine = (*I)->First->isNot(tok::r_brace) ? (*I) : nullptr; + } + + setCommentLineLevels((*I)->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) { + for (SmallVectorImpl::iterator I = Line.Children.begin(), + E = Line.Children.end(); + I != E; ++I) { + annotate(**I); + } + AnnotatingParser Parser(Style, Line, Keywords); + Line.Type = Parser.parseLine(); + + // With very deep nesting, ExpressionParser uses lots of stack and the + // formatting algorithm is very slow. We're not going to do a good job here + // anyway - it's probably generated code being formatted by mistake. + // Just skip the whole line. + 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; +} + +// This function heuristically determines whether 'Current' starts the name of a +// function declaration. +static bool isFunctionDeclarationName(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)) { + // For 'new[]' and 'delete[]'. + if (Next->Next && Next->Next->is(tok::l_square) && + Next->Next->Next && Next->Next->Next->is(tok::r_square)) + Next = Next->Next->Next; + continue; + } + + break; + } + return nullptr; + }; + + // Find parentheses of parameter list. + 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; + } + } + } + + // Check whether parameter list can belong to a function declaration. + if (!Next || !Next->is(tok::l_paren) || !Next->MatchingParen) + return false; + // If the lines ends with "{", this is likely an function definition. + if (Line.Last->is(tok::l_brace)) + return true; + if (Next->Next == Next->MatchingParen) + return true; // Empty parentheses. + // If there is an &/&& after the r_paren, this is likely a function. + if (Next->MatchingParen->Next && + Next->MatchingParen->Next->is(TT_PointerOrReference)) + return true; + for (const FormatToken *Tok = Next->Next; Tok && Tok != Next->MatchingParen; + Tok = Tok->Next) { + if (Tok->is(tok::l_paren) && 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) { + for (SmallVectorImpl::iterator I = Line.Children.begin(), + E = Line.Children.end(); + I != E; ++I) { + calculateFormattingInformation(**I); + } + + Line.First->TotalLength = + Line.First->IsMultiline ? Style.ColumnLimit : Line.First->ColumnWidth; + FormatToken *Current = Line.First->Next; + bool InFunctionDecl = Line.MightBeFunctionDecl; + while (Current) { + if (isFunctionDeclarationName(*Current, Line)) + Current->Type = TT_FunctionDeclarationName; + if (Current->is(TT_LineComment)) { + if (Current->Previous->BlockKind == BK_BracedInit && + Current->Previous->opensScope()) + Current->SpacesRequiredBefore = Style.Cpp11BracedListStyle ? 0 : 1; + else + Current->SpacesRequiredBefore = Style.SpacesBeforeTrailingComments; + + // If we find a trailing comment, iterate backwards to determine whether + // it seems to relate to a specific parameter. If so, break before that + // parameter to avoid changing the comment's meaning. E.g. don't move 'b' + // to the previous line in: + // SomeFunction(a, + // b, // comment + // c); + 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; + } + + 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 (Current->Previous->Children.size() == 1) { + FormatToken &LastOfChild = *Current->Previous->Children[0]->Last; + ChildSize = LastOfChild.isTrailingComment() ? Style.ColumnLimit + : LastOfChild.TotalLength + 1; + } + const FormatToken *Prev = Current->Previous; + 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; + + // FIXME: Only calculate this if CanBreakBefore is true once static + // initializers etc. are sorted out. + // FIXME: Move magic numbers to a better place. + Current->SplitPenalty = 20 * Current->BindingStrength + + splitPenalty(Line, *Current, InFunctionDecl); + + 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)) { + assert(IndentLevel > 0); + --IndentLevel; + } + Current->IndentLevel = IndentLevel; + if (Current->opensBlockOrBlockTypeList(Style)) + ++IndentLevel; + } + + DEBUG({ printDebugInfo(Line); }); +} + +void TokenAnnotator::calculateUnbreakableTailLengths(AnnotatedLine &Line) { + 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; + } +} + +unsigned TokenAnnotator::splitPenalty(const AnnotatedLine &Line, + const FormatToken &Tok, + bool InFunctionDecl) { + 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.Language == FormatStyle::LK_JavaScript) { + 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; + // Prefer breaking call chains (".foo") over empty "{}", "[]" or "()". + 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; + // Slightly prefer formatting local lambda definitions like functions. + if (Right.is(TT_LambdaLSquare) && Left.is(tok::equal)) + return 35; + if (!Right.isOneOf(TT_ObjCMethodExpr, TT_LambdaLSquare, + TT_ArrayInitializerLSquare, + TT_DesignatedInitializerLSquare)) + 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.is(tok::coloncolon) || + (Right.is(tok::period) && Style.Language == FormatStyle::LK_Proto)) + return 500; + 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()) { + // Breaking before the "./->" of a chained call/member access is reasonably + // cheap, as formatting those with one call per line is generally + // desirable. In particular, it should be cheaper to break before the call + // than it is to break inside a call's parameters, which could lead to weird + // "hanging" indents. The exception is the very last "./->" to support this + // frequent pattern: + // + // aaaaaaaa.aaaaaaaa.bbbbbbb().ccccccccccccccccccccc( + // dddddddd); + // + // which might otherwise be blown up onto many lines. Here, clang-format + // won't produce "hanging" indents anyway as there is no other trailing + // call. + // + // Also apply higher penalty is not a call as that might lead to a wrapping + // like: + // + // aaaaaaa + // .aaaaaaaaa.bbbbbbbb(cccccccc); + return !Right.NextOperator || !Right.NextOperator->Previous->closesScope() + ? 150 + : 35; + } + + if (Right.is(TT_TrailingAnnotation) && + (!Right.Next || Right.Next->isNot(tok::l_paren))) { + // Moving trailing annotations to the next line is fine for ObjC method + // declarations. + if (Line.startsWith(TT_ObjCMethodSpecifier)) + return 10; + // Generally, breaking before a trailing annotation is bad unless it is + // function-like. It seems to be especially preferable to keep standard + // annotations (i.e. "const", "final" and "override") on the same line. + // Use a slightly higher penalty after ")" so that annotations like + // "const override" are kept together. + bool is_short_annotation = Right.TokenText.size() < 10; + return (Left.is(tok::r_paren) ? 100 : 120) + (is_short_annotation ? 50 : 0); + } + + // In for-loops, prefer breaking at ',' and ';'. + if (Line.startsWith(tok::kw_for) && Left.is(tok::equal)) + return 4; + + // In Objective-C method expressions, prefer breaking before "param:" over + // breaking after it. + if (Right.is(TT_SelectorName)) + return 0; + if (Left.is(tok::colon) && Left.is(TT_ObjCMethodExpr)) + return Line.MightBeFunctionDecl ? 50 : 500; + + if (Left.is(tok::l_paren) && InFunctionDecl && + Style.AlignAfterOpenBracket != FormatStyle::BAS_DontAlign) + return 100; + if (Left.is(tok::l_paren) && Left.Previous && + (Left.Previous->isOneOf(tok::kw_if, tok::kw_for) + || Left.Previous->endsSequence(tok::kw_constexpr, tok::kw_if))) + 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) + return 0; + return Left.ParameterCount > 1 ? Style.PenaltyBreakBeforeFirstCallParameter + : 19; + } + if (Left.is(TT_JavaAnnotation)) + return 50; + + if (Left.isOneOf(tok::plus, tok::comma) && Left.Previous && + Left.Previous->isLabelString() && + (Left.NextOperator || Left.OperatorIndex != 0)) + return 45; + 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)) { + // Breaking at a << is really cheap. + if (!Left.is(tok::r_paren) || Right.OperatorIndex > 0) + // Slightly prefer to break before the first one in log-like statements. + return 2; + return 1; + } + if (Left.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::spaceRequiredBetween(const AnnotatedLine &Line, + const FormatToken &Left, + const FormatToken &Right) { + if (Left.is(tok::kw_return) && Right.isNot(tok::semi)) + 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)) + return Style.SpaceInEmptyParentheses; + 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 && Style.ObjCSpaceBeforeProtocolList) + return true; + 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)) + 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 false; + 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 || + !TokenBeforeMatchingParen->isOneOf(tok::kw_typeof, tok::kw_decltype)) + return true; + } + return (Left.Tok.isLiteral() || + (!Left.isOneOf(TT_PointerOrReference, tok::l_paren) && + (Style.PointerAlignment != FormatStyle::PAS_Left || + (Line.IsMultiVariableDeclStmt && + (Left.NestingLevel == 0 || + (Left.NestingLevel == 1 && Line.First->is(tok::kw_for))))))); + } + if (Right.is(TT_FunctionTypeLParen) && Left.isNot(tok::l_paren) && + (!Left.is(TT_PointerOrReference) || + (Style.PointerAlignment != FormatStyle::PAS_Right && + !Line.IsMultiVariableDeclStmt))) + return true; + if (Left.is(TT_PointerOrReference)) + return Right.Tok.isLiteral() || Right.is(TT_BlockComment) || + (Right.isOneOf(Keywords.kw_override, Keywords.kw_final) && + !Right.is(TT_StartOfName)) || + (Right.is(tok::l_brace) && Right.BlockKind == BK_Block) || + (!Right.isOneOf(TT_PointerOrReference, TT_ArraySubscriptLSquare, + tok::l_paren) && + (Style.PointerAlignment != FormatStyle::PAS_Right && + !Line.IsMultiVariableDeclStmt) && + Left.Previous && + !Left.Previous->isOneOf(tok::l_paren, tok::coloncolon)); + if (Right.is(tok::star) && Left.is(tok::l_paren)) + return false; + if (Left.is(tok::l_square)) + return (Left.is(TT_ArrayInitializerLSquare) && + Style.SpacesInContainerLiterals && Right.isNot(tok::r_square)) || + (Left.isOneOf(TT_ArraySubscriptLSquare, + TT_StructuredBindingLSquare) && + Style.SpacesInSquareBrackets && Right.isNot(tok::r_square)); + if (Right.is(tok::r_square)) + return Right.MatchingParen && + ((Style.SpacesInContainerLiterals && + Right.MatchingParen->is(TT_ArrayInitializerLSquare)) || + (Style.SpacesInSquareBrackets && + Right.MatchingParen->isOneOf(TT_ArraySubscriptLSquare, + TT_StructuredBindingLSquare))); + if (Right.is(tok::l_square) && + !Right.isOneOf(TT_ObjCMethodExpr, TT_LambdaLSquare, + TT_DesignatedInitializerLSquare, + TT_StructuredBindingLSquare) && + !Left.isOneOf(tok::numeric_constant, TT_DictLiteral)) + return false; + if (Left.is(tok::l_brace) && Right.is(tok::r_brace)) + return !Left.Children.empty(); // No spaces in "{}". + if ((Left.is(tok::l_brace) && Left.BlockKind != BK_Block) || + (Right.is(tok::r_brace) && Right.MatchingParen && + Right.MatchingParen->BlockKind != BK_Block)) + return !Style.Cpp11BracedListStyle; + if (Left.is(TT_BlockComment)) + return !Left.TokenText.endswith("=*/"); + if (Right.is(tok::l_paren)) { + if (Left.is(tok::r_paren) && Left.is(TT_AttributeParen)) + return true; + return Line.Type == LT_ObjCDecl || Left.is(tok::semi) || + (Style.SpaceBeforeParens != FormatStyle::SBPO_Never && + (Left.isOneOf(tok::kw_if, tok::pp_elif, tok::kw_for, tok::kw_while, + tok::kw_switch, tok::kw_case, TT_ForEachMacro, + TT_ObjCForIn) || + Left.endsSequence(tok::kw_constexpr, tok::kw_if) || + (Left.isOneOf(tok::kw_try, Keywords.kw___except, tok::kw_catch, + tok::kw_new, tok::kw_delete) && + (!Left.Previous || Left.Previous->isNot(tok::period))))) || + (Style.SpaceBeforeParens == FormatStyle::SBPO_Always && + (Left.is(tok::identifier) || Left.isFunctionLikeKeyword() || + Left.is(tok::r_paren)) && + Line.Type != LT_PreprocessorDirective); + } + 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.BlockKind != 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") + return false; + if (Left.is(TT_TemplateCloser) && Left.MatchingParen && + Left.MatchingParen->Previous && + Left.MatchingParen->Previous->is(tok::period)) + // A.DoSomething(); + return false; + if (Left.is(TT_TemplateCloser) && Right.is(tok::l_square)) + return false; + return true; +} + +bool TokenAnnotator::spaceRequiredBefore(const AnnotatedLine &Line, + const FormatToken &Right) { + const FormatToken &Left = *Right.Previous; + if (Right.Tok.getIdentifierInfo() && Left.Tok.getIdentifierInfo()) + return true; // Never ever merge two identifiers. + if (Style.isCpp()) { + if (Left.is(tok::kw_operator)) + return Right.is(tok::coloncolon); + } 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; + } else if (Style.Language == FormatStyle::LK_JavaScript) { + if (Left.is(TT_JsFatArrow)) + return true; + // for await ( ... + 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(); + // An async arrow function, for example: `x = async () => foo();`, + // as opposed to calling a function called async: `x = async();` + if (Next && Next->is(TT_JsFatArrow)) + return true; + } + if ((Left.is(TT_TemplateString) && Left.TokenText.endswith("${")) || + (Right.is(TT_TemplateString) && Right.TokenText.startswith("}"))) + return false; + // In tagged template literals ("html`bar baz`"), there is no space between + // the tag identifier and the template string. getIdentifierInfo makes sure + // that the identifier is not a pseudo keyword like `yield`, either. + if (Left.is(tok::identifier) && Keywords.IsJavaScriptIdentifier(Left) && + 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)) { + // JS methods can use some keywords as names (e.g. `delete()`). + if (Line.MustBeDeclaration && Left.Tok.getIdentifierInfo()) + return false; + // Valid JS method names can include keywords, e.g. `foo.delete()` or + // `bar.instanceof()`. Recognize call positions by preceding period. + if (Left.Previous && Left.Previous->is(tok::period) && + Left.Tok.getIdentifierInfo()) + return false; + // Additional unary JavaScript operators that need a space after. + if (Left.isOneOf(tok::kw_throw, Keywords.kw_await, Keywords.kw_typeof, + tok::kw_void)) + return true; + } + if ((Left.isOneOf(Keywords.kw_let, Keywords.kw_var, Keywords.kw_in, + tok::kw_const) || + // "of" is only a keyword if it appears after another identifier + // (e.g. as "const x of y" in a for loop). + (Left.is(Keywords.kw_of) && Left.Previous && + Left.Previous->Tok.getIdentifierInfo())) && + (!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)) + // Type assertions ('expr') are not followed by whitespace. Other + // locations that should have whitespace following are identified by the + // above set of follower tokens. + return false; + if (Right.is(TT_JsNonNullAssertion)) + return false; + if (Left.is(TT_JsNonNullAssertion) && Right.is(Keywords.kw_as)) + return true; // "x! as string" + } 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.SpaceBeforeParens != FormatStyle::SBPO_Never; + 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; + } + if (Left.is(TT_ImplicitStringLiteral)) + return Right.WhitespaceRange.getBegin() != Right.WhitespaceRange.getEnd(); + if (Line.Type == LT_ObjCMethodDecl) { + if (Left.is(TT_ObjCMethodSpecifier)) + return true; + if (Left.is(tok::r_paren) && Right.is(tok::identifier)) + // Don't space between ')' and + 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 (Right.is(TT_OverloadedOperatorLParen)) + return Style.SpaceBeforeParens == FormatStyle::SBPO_Always; + if (Left.is(tok::comma)) + return true; + if (Right.is(tok::comma)) + return false; + if (Right.isOneOf(TT_CtorInitializerColon, TT_ObjCBlockLParen)) + return true; + if (Right.is(tok::colon)) { + if (Line.First->isOneOf(tok::kw_case, tok::kw_default) || + !Right.getNextNonComment() || Right.getNextNonComment()->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; + return true; + } + if (Left.is(TT_UnaryOperator)) + return Right.is(TT_BinaryOperator); + + // If the next token is a binary operator or a selector name, we have + // incorrectly classified the parenthesis as a cast. FIXME: Detect correctly. + if (Left.is(TT_CastRParen)) + return Style.SpaceAfterCStyleCast || + Right.isOneOf(TT_BinaryOperator, TT_SelectorName); + + if (Left.is(tok::greater) && Right.is(tok::greater)) + return Right.is(TT_TemplateCloser) && Left.is(TT_TemplateCloser) && + (Style.Standard != FormatStyle::LS_Cpp11 || Style.SpacesInAngles); + 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 && + Right.getPrecedence() == prec::Assignment) + return false; + if (Right.is(tok::coloncolon) && Left.is(tok::identifier)) + // Generally don't remove existing spaces between an identifier and "::". + // The identifier might actually be a macro name such as ALWAYS_INLINE. If + // this turns out to be too lenient, add analysis of the identifier itself. + return Right.WhitespaceRange.getBegin() != Right.WhitespaceRange.getEnd(); + if (Right.is(tok::coloncolon) && !Left.isOneOf(tok::l_brace, tok::comment)) + return (Left.is(TT_TemplateOpener) && + Style.Standard == FormatStyle::LS_Cpp03) || + !(Left.isOneOf(tok::l_paren, tok::r_paren, tok::l_square, + tok::kw___super, TT_TemplateCloser, TT_TemplateOpener)); + if ((Left.is(TT_TemplateOpener)) != (Right.is(TT_TemplateCloser))) + return Style.SpacesInAngles; + if ((Right.is(TT_BinaryOperator) && !Left.is(tok::l_paren)) || + (Left.isOneOf(TT_BinaryOperator, TT_ConditionalExpr) && + !Right.is(tok::r_paren))) + return true; + if (Left.is(TT_TemplateCloser) && Right.is(tok::l_paren) && + Right.isNot(TT_FunctionTypeLParen)) + return Style.SpaceBeforeParens == FormatStyle::SBPO_Always; + 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); +} + +// Returns 'true' if 'Tok' is a brace we'd want to break before in Allman style. +static bool isAllmanBrace(const FormatToken &Tok) { + return Tok.is(tok::l_brace) && Tok.BlockKind == BK_Block && + !Tok.isOneOf(TT_ObjCBlockLBrace, TT_DictLiteral); +} + +bool TokenAnnotator::mustBreakBefore(const AnnotatedLine &Line, + const FormatToken &Right) { + const FormatToken &Left = *Right.Previous; + if (Right.NewlinesBefore > 1 && Style.MaxEmptyLinesToKeep > 0) + return true; + + if (Style.Language == FormatStyle::LK_JavaScript) { + // FIXME: This might apply to other languages and token kinds. + if (Right.is(tok::string_literal) && Left.is(tok::plus) && Left.Previous && + Left.Previous->is(tok::string_literal)) + return true; + if (Left.is(TT_DictLiteral) && Left.is(tok::l_brace) && Line.Level == 0 && + Left.Previous && Left.Previous->is(tok::equal) && + Line.First->isOneOf(tok::identifier, Keywords.kw_import, tok::kw_export, + tok::kw_const) && + // kw_var/kw_let are pseudo-tokens that are tok::identifier, so match + // above. + !Line.First->isOneOf(Keywords.kw_var, Keywords.kw_let)) + // Object literals on the top level of a file are treated as "enum-style". + // Each key/value pair is put on a separate line, instead of bin-packing. + return true; + if (Left.is(tok::l_brace) && Line.Level == 0 && + (Line.startsWith(tok::kw_enum) || + Line.startsWith(tok::kw_const, tok::kw_enum) || + Line.startsWith(tok::kw_export, tok::kw_enum) || + Line.startsWith(tok::kw_export, tok::kw_const, tok::kw_enum))) + // JavaScript top-level enum key/value pairs are put on separate lines + // instead of bin-packing. + return true; + if (Right.is(tok::r_brace) && Left.is(tok::l_brace) && + !Left.Children.empty()) + // Support AllowShortFunctionsOnASingleLine for JavaScript. + return Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_None || + Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_Empty || + (Left.NestingLevel == 0 && Line.Level == 0 && + Style.AllowShortFunctionsOnASingleLine & + FormatStyle::SFS_InlineOnly); + } else if (Style.Language == FormatStyle::LK_Java) { + if (Right.is(tok::plus) && Left.is(tok::string_literal) && Right.Next && + Right.Next->is(tok::string_literal)) + return true; + } else if (Style.Language == FormatStyle::LK_Cpp || + Style.Language == FormatStyle::LK_ObjC || + Style.Language == FormatStyle::LK_Proto) { + if (Left.isStringLiteral() && Right.isStringLiteral()) + return true; + } + + // If the last token before a '}', ']', or ')' is a comma or a trailing + // comment, the intention is to insert a line break after it in order to make + // shuffling around entries easier. Import statements, especially in + // JavaScript, can be an exception to this rule. + if (Style.JavaScriptWrapImports || Line.Type != LT_ImportStatement) { + const FormatToken *BeforeClosingBrace = nullptr; + if ((Left.isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) || + (Style.Language == FormatStyle::LK_JavaScript && + Left.is(tok::l_paren))) && + Left.BlockKind != BK_Block && Left.MatchingParen) + BeforeClosingBrace = Left.MatchingParen->Previous; + else if (Right.MatchingParen && + (Right.MatchingParen->isOneOf(tok::l_brace, + TT_ArrayInitializerLSquare) || + (Style.Language == FormatStyle::LK_JavaScript && + 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.BlockKind != BK_BracedInit && + Left.isNot(TT_CtorInitializerColon) && + (Right.NewlinesBefore > 0 && Right.HasUnescapedNewline); + if (Left.isTrailingComment()) + return true; + if (Right.Previous->IsUnterminatedLiteral) + return true; + if (Right.is(tok::lessless) && Right.Next && + Right.Previous->is(tok::string_literal) && + Right.Next->is(tok::string_literal)) + return true; + if (Right.Previous->ClosesTemplateDeclaration && + Right.Previous->MatchingParen && + Right.Previous->MatchingParen->NestingLevel == 0 && + Style.AlwaysBreakTemplateDeclarations) + return true; + if (Right.is(TT_CtorInitializerComma) && + Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma && + !Style.ConstructorInitializerAllOnOneLineOrOnePerLine) + return true; + if (Right.is(TT_CtorInitializerColon) && + Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeComma && + !Style.ConstructorInitializerAllOnOneLineOrOnePerLine) + return true; + // Break only if we have multiple inheritance. + if (Style.BreakBeforeInheritanceComma && + Right.is(TT_InheritanceComma)) + return true; + if (Right.is(tok::string_literal) && Right.TokenText.startswith("R\"")) + // Raw string literals are special wrt. line breaks. The author has made a + // deliberate choice and might have aligned the contents of the string + // literal accordingly. Thus, we try keep existing line breaks. + return Right.NewlinesBefore > 0; + if ((Right.Previous->is(tok::l_brace) || + (Right.Previous->is(tok::less) && + Right.Previous->Previous && + Right.Previous->Previous->is(tok::equal)) + ) && + Right.NestingLevel == 1 && Style.Language == FormatStyle::LK_Proto) { + // Don't put enums or option definitions onto single lines in protocol + // buffers. + return true; + } + if (Right.is(TT_InlineASMBrace)) + return Right.HasUnescapedNewline; + if (isAllmanBrace(Left) || isAllmanBrace(Right)) + return (Line.startsWith(tok::kw_enum) && Style.BraceWrapping.AfterEnum) || + (Line.startsWith(tok::kw_class) && Style.BraceWrapping.AfterClass) || + (Line.startsWith(tok::kw_struct) && Style.BraceWrapping.AfterStruct); + if (Left.is(TT_ObjCBlockLBrace) && !Style.AllowShortBlocksOnASingleLine) + return true; + + if ((Style.Language == FormatStyle::LK_Java || + Style.Language == FormatStyle::LK_JavaScript) && + Left.is(TT_LeadingJavaAnnotation) && + Right.isNot(TT_LeadingJavaAnnotation) && Right.isNot(tok::l_paren) && + (Line.Last->is(tok::l_brace) || Style.BreakAfterJavaFieldAnnotations)) + return true; + + return false; +} + +bool TokenAnnotator::canBreakBefore(const AnnotatedLine &Line, + const FormatToken &Right) { + const FormatToken &Left = *Right.Previous; + + // Language-specific stuff. + 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.Language == FormatStyle::LK_JavaScript) { + const FormatToken *NonComment = Right.getPreviousNonComment(); + if (NonComment && + NonComment->isOneOf(tok::kw_return, 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_abstract, + Keywords.kw_get, Keywords.kw_set)) + return false; // Otherwise automatic semicolon insertion would trigger. + if (Left.is(TT_JsFatArrow) && Right.is(tok::l_brace)) + return false; + if (Left.is(TT_JsTypeColon)) + return true; + if (Right.NestingLevel == 0 && Right.is(Keywords.kw_is)) + 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; // must not break before as in 'x as type' casts + if (Left.is(Keywords.kw_as)) + return true; + if (Left.is(TT_JsNonNullAssertion)) + 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)) + // See grammar for 'declare' statements at: + // https://github.com/Microsoft/TypeScript/blob/master/doc/spec.md#A.10 + return false; + if (Left.isOneOf(Keywords.kw_module, tok::kw_namespace) && + Right.isOneOf(tok::identifier, tok::string_literal)) + return false; // must not break in "module foo { ...}" + if (Right.is(TT_TemplateString) && Right.closesScope()) + 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 || + (Style.PointerAlignment == 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()) + // We rely on MustBreakBefore being set correctly here as we should not + // change the "binding" behavior of a comment. + // The first comment in a braced lists is always interpreted as belonging to + // the first list element. Otherwise, it should be placed outside of the + // list. + return Left.BlockKind == BK_BracedInit || + (Left.is(TT_CtorInitializerColon) && + Style.BreakConstructorInitializers == + FormatStyle::BCIS_AfterColon); + if (Left.is(tok::question) && Right.is(tok::colon)) + return false; + if (Right.is(TT_ConditionalExpr) || Right.is(tok::question)) + return Style.BreakBeforeTernaryOperators; + if (Left.is(TT_ConditionalExpr) || Left.is(tok::question)) + return !Style.BreakBeforeTernaryOperators; + if (Right.is(TT_InheritanceColon)) + return true; + 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)) + return true; + if (Right.is(TT_SelectorName) || (Right.is(tok::identifier) && Right.Next && + Right.Next->is(TT_ObjCMethodExpr))) + return Left.isNot(tok::period); // FIXME: Properly parse ObjC calls. + if (Left.is(tok::r_paren) && Line.Type == LT_ObjCProperty) + return true; + if (Left.ClosesTemplateDeclaration || Left.is(TT_FunctionAnnotationRParen)) + 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.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::l_paren) && Left.is(TT_AttributeParen)) + 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(tok::r_paren) || Right.is(TT_TemplateCloser)) + return false; + if (Right.is(tok::r_square) && Right.MatchingParen && + Right.MatchingParen->is(TT_LambdaLSquare)) + return false; + + // We only break before r_brace if there was a corresponding break before + // the l_brace, which is tracked by BreakBeforeClosingBrace. + if (Right.is(tok::r_brace)) + return Right.MatchingParen && Right.MatchingParen->BlockKind == BK_Block; + + // Allow breaking after a trailing annotation, e.g. after a method + // declaration. + 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)) + return true; + + 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; + 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.BreakBeforeInheritanceComma) + return false; + if (Right.is(TT_InheritanceComma) && Style.BreakBeforeInheritanceComma) + 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.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; + 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) { + 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->Type) + << " S=" << Tok->SpacesRequiredBefore + << " B=" << Tok->BlockParameterCount + << " BK=" << Tok->BlockKind + << " P=" << Tok->SplitPenalty << " Name=" << Tok->Tok.getName() + << " L=" << Tok->TotalLength << " PPK=" << Tok->PackingKind + << " FakeLParens="; + for (unsigned i = 0, e = Tok->FakeLParens.size(); i != e; ++i) + llvm::errs() << Tok->FakeLParens[i] << "/"; + llvm::errs() << " FakeRParens=" << Tok->FakeRParens; + llvm::errs() << " Text='" << Tok->TokenText << "'\n"; + if (!Tok->Next) + assert(Tok == Line.Last); + Tok = Tok->Next; + } + llvm::errs() << "----\n"; +} + +} // namespace format +} // namespace clang Index: unittests/Format/FormatTest.cpp =================================================================== --- unittests/Format/FormatTest.cpp +++ unittests/Format/FormatTest.cpp @@ -1,11222 +1,11247 @@ -//===- unittest/Format/FormatTest.cpp - Formatting unit tests -------------===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// - -#include "clang/Format/Format.h" - -#include "../Tooling/ReplacementTest.h" -#include "FormatTestUtils.h" - -#include "clang/Frontend/TextDiagnosticPrinter.h" -#include "llvm/Support/Debug.h" -#include "llvm/Support/MemoryBuffer.h" -#include "gtest/gtest.h" - -#define DEBUG_TYPE "format-test" - -using clang::tooling::ReplacementTest; -using clang::tooling::toReplacements; - -namespace clang { -namespace format { -namespace { - -FormatStyle getGoogleStyle() { return getGoogleStyle(FormatStyle::LK_Cpp); } - -class FormatTest : public ::testing::Test { -protected: - enum StatusCheck { - SC_ExpectComplete, - SC_ExpectIncomplete, - SC_DoNotCheck - }; - - std::string format(llvm::StringRef Code, - const FormatStyle &Style = getLLVMStyle(), - StatusCheck CheckComplete = SC_ExpectComplete) { - DEBUG(llvm::errs() << "---\n"); - DEBUG(llvm::errs() << Code << "\n\n"); - std::vector Ranges(1, tooling::Range(0, Code.size())); - FormattingAttemptStatus Status; - tooling::Replacements Replaces = - reformat(Style, Code, Ranges, "", &Status); - if (CheckComplete != SC_DoNotCheck) { - bool ExpectedCompleteFormat = CheckComplete == SC_ExpectComplete; - EXPECT_EQ(ExpectedCompleteFormat, Status.FormatComplete) - << Code << "\n\n"; - } - ReplacementCount = Replaces.size(); - auto Result = applyAllReplacements(Code, Replaces); - EXPECT_TRUE(static_cast(Result)); - DEBUG(llvm::errs() << "\n" << *Result << "\n\n"); - return *Result; - } - - FormatStyle getStyleWithColumns(FormatStyle Style, unsigned ColumnLimit) { - Style.ColumnLimit = ColumnLimit; - return Style; - } - - FormatStyle getLLVMStyleWithColumns(unsigned ColumnLimit) { - return getStyleWithColumns(getLLVMStyle(), ColumnLimit); - } - - FormatStyle getGoogleStyleWithColumns(unsigned ColumnLimit) { - return getStyleWithColumns(getGoogleStyle(), ColumnLimit); - } - - void verifyFormat(llvm::StringRef Code, - const FormatStyle &Style = getLLVMStyle()) { - EXPECT_EQ(Code.str(), format(test::messUp(Code), Style)); - if (Style.Language == FormatStyle::LK_Cpp) { - // Objective-C++ is a superset of C++, so everything checked for C++ - // needs to be checked for Objective-C++ as well. - FormatStyle ObjCStyle = Style; - ObjCStyle.Language = FormatStyle::LK_ObjC; - EXPECT_EQ(Code.str(), format(test::messUp(Code), ObjCStyle)); - } - } - - void verifyIncompleteFormat(llvm::StringRef Code, - const FormatStyle &Style = getLLVMStyle()) { - EXPECT_EQ(Code.str(), - format(test::messUp(Code), Style, SC_ExpectIncomplete)); - } - - void verifyGoogleFormat(llvm::StringRef Code) { - verifyFormat(Code, getGoogleStyle()); - } - - void verifyIndependentOfContext(llvm::StringRef text) { - verifyFormat(text); - verifyFormat(llvm::Twine("void f() { " + text + " }").str()); - } - - /// \brief Verify that clang-format does not crash on the given input. - void verifyNoCrash(llvm::StringRef Code, - const FormatStyle &Style = getLLVMStyle()) { - format(Code, Style, SC_DoNotCheck); - } - - int ReplacementCount; -}; - -TEST_F(FormatTest, MessUp) { - EXPECT_EQ("1 2 3", test::messUp("1 2 3")); - EXPECT_EQ("1 2 3\n", test::messUp("1\n2\n3\n")); - EXPECT_EQ("a\n//b\nc", test::messUp("a\n//b\nc")); - EXPECT_EQ("a\n#b\nc", test::messUp("a\n#b\nc")); - EXPECT_EQ("a\n#b c d\ne", test::messUp("a\n#b\\\nc\\\nd\ne")); -} - -//===----------------------------------------------------------------------===// -// Basic function tests. -//===----------------------------------------------------------------------===// - -TEST_F(FormatTest, DoesNotChangeCorrectlyFormattedCode) { - EXPECT_EQ(";", format(";")); -} - -TEST_F(FormatTest, FormatsGlobalStatementsAt0) { - EXPECT_EQ("int i;", format(" int i;")); - EXPECT_EQ("\nint i;", format(" \n\t \v \f int i;")); - EXPECT_EQ("int i;\nint j;", format(" int i; int j;")); - EXPECT_EQ("int i;\nint j;", format(" int i;\n int j;")); -} - -TEST_F(FormatTest, FormatsUnwrappedLinesAtFirstFormat) { - EXPECT_EQ("int i;", format("int\ni;")); -} - -TEST_F(FormatTest, FormatsNestedBlockStatements) { - EXPECT_EQ("{\n {\n {}\n }\n}", format("{{{}}}")); -} - -TEST_F(FormatTest, FormatsNestedCall) { - verifyFormat("Method(f1, f2(f3));"); - verifyFormat("Method(f1(f2, f3()));"); - verifyFormat("Method(f1(f2, (f3())));"); -} - -TEST_F(FormatTest, NestedNameSpecifiers) { - verifyFormat("vector<::Type> v;"); - verifyFormat("::ns::SomeFunction(::ns::SomeOtherFunction())"); - verifyFormat("static constexpr bool Bar = decltype(bar())::value;"); - verifyFormat("bool a = 2 < ::SomeFunction();"); - verifyFormat("ALWAYS_INLINE ::std::string getName();"); - verifyFormat("some::string getName();"); -} - -TEST_F(FormatTest, OnlyGeneratesNecessaryReplacements) { - EXPECT_EQ("if (a) {\n" - " f();\n" - "}", - format("if(a){f();}")); - EXPECT_EQ(4, ReplacementCount); - EXPECT_EQ("if (a) {\n" - " f();\n" - "}", - format("if (a) {\n" - " f();\n" - "}")); - EXPECT_EQ(0, ReplacementCount); - EXPECT_EQ("/*\r\n" - "\r\n" - "*/\r\n", - format("/*\r\n" - "\r\n" - "*/\r\n")); - EXPECT_EQ(0, ReplacementCount); -} - -TEST_F(FormatTest, RemovesEmptyLines) { - EXPECT_EQ("class C {\n" - " int i;\n" - "};", - format("class C {\n" - " int i;\n" - "\n" - "};")); - - // Don't remove empty lines at the start of namespaces or extern "C" blocks. - EXPECT_EQ("namespace N {\n" - "\n" - "int i;\n" - "}", - format("namespace N {\n" - "\n" - "int i;\n" - "}", - getGoogleStyle())); - EXPECT_EQ("extern /**/ \"C\" /**/ {\n" - "\n" - "int i;\n" - "}", - format("extern /**/ \"C\" /**/ {\n" - "\n" - "int i;\n" - "}", - getGoogleStyle())); - - // ...but do keep inlining and removing empty lines for non-block extern "C" - // functions. - verifyFormat("extern \"C\" int f() { return 42; }", getGoogleStyle()); - EXPECT_EQ("extern \"C\" int f() {\n" - " int i = 42;\n" - " return i;\n" - "}", - format("extern \"C\" int f() {\n" - "\n" - " int i = 42;\n" - " return i;\n" - "}", - getGoogleStyle())); - - // Remove empty lines at the beginning and end of blocks. - EXPECT_EQ("void f() {\n" - "\n" - " if (a) {\n" - "\n" - " f();\n" - " }\n" - "}", - format("void f() {\n" - "\n" - " if (a) {\n" - "\n" - " f();\n" - "\n" - " }\n" - "\n" - "}", - getLLVMStyle())); - EXPECT_EQ("void f() {\n" - " if (a) {\n" - " f();\n" - " }\n" - "}", - format("void f() {\n" - "\n" - " if (a) {\n" - "\n" - " f();\n" - "\n" - " }\n" - "\n" - "}", - getGoogleStyle())); - - // Don't remove empty lines in more complex control statements. - EXPECT_EQ("void f() {\n" - " if (a) {\n" - " f();\n" - "\n" - " } else if (b) {\n" - " f();\n" - " }\n" - "}", - format("void f() {\n" - " if (a) {\n" - " f();\n" - "\n" - " } else if (b) {\n" - " f();\n" - "\n" - " }\n" - "\n" - "}")); - - // FIXME: This is slightly inconsistent. - FormatStyle LLVMWithNoNamespaceFix = getLLVMStyle(); - LLVMWithNoNamespaceFix.FixNamespaceComments = false; - EXPECT_EQ("namespace {\n" - "int i;\n" - "}", - format("namespace {\n" - "int i;\n" - "\n" - "}", LLVMWithNoNamespaceFix)); - EXPECT_EQ("namespace {\n" - "int i;\n" - "}", - format("namespace {\n" - "int i;\n" - "\n" - "}")); - EXPECT_EQ("namespace {\n" - "int i;\n" - "\n" - "} // namespace", - format("namespace {\n" - "int i;\n" - "\n" - "} // namespace")); - - FormatStyle Style = getLLVMStyle(); - Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; - Style.MaxEmptyLinesToKeep = 2; - Style.BreakBeforeBraces = FormatStyle::BS_Custom; - Style.BraceWrapping.AfterClass = true; - Style.BraceWrapping.AfterFunction = true; - Style.KeepEmptyLinesAtTheStartOfBlocks = false; - - EXPECT_EQ("class Foo\n" - "{\n" - " Foo() {}\n" - "\n" - " void funk() {}\n" - "};", - format("class Foo\n" - "{\n" - " Foo()\n" - " {\n" - " }\n" - "\n" - " void funk() {}\n" - "};", - Style)); -} - -TEST_F(FormatTest, RecognizesBinaryOperatorKeywords) { - verifyFormat("x = (a) and (b);"); - verifyFormat("x = (a) or (b);"); - verifyFormat("x = (a) bitand (b);"); - verifyFormat("x = (a) bitor (b);"); - verifyFormat("x = (a) not_eq (b);"); - verifyFormat("x = (a) and_eq (b);"); - verifyFormat("x = (a) or_eq (b);"); - verifyFormat("x = (a) xor (b);"); -} - -TEST_F(FormatTest, RecognizesUnaryOperatorKeywords) { - verifyFormat("x = compl(a);"); - verifyFormat("x = not(a);"); - verifyFormat("x = bitand(a);"); - // Unary operator must not be merged with the next identifier - verifyFormat("x = compl a;"); - verifyFormat("x = not a;"); - verifyFormat("x = bitand a;"); -} - -//===----------------------------------------------------------------------===// -// Tests for control statements. -//===----------------------------------------------------------------------===// - -TEST_F(FormatTest, FormatIfWithoutCompoundStatement) { - verifyFormat("if (true)\n f();\ng();"); - verifyFormat("if (a)\n if (b)\n if (c)\n g();\nh();"); - verifyFormat("if (a)\n if (b) {\n f();\n }\ng();"); - verifyFormat("if constexpr (true)\n" - " f();\ng();"); - verifyFormat("if constexpr (a)\n" - " if constexpr (b)\n" - " if constexpr (c)\n" - " g();\n" - "h();"); - verifyFormat("if constexpr (a)\n" - " if constexpr (b) {\n" - " f();\n" - " }\n" - "g();"); - - FormatStyle AllowsMergedIf = getLLVMStyle(); - AllowsMergedIf.AlignEscapedNewlines = FormatStyle::ENAS_Left; - AllowsMergedIf.AllowShortIfStatementsOnASingleLine = true; - verifyFormat("if (a)\n" - " // comment\n" - " f();", - AllowsMergedIf); - verifyFormat("{\n" - " if (a)\n" - " label:\n" - " f();\n" - "}", - AllowsMergedIf); - verifyFormat("#define A \\\n" - " if (a) \\\n" - " label: \\\n" - " f()", - AllowsMergedIf); - verifyFormat("if (a)\n" - " ;", - AllowsMergedIf); - verifyFormat("if (a)\n" - " if (b) return;", - AllowsMergedIf); - - verifyFormat("if (a) // Can't merge this\n" - " f();\n", - AllowsMergedIf); - verifyFormat("if (a) /* still don't merge */\n" - " f();", - AllowsMergedIf); - verifyFormat("if (a) { // Never merge this\n" - " f();\n" - "}", - AllowsMergedIf); - verifyFormat("if (a) { /* Never merge this */\n" - " f();\n" - "}", - AllowsMergedIf); - - AllowsMergedIf.ColumnLimit = 14; - verifyFormat("if (a) return;", AllowsMergedIf); - verifyFormat("if (aaaaaaaaa)\n" - " return;", - AllowsMergedIf); - - AllowsMergedIf.ColumnLimit = 13; - verifyFormat("if (a)\n return;", AllowsMergedIf); -} - -TEST_F(FormatTest, FormatLoopsWithoutCompoundStatement) { - FormatStyle AllowsMergedLoops = getLLVMStyle(); - AllowsMergedLoops.AllowShortLoopsOnASingleLine = true; - verifyFormat("while (true) continue;", AllowsMergedLoops); - verifyFormat("for (;;) continue;", AllowsMergedLoops); - verifyFormat("for (int &v : vec) v *= 2;", AllowsMergedLoops); - verifyFormat("while (true)\n" - " ;", - AllowsMergedLoops); - verifyFormat("for (;;)\n" - " ;", - AllowsMergedLoops); - verifyFormat("for (;;)\n" - " for (;;) continue;", - AllowsMergedLoops); - verifyFormat("for (;;) // Can't merge this\n" - " continue;", - AllowsMergedLoops); - verifyFormat("for (;;) /* still don't merge */\n" - " continue;", - AllowsMergedLoops); -} - -TEST_F(FormatTest, FormatShortBracedStatements) { - FormatStyle AllowSimpleBracedStatements = getLLVMStyle(); - AllowSimpleBracedStatements.AllowShortBlocksOnASingleLine = true; - - AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine = true; - AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = true; - - verifyFormat("if (true) {}", AllowSimpleBracedStatements); - verifyFormat("if constexpr (true) {}", AllowSimpleBracedStatements); - verifyFormat("while (true) {}", AllowSimpleBracedStatements); - verifyFormat("for (;;) {}", AllowSimpleBracedStatements); - verifyFormat("if (true) { f(); }", AllowSimpleBracedStatements); - verifyFormat("if constexpr (true) { f(); }", AllowSimpleBracedStatements); - verifyFormat("while (true) { f(); }", AllowSimpleBracedStatements); - verifyFormat("for (;;) { f(); }", AllowSimpleBracedStatements); - verifyFormat("if (true) { //\n" - " f();\n" - "}", - AllowSimpleBracedStatements); - verifyFormat("if (true) {\n" - " f();\n" - " f();\n" - "}", - AllowSimpleBracedStatements); - verifyFormat("if (true) {\n" - " f();\n" - "} else {\n" - " f();\n" - "}", - AllowSimpleBracedStatements); - - verifyFormat("struct A2 {\n" - " int X;\n" - "};", - AllowSimpleBracedStatements); - verifyFormat("typedef struct A2 {\n" - " int X;\n" - "} A2_t;", - AllowSimpleBracedStatements); - verifyFormat("template struct A2 {\n" - " struct B {};\n" - "};", - AllowSimpleBracedStatements); - - AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine = false; - verifyFormat("if (true) {\n" - " f();\n" - "}", - AllowSimpleBracedStatements); - verifyFormat("if (true) {\n" - " f();\n" - "} else {\n" - " f();\n" - "}", - AllowSimpleBracedStatements); - - AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = false; - verifyFormat("while (true) {\n" - " f();\n" - "}", - AllowSimpleBracedStatements); - verifyFormat("for (;;) {\n" - " f();\n" - "}", - AllowSimpleBracedStatements); -} - -TEST_F(FormatTest, ParseIfElse) { - verifyFormat("if (true)\n" - " if (true)\n" - " if (true)\n" - " f();\n" - " else\n" - " g();\n" - " else\n" - " h();\n" - "else\n" - " i();"); - verifyFormat("if (true)\n" - " if (true)\n" - " if (true) {\n" - " if (true)\n" - " f();\n" - " } else {\n" - " g();\n" - " }\n" - " else\n" - " h();\n" - "else {\n" - " i();\n" - "}"); - verifyFormat("if (true)\n" - " if constexpr (true)\n" - " if (true) {\n" - " if constexpr (true)\n" - " f();\n" - " } else {\n" - " g();\n" - " }\n" - " else\n" - " h();\n" - "else {\n" - " i();\n" - "}"); - verifyFormat("void f() {\n" - " if (a) {\n" - " } else {\n" - " }\n" - "}"); -} - -TEST_F(FormatTest, ElseIf) { - verifyFormat("if (a) {\n} else if (b) {\n}"); - verifyFormat("if (a)\n" - " f();\n" - "else if (b)\n" - " g();\n" - "else\n" - " h();"); - verifyFormat("if constexpr (a)\n" - " f();\n" - "else if constexpr (b)\n" - " g();\n" - "else\n" - " h();"); - verifyFormat("if (a) {\n" - " f();\n" - "}\n" - "// or else ..\n" - "else {\n" - " g()\n" - "}"); - - verifyFormat("if (a) {\n" - "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n" - "}"); - verifyFormat("if (a) {\n" - "} else if (\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n" - "}", - getLLVMStyleWithColumns(62)); - verifyFormat("if (a) {\n" - "} else if constexpr (\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n" - "}", - getLLVMStyleWithColumns(62)); -} - -TEST_F(FormatTest, FormatsForLoop) { - verifyFormat( - "for (int VeryVeryLongLoopVariable = 0; VeryVeryLongLoopVariable < 10;\n" - " ++VeryVeryLongLoopVariable)\n" - " ;"); - verifyFormat("for (;;)\n" - " f();"); - verifyFormat("for (;;) {\n}"); - verifyFormat("for (;;) {\n" - " f();\n" - "}"); - verifyFormat("for (int i = 0; (i < 10); ++i) {\n}"); - - verifyFormat( - "for (std::vector::iterator I = UnwrappedLines.begin(),\n" - " E = UnwrappedLines.end();\n" - " I != E; ++I) {\n}"); - - verifyFormat( - "for (MachineFun::iterator IIII = PrevIt, EEEE = F.end(); IIII != EEEE;\n" - " ++IIIII) {\n}"); - verifyFormat("for (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaa =\n" - " aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa;\n" - " aaaaaaaaaaa != aaaaaaaaaaaaaaaaaaa; ++aaaaaaaaaaa) {\n}"); - verifyFormat("for (llvm::ArrayRef::iterator\n" - " I = FD->getDeclsInPrototypeScope().begin(),\n" - " E = FD->getDeclsInPrototypeScope().end();\n" - " I != E; ++I) {\n}"); - verifyFormat("for (SmallVectorImpl::iterator\n" - " I = Container.begin(),\n" - " E = Container.end();\n" - " I != E; ++I) {\n}", - getLLVMStyleWithColumns(76)); - - verifyFormat( - "for (aaaaaaaaaaaaaaaaa aaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa !=\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n" - " ++aaaaaaaaaaa) {\n}"); - verifyFormat("for (int i = 0; i < aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" - " bbbbbbbbbbbbbbbbbbbb < ccccccccccccccc;\n" - " ++i) {\n}"); - verifyFormat("for (int aaaaaaaaaaa = 1; aaaaaaaaaaa <= bbbbbbbbbbbbbbb;\n" - " aaaaaaaaaaa++, bbbbbbbbbbbbbbbbb++) {\n" - "}"); - verifyFormat("for (some_namespace::SomeIterator iter( // force break\n" - " aaaaaaaaaa);\n" - " iter; ++iter) {\n" - "}"); - verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbbbbbbb;\n" - " ++aaaaaaaaaaaaaaaaaaaaaaaaaaa) {"); - - FormatStyle NoBinPacking = getLLVMStyle(); - NoBinPacking.BinPackParameters = false; - verifyFormat("for (int aaaaaaaaaaa = 1;\n" - " aaaaaaaaaaa <= aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa,\n" - " aaaaaaaaaaaaaaaa,\n" - " aaaaaaaaaaaaaaaa,\n" - " aaaaaaaaaaaaaaaa);\n" - " aaaaaaaaaaa++, bbbbbbbbbbbbbbbbb++) {\n" - "}", - NoBinPacking); - verifyFormat( - "for (std::vector::iterator I = UnwrappedLines.begin(),\n" - " E = UnwrappedLines.end();\n" - " I != E;\n" - " ++I) {\n}", - NoBinPacking); -} - -TEST_F(FormatTest, RangeBasedForLoops) { - verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}"); - verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaa :\n" - " aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa, aaaaaaaaaaaaa)) {\n}"); - verifyFormat("for (const aaaaaaaaaaaaaaaaaaaaa &aaaaaaaaa :\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}"); - verifyFormat("for (aaaaaaaaa aaaaaaaaaaaaaaaaaaaaa :\n" - " aaaaaaaaaaaa.aaaaaaaaaaaa().aaaaaaaaa().a()) {\n}"); -} - -TEST_F(FormatTest, ForEachLoops) { - verifyFormat("void f() {\n" - " foreach (Item *item, itemlist) {}\n" - " Q_FOREACH (Item *item, itemlist) {}\n" - " BOOST_FOREACH (Item *item, itemlist) {}\n" - " UNKNOWN_FORACH(Item * item, itemlist) {}\n" - "}"); - - // As function-like macros. - verifyFormat("#define foreach(x, y)\n" - "#define Q_FOREACH(x, y)\n" - "#define BOOST_FOREACH(x, y)\n" - "#define UNKNOWN_FOREACH(x, y)\n"); - - // Not as function-like macros. - verifyFormat("#define foreach (x, y)\n" - "#define Q_FOREACH (x, y)\n" - "#define BOOST_FOREACH (x, y)\n" - "#define UNKNOWN_FOREACH (x, y)\n"); -} - -TEST_F(FormatTest, FormatsWhileLoop) { - verifyFormat("while (true) {\n}"); - verifyFormat("while (true)\n" - " f();"); - verifyFormat("while () {\n}"); - verifyFormat("while () {\n" - " f();\n" - "}"); -} - -TEST_F(FormatTest, FormatsDoWhile) { - verifyFormat("do {\n" - " do_something();\n" - "} while (something());"); - verifyFormat("do\n" - " do_something();\n" - "while (something());"); -} - -TEST_F(FormatTest, FormatsSwitchStatement) { - verifyFormat("switch (x) {\n" - "case 1:\n" - " f();\n" - " break;\n" - "case kFoo:\n" - "case ns::kBar:\n" - "case kBaz:\n" - " break;\n" - "default:\n" - " g();\n" - " break;\n" - "}"); - verifyFormat("switch (x) {\n" - "case 1: {\n" - " f();\n" - " break;\n" - "}\n" - "case 2: {\n" - " break;\n" - "}\n" - "}"); - verifyFormat("switch (x) {\n" - "case 1: {\n" - " f();\n" - " {\n" - " g();\n" - " h();\n" - " }\n" - " break;\n" - "}\n" - "}"); - verifyFormat("switch (x) {\n" - "case 1: {\n" - " f();\n" - " if (foo) {\n" - " g();\n" - " h();\n" - " }\n" - " break;\n" - "}\n" - "}"); - verifyFormat("switch (x) {\n" - "case 1: {\n" - " f();\n" - " g();\n" - "} break;\n" - "}"); - verifyFormat("switch (test)\n" - " ;"); - verifyFormat("switch (x) {\n" - "default: {\n" - " // Do nothing.\n" - "}\n" - "}"); - verifyFormat("switch (x) {\n" - "// comment\n" - "// if 1, do f()\n" - "case 1:\n" - " f();\n" - "}"); - verifyFormat("switch (x) {\n" - "case 1:\n" - " // Do amazing stuff\n" - " {\n" - " f();\n" - " g();\n" - " }\n" - " break;\n" - "}"); - verifyFormat("#define A \\\n" - " switch (x) { \\\n" - " case a: \\\n" - " foo = b; \\\n" - " }", - getLLVMStyleWithColumns(20)); - verifyFormat("#define OPERATION_CASE(name) \\\n" - " case OP_name: \\\n" - " return operations::Operation##name\n", - getLLVMStyleWithColumns(40)); - verifyFormat("switch (x) {\n" - "case 1:;\n" - "default:;\n" - " int i;\n" - "}"); - - verifyGoogleFormat("switch (x) {\n" - " case 1:\n" - " f();\n" - " break;\n" - " case kFoo:\n" - " case ns::kBar:\n" - " case kBaz:\n" - " break;\n" - " default:\n" - " g();\n" - " break;\n" - "}"); - verifyGoogleFormat("switch (x) {\n" - " case 1: {\n" - " f();\n" - " break;\n" - " }\n" - "}"); - verifyGoogleFormat("switch (test)\n" - " ;"); - - verifyGoogleFormat("#define OPERATION_CASE(name) \\\n" - " case OP_name: \\\n" - " return operations::Operation##name\n"); - verifyGoogleFormat("Operation codeToOperation(OperationCode OpCode) {\n" - " // Get the correction operation class.\n" - " switch (OpCode) {\n" - " CASE(Add);\n" - " CASE(Subtract);\n" - " default:\n" - " return operations::Unknown;\n" - " }\n" - "#undef OPERATION_CASE\n" - "}"); - verifyFormat("DEBUG({\n" - " switch (x) {\n" - " case A:\n" - " f();\n" - " break;\n" - " // fallthrough\n" - " case B:\n" - " g();\n" - " break;\n" - " }\n" - "});"); - EXPECT_EQ("DEBUG({\n" - " switch (x) {\n" - " case A:\n" - " f();\n" - " break;\n" - " // On B:\n" - " case B:\n" - " g();\n" - " break;\n" - " }\n" - "});", - format("DEBUG({\n" - " switch (x) {\n" - " case A:\n" - " f();\n" - " break;\n" - " // On B:\n" - " case B:\n" - " g();\n" - " break;\n" - " }\n" - "});", - getLLVMStyle())); - verifyFormat("switch (a) {\n" - "case (b):\n" - " return;\n" - "}"); - - verifyFormat("switch (a) {\n" - "case some_namespace::\n" - " some_constant:\n" - " return;\n" - "}", - getLLVMStyleWithColumns(34)); -} - -TEST_F(FormatTest, CaseRanges) { - verifyFormat("switch (x) {\n" - "case 'A' ... 'Z':\n" - "case 1 ... 5:\n" - "case a ... b:\n" - " break;\n" - "}"); -} - -TEST_F(FormatTest, ShortCaseLabels) { - FormatStyle Style = getLLVMStyle(); - Style.AllowShortCaseLabelsOnASingleLine = true; - verifyFormat("switch (a) {\n" - "case 1: x = 1; break;\n" - "case 2: return;\n" - "case 3:\n" - "case 4:\n" - "case 5: return;\n" - "case 6: // comment\n" - " return;\n" - "case 7:\n" - " // comment\n" - " return;\n" - "case 8:\n" - " x = 8; // comment\n" - " break;\n" - "default: y = 1; break;\n" - "}", - Style); - verifyFormat("switch (a) {\n" - "case 0: return; // comment\n" - "case 1: break; // comment\n" - "case 2: return;\n" - "// comment\n" - "case 3: return;\n" - "// comment 1\n" - "// comment 2\n" - "// comment 3\n" - "case 4: break; /* comment */\n" - "case 5:\n" - " // comment\n" - " break;\n" - "case 6: /* comment */ x = 1; break;\n" - "case 7: x = /* comment */ 1; break;\n" - "case 8:\n" - " x = 1; /* comment */\n" - " break;\n" - "case 9:\n" - " break; // comment line 1\n" - " // comment line 2\n" - "}", - Style); - EXPECT_EQ("switch (a) {\n" - "case 1:\n" - " x = 8;\n" - " // fall through\n" - "case 2: x = 8;\n" - "// comment\n" - "case 3:\n" - " return; /* comment line 1\n" - " * comment line 2 */\n" - "case 4: i = 8;\n" - "// something else\n" - "#if FOO\n" - "case 5: break;\n" - "#endif\n" - "}", - format("switch (a) {\n" - "case 1: x = 8;\n" - " // fall through\n" - "case 2:\n" - " x = 8;\n" - "// comment\n" - "case 3:\n" - " return; /* comment line 1\n" - " * comment line 2 */\n" - "case 4:\n" - " i = 8;\n" - "// something else\n" - "#if FOO\n" - "case 5: break;\n" - "#endif\n" - "}", - Style)); - EXPECT_EQ("switch (a) {\n" "case 0:\n" - " return; // long long long long long long long long long long long long comment\n" - " // line\n" "}", - format("switch (a) {\n" - "case 0: return; // long long long long long long long long long long long long comment line\n" - "}", - Style)); - EXPECT_EQ("switch (a) {\n" - "case 0:\n" - " return; /* long long long long long long long long long long long long comment\n" - " line */\n" - "}", - format("switch (a) {\n" - "case 0: return; /* long long long long long long long long long long long long comment line */\n" - "}", - Style)); - verifyFormat("switch (a) {\n" - "#if FOO\n" - "case 0: return 0;\n" - "#endif\n" - "}", - Style); - verifyFormat("switch (a) {\n" - "case 1: {\n" - "}\n" - "case 2: {\n" - " return;\n" - "}\n" - "case 3: {\n" - " x = 1;\n" - " return;\n" - "}\n" - "case 4:\n" - " if (x)\n" - " return;\n" - "}", - Style); - Style.ColumnLimit = 21; - verifyFormat("switch (a) {\n" - "case 1: x = 1; break;\n" - "case 2: return;\n" - "case 3:\n" - "case 4:\n" - "case 5: return;\n" - "default:\n" - " y = 1;\n" - " break;\n" - "}", - Style); -} - -TEST_F(FormatTest, FormatsLabels) { - verifyFormat("void f() {\n" - " some_code();\n" - "test_label:\n" - " some_other_code();\n" - " {\n" - " some_more_code();\n" - " another_label:\n" - " some_more_code();\n" - " }\n" - "}"); - verifyFormat("{\n" - " some_code();\n" - "test_label:\n" - " some_other_code();\n" - "}"); - verifyFormat("{\n" - " some_code();\n" - "test_label:;\n" - " int i = 0;\n" - "}"); -} - -//===----------------------------------------------------------------------===// -// Tests for classes, namespaces, etc. -//===----------------------------------------------------------------------===// - -TEST_F(FormatTest, DoesNotBreakSemiAfterClassDecl) { - verifyFormat("class A {};"); -} - -TEST_F(FormatTest, UnderstandsAccessSpecifiers) { - verifyFormat("class A {\n" - "public:\n" - "public: // comment\n" - "protected:\n" - "private:\n" - " void f() {}\n" - "};"); - verifyGoogleFormat("class A {\n" - " public:\n" - " protected:\n" - " private:\n" - " void f() {}\n" - "};"); - verifyFormat("class A {\n" - "public slots:\n" - " void f1() {}\n" - "public Q_SLOTS:\n" - " void f2() {}\n" - "protected slots:\n" - " void f3() {}\n" - "protected Q_SLOTS:\n" - " void f4() {}\n" - "private slots:\n" - " void f5() {}\n" - "private Q_SLOTS:\n" - " void f6() {}\n" - "signals:\n" - " void g1();\n" - "Q_SIGNALS:\n" - " void g2();\n" - "};"); - - // Don't interpret 'signals' the wrong way. - verifyFormat("signals.set();"); - verifyFormat("for (Signals signals : f()) {\n}"); - verifyFormat("{\n" - " signals.set(); // This needs indentation.\n" - "}"); - verifyFormat("void f() {\n" - "label:\n" - " signals.baz();\n" - "}"); -} - -TEST_F(FormatTest, SeparatesLogicalBlocks) { - EXPECT_EQ("class A {\n" - "public:\n" - " void f();\n" - "\n" - "private:\n" - " void g() {}\n" - " // test\n" - "protected:\n" - " int h;\n" - "};", - format("class A {\n" - "public:\n" - "void f();\n" - "private:\n" - "void g() {}\n" - "// test\n" - "protected:\n" - "int h;\n" - "};")); - EXPECT_EQ("class A {\n" - "protected:\n" - "public:\n" - " void f();\n" - "};", - format("class A {\n" - "protected:\n" - "\n" - "public:\n" - "\n" - " void f();\n" - "};")); - - // Even ensure proper spacing inside macros. - EXPECT_EQ("#define B \\\n" - " class A { \\\n" - " protected: \\\n" - " public: \\\n" - " void f(); \\\n" - " };", - format("#define B \\\n" - " class A { \\\n" - " protected: \\\n" - " \\\n" - " public: \\\n" - " \\\n" - " void f(); \\\n" - " };", - getGoogleStyle())); - // But don't remove empty lines after macros ending in access specifiers. - EXPECT_EQ("#define A private:\n" - "\n" - "int i;", - format("#define A private:\n" - "\n" - "int i;")); -} - -TEST_F(FormatTest, FormatsClasses) { - verifyFormat("class A : public B {};"); - verifyFormat("class A : public ::B {};"); - - verifyFormat( - "class AAAAAAAAAAAAAAAAAAAA : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n" - " public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};"); - verifyFormat("class AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n" - " : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n" - " public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};"); - verifyFormat( - "class A : public B, public C, public D, public E, public F {};"); - verifyFormat("class AAAAAAAAAAAA : public B,\n" - " public C,\n" - " public D,\n" - " public E,\n" - " public F,\n" - " public G {};"); - - verifyFormat("class\n" - " ReallyReallyLongClassName {\n" - " int i;\n" - "};", - getLLVMStyleWithColumns(32)); - verifyFormat("struct aaaaaaaaaaaaa : public aaaaaaaaaaaaaaaaaaa< // break\n" - " aaaaaaaaaaaaaaaa> {};"); - verifyFormat("struct aaaaaaaaaaaaaaaaaaaa\n" - " : public aaaaaaaaaaaaaaaaaaa {};"); - verifyFormat("template \n" - "struct Aaaaaaaaaaaaaaaaa\n" - " : Aaaaaaaaaaaaaaaaa {};"); - verifyFormat("class ::A::B {};"); -} - -TEST_F(FormatTest, BreakBeforeInheritanceComma) { - FormatStyle StyleWithInheritanceBreak = getLLVMStyle(); - StyleWithInheritanceBreak.BreakBeforeInheritanceComma = true; - - verifyFormat("class MyClass : public X {};", StyleWithInheritanceBreak); - verifyFormat("class MyClass\n" - " : public X\n" - " , public Y {};", - StyleWithInheritanceBreak); -} - -TEST_F(FormatTest, FormatsVariableDeclarationsAfterStructOrClass) { - verifyFormat("class A {\n} a, b;"); - verifyFormat("struct A {\n} a, b;"); - verifyFormat("union A {\n} a;"); -} - -TEST_F(FormatTest, FormatsEnum) { - verifyFormat("enum {\n" - " Zero,\n" - " One = 1,\n" - " Two = One + 1,\n" - " Three = (One + Two),\n" - " Four = (Zero && (One ^ Two)) | (One << Two),\n" - " Five = (One, Two, Three, Four, 5)\n" - "};"); - verifyGoogleFormat("enum {\n" - " Zero,\n" - " One = 1,\n" - " Two = One + 1,\n" - " Three = (One + Two),\n" - " Four = (Zero && (One ^ Two)) | (One << Two),\n" - " Five = (One, Two, Three, Four, 5)\n" - "};"); - verifyFormat("enum Enum {};"); - verifyFormat("enum {};"); - verifyFormat("enum X E {} d;"); - verifyFormat("enum __attribute__((...)) E {} d;"); - verifyFormat("enum __declspec__((...)) E {} d;"); - verifyFormat("enum {\n" - " Bar = Foo::value\n" - "};", - getLLVMStyleWithColumns(30)); - - verifyFormat("enum ShortEnum { A, B, C };"); - verifyGoogleFormat("enum ShortEnum { A, B, C };"); - - EXPECT_EQ("enum KeepEmptyLines {\n" - " ONE,\n" - "\n" - " TWO,\n" - "\n" - " THREE\n" - "}", - format("enum KeepEmptyLines {\n" - " ONE,\n" - "\n" - " TWO,\n" - "\n" - "\n" - " THREE\n" - "}")); - verifyFormat("enum E { // comment\n" - " ONE,\n" - " TWO\n" - "};\n" - "int i;"); - // Not enums. - verifyFormat("enum X f() {\n" - " a();\n" - " return 42;\n" - "}"); - verifyFormat("enum X Type::f() {\n" - " a();\n" - " return 42;\n" - "}"); - verifyFormat("enum ::X f() {\n" - " a();\n" - " return 42;\n" - "}"); - verifyFormat("enum ns::X f() {\n" - " a();\n" - " return 42;\n" - "}"); -} - -TEST_F(FormatTest, FormatsEnumsWithErrors) { - verifyFormat("enum Type {\n" - " One = 0; // These semicolons should be commas.\n" - " Two = 1;\n" - "};"); - verifyFormat("namespace n {\n" - "enum Type {\n" - " One,\n" - " Two, // missing };\n" - " int i;\n" - "}\n" - "void g() {}"); -} - -TEST_F(FormatTest, FormatsEnumStruct) { - verifyFormat("enum struct {\n" - " Zero,\n" - " One = 1,\n" - " Two = One + 1,\n" - " Three = (One + Two),\n" - " Four = (Zero && (One ^ Two)) | (One << Two),\n" - " Five = (One, Two, Three, Four, 5)\n" - "};"); - verifyFormat("enum struct Enum {};"); - verifyFormat("enum struct {};"); - verifyFormat("enum struct X E {} d;"); - verifyFormat("enum struct __attribute__((...)) E {} d;"); - verifyFormat("enum struct __declspec__((...)) E {} d;"); - verifyFormat("enum struct X f() {\n a();\n return 42;\n}"); -} - -TEST_F(FormatTest, FormatsEnumClass) { - verifyFormat("enum class {\n" - " Zero,\n" - " One = 1,\n" - " Two = One + 1,\n" - " Three = (One + Two),\n" - " Four = (Zero && (One ^ Two)) | (One << Two),\n" - " Five = (One, Two, Three, Four, 5)\n" - "};"); - verifyFormat("enum class Enum {};"); - verifyFormat("enum class {};"); - verifyFormat("enum class X E {} d;"); - verifyFormat("enum class __attribute__((...)) E {} d;"); - verifyFormat("enum class __declspec__((...)) E {} d;"); - verifyFormat("enum class X f() {\n a();\n return 42;\n}"); -} - -TEST_F(FormatTest, FormatsEnumTypes) { - verifyFormat("enum X : int {\n" - " A, // Force multiple lines.\n" - " B\n" - "};"); - verifyFormat("enum X : int { A, B };"); - verifyFormat("enum X : std::uint32_t { A, B };"); -} - -TEST_F(FormatTest, FormatsNSEnums) { - verifyGoogleFormat("typedef NS_ENUM(NSInteger, SomeName) { AAA, BBB }"); - verifyGoogleFormat("typedef NS_ENUM(NSInteger, MyType) {\n" - " // Information about someDecentlyLongValue.\n" - " someDecentlyLongValue,\n" - " // Information about anotherDecentlyLongValue.\n" - " anotherDecentlyLongValue,\n" - " // Information about aThirdDecentlyLongValue.\n" - " aThirdDecentlyLongValue\n" - "};"); - verifyGoogleFormat("typedef NS_OPTIONS(NSInteger, MyType) {\n" - " a = 1,\n" - " b = 2,\n" - " c = 3,\n" - "};"); - verifyGoogleFormat("typedef CF_ENUM(NSInteger, MyType) {\n" - " a = 1,\n" - " b = 2,\n" - " c = 3,\n" - "};"); - verifyGoogleFormat("typedef CF_OPTIONS(NSInteger, MyType) {\n" - " a = 1,\n" - " b = 2,\n" - " c = 3,\n" - "};"); -} - -TEST_F(FormatTest, FormatsBitfields) { - verifyFormat("struct Bitfields {\n" - " unsigned sClass : 8;\n" - " unsigned ValueKind : 2;\n" - "};"); - verifyFormat("struct A {\n" - " int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa : 1,\n" - " bbbbbbbbbbbbbbbbbbbbbbbbb;\n" - "};"); - verifyFormat("struct MyStruct {\n" - " uchar data;\n" - " uchar : 8;\n" - " uchar : 8;\n" - " uchar other;\n" - "};"); -} - -TEST_F(FormatTest, FormatsNamespaces) { - FormatStyle LLVMWithNoNamespaceFix = getLLVMStyle(); - LLVMWithNoNamespaceFix.FixNamespaceComments = false; - - verifyFormat("namespace some_namespace {\n" - "class A {};\n" - "void f() { f(); }\n" - "}", - LLVMWithNoNamespaceFix); - verifyFormat("namespace {\n" - "class A {};\n" - "void f() { f(); }\n" - "}", - LLVMWithNoNamespaceFix); - verifyFormat("inline namespace X {\n" - "class A {};\n" - "void f() { f(); }\n" - "}", - LLVMWithNoNamespaceFix); - verifyFormat("using namespace some_namespace;\n" - "class A {};\n" - "void f() { f(); }", - LLVMWithNoNamespaceFix); - - // This code is more common than we thought; if we - // layout this correctly the semicolon will go into - // its own line, which is undesirable. - verifyFormat("namespace {};", - LLVMWithNoNamespaceFix); - verifyFormat("namespace {\n" - "class A {};\n" - "};", - LLVMWithNoNamespaceFix); - - verifyFormat("namespace {\n" - "int SomeVariable = 0; // comment\n" - "} // namespace", - LLVMWithNoNamespaceFix); - EXPECT_EQ("#ifndef HEADER_GUARD\n" - "#define HEADER_GUARD\n" - "namespace my_namespace {\n" - "int i;\n" - "} // my_namespace\n" - "#endif // HEADER_GUARD", - format("#ifndef HEADER_GUARD\n" - " #define HEADER_GUARD\n" - " namespace my_namespace {\n" - "int i;\n" - "} // my_namespace\n" - "#endif // HEADER_GUARD", - LLVMWithNoNamespaceFix)); - - EXPECT_EQ("namespace A::B {\n" - "class C {};\n" - "}", - format("namespace A::B {\n" - "class C {};\n" - "}", - LLVMWithNoNamespaceFix)); - - FormatStyle Style = getLLVMStyle(); - Style.NamespaceIndentation = FormatStyle::NI_All; - EXPECT_EQ("namespace out {\n" - " int i;\n" - " namespace in {\n" - " int i;\n" - " } // namespace in\n" - "} // namespace out", - format("namespace out {\n" - "int i;\n" - "namespace in {\n" - "int i;\n" - "} // namespace in\n" - "} // namespace out", - Style)); - - Style.NamespaceIndentation = FormatStyle::NI_Inner; - EXPECT_EQ("namespace out {\n" - "int i;\n" - "namespace in {\n" - " int i;\n" - "} // namespace in\n" - "} // namespace out", - format("namespace out {\n" - "int i;\n" - "namespace in {\n" - "int i;\n" - "} // namespace in\n" - "} // namespace out", - Style)); -} - -TEST_F(FormatTest, FormatsCompactNamespaces) { - FormatStyle Style = getLLVMStyle(); - Style.CompactNamespaces = true; - - verifyFormat("namespace A { namespace B {\n" - "}} // namespace A::B", - Style); - - EXPECT_EQ("namespace out { namespace in {\n" - "}} // namespace out::in", - format("namespace out {\n" - "namespace in {\n" - "} // namespace in\n" - "} // namespace out", - Style)); - - // Only namespaces which have both consecutive opening and end get compacted - EXPECT_EQ("namespace out {\n" - "namespace in1 {\n" - "} // namespace in1\n" - "namespace in2 {\n" - "} // namespace in2\n" - "} // namespace out", - format("namespace out {\n" - "namespace in1 {\n" - "} // namespace in1\n" - "namespace in2 {\n" - "} // namespace in2\n" - "} // namespace out", - Style)); - - EXPECT_EQ("namespace out {\n" - "int i;\n" - "namespace in {\n" - "int j;\n" - "} // namespace in\n" - "int k;\n" - "} // namespace out", - format("namespace out { int i;\n" - "namespace in { int j; } // namespace in\n" - "int k; } // namespace out", - Style)); - - EXPECT_EQ("namespace A { namespace B { namespace C {\n" - "}}} // namespace A::B::C\n", - format("namespace A { namespace B {\n" - "namespace C {\n" - "}} // namespace B::C\n" - "} // namespace A\n", - Style)); - - Style.ColumnLimit = 40; - EXPECT_EQ("namespace aaaaaaaaaa {\n" - "namespace bbbbbbbbbb {\n" - "}} // namespace aaaaaaaaaa::bbbbbbbbbb", - format("namespace aaaaaaaaaa {\n" - "namespace bbbbbbbbbb {\n" - "} // namespace bbbbbbbbbb\n" - "} // namespace aaaaaaaaaa", - Style)); - - EXPECT_EQ("namespace aaaaaa { namespace bbbbbb {\n" - "namespace cccccc {\n" - "}}} // namespace aaaaaa::bbbbbb::cccccc", - format("namespace aaaaaa {\n" - "namespace bbbbbb {\n" - "namespace cccccc {\n" - "} // namespace cccccc\n" - "} // namespace bbbbbb\n" - "} // namespace aaaaaa", - Style)); - Style.ColumnLimit = 80; - - // Extra semicolon after 'inner' closing brace prevents merging - EXPECT_EQ("namespace out { namespace in {\n" - "}; } // namespace out::in", - format("namespace out {\n" - "namespace in {\n" - "}; // namespace in\n" - "} // namespace out", - Style)); - - // Extra semicolon after 'outer' closing brace is conserved - EXPECT_EQ("namespace out { namespace in {\n" - "}}; // namespace out::in", - format("namespace out {\n" - "namespace in {\n" - "} // namespace in\n" - "}; // namespace out", - Style)); - - Style.NamespaceIndentation = FormatStyle::NI_All; - EXPECT_EQ("namespace out { namespace in {\n" - " int i;\n" - "}} // namespace out::in", - format("namespace out {\n" - "namespace in {\n" - "int i;\n" - "} // namespace in\n" - "} // namespace out", - Style)); - EXPECT_EQ("namespace out { namespace mid {\n" - " namespace in {\n" - " int j;\n" - " } // namespace in\n" - " int k;\n" - "}} // namespace out::mid", - format("namespace out { namespace mid {\n" - "namespace in { int j; } // namespace in\n" - "int k; }} // namespace out::mid", - Style)); - - Style.NamespaceIndentation = FormatStyle::NI_Inner; - EXPECT_EQ("namespace out { namespace in {\n" - " int i;\n" - "}} // namespace out::in", - format("namespace out {\n" - "namespace in {\n" - "int i;\n" - "} // namespace in\n" - "} // namespace out", - Style)); - EXPECT_EQ("namespace out { namespace mid { namespace in {\n" - " int i;\n" - "}}} // namespace out::mid::in", - format("namespace out {\n" - "namespace mid {\n" - "namespace in {\n" - "int i;\n" - "} // namespace in\n" - "} // namespace mid\n" - "} // namespace out", - Style)); -} - -TEST_F(FormatTest, FormatsExternC) { verifyFormat("extern \"C\" {\nint a;"); } - -TEST_F(FormatTest, FormatsInlineASM) { - verifyFormat("asm(\"xyz\" : \"=a\"(a), \"=d\"(b) : \"a\"(data));"); - verifyFormat("asm(\"nop\" ::: \"memory\");"); - verifyFormat( - "asm(\"movq\\t%%rbx, %%rsi\\n\\t\"\n" - " \"cpuid\\n\\t\"\n" - " \"xchgq\\t%%rbx, %%rsi\\n\\t\"\n" - " : \"=a\"(*rEAX), \"=S\"(*rEBX), \"=c\"(*rECX), \"=d\"(*rEDX)\n" - " : \"a\"(value));"); - EXPECT_EQ( - "void NS_InvokeByIndex(void *that, unsigned int methodIndex) {\n" - " __asm {\n" - " mov edx,[that] // vtable in edx\n" - " mov eax,methodIndex\n" - " call [edx][eax*4] // stdcall\n" - " }\n" - "}", - format("void NS_InvokeByIndex(void *that, unsigned int methodIndex) {\n" - " __asm {\n" - " mov edx,[that] // vtable in edx\n" - " mov eax,methodIndex\n" - " call [edx][eax*4] // stdcall\n" - " }\n" - "}")); - EXPECT_EQ("_asm {\n" - " xor eax, eax;\n" - " cpuid;\n" - "}", - format("_asm {\n" - " xor eax, eax;\n" - " cpuid;\n" - "}")); - verifyFormat("void function() {\n" - " // comment\n" - " asm(\"\");\n" - "}"); - EXPECT_EQ("__asm {\n" - "}\n" - "int i;", - format("__asm {\n" - "}\n" - "int i;")); -} - -TEST_F(FormatTest, FormatTryCatch) { - verifyFormat("try {\n" - " throw a * b;\n" - "} catch (int a) {\n" - " // Do nothing.\n" - "} catch (...) {\n" - " exit(42);\n" - "}"); - - // Function-level try statements. - verifyFormat("int f() try { return 4; } catch (...) {\n" - " return 5;\n" - "}"); - verifyFormat("class A {\n" - " int a;\n" - " A() try : a(0) {\n" - " } catch (...) {\n" - " throw;\n" - " }\n" - "};\n"); - - // Incomplete try-catch blocks. - verifyIncompleteFormat("try {} catch ("); -} - -TEST_F(FormatTest, FormatSEHTryCatch) { - verifyFormat("__try {\n" - " int a = b * c;\n" - "} __except (EXCEPTION_EXECUTE_HANDLER) {\n" - " // Do nothing.\n" - "}"); - - verifyFormat("__try {\n" - " int a = b * c;\n" - "} __finally {\n" - " // Do nothing.\n" - "}"); - - verifyFormat("DEBUG({\n" - " __try {\n" - " } __finally {\n" - " }\n" - "});\n"); -} - -TEST_F(FormatTest, IncompleteTryCatchBlocks) { - verifyFormat("try {\n" - " f();\n" - "} catch {\n" - " g();\n" - "}"); - verifyFormat("try {\n" - " f();\n" - "} catch (A a) MACRO(x) {\n" - " g();\n" - "} catch (B b) MACRO(x) {\n" - " g();\n" - "}"); -} - -TEST_F(FormatTest, FormatTryCatchBraceStyles) { - FormatStyle Style = getLLVMStyle(); - for (auto BraceStyle : {FormatStyle::BS_Attach, FormatStyle::BS_Mozilla, - FormatStyle::BS_WebKit}) { - Style.BreakBeforeBraces = BraceStyle; - verifyFormat("try {\n" - " // something\n" - "} catch (...) {\n" - " // something\n" - "}", - Style); - } - Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup; - verifyFormat("try {\n" - " // something\n" - "}\n" - "catch (...) {\n" - " // something\n" - "}", - Style); - verifyFormat("__try {\n" - " // something\n" - "}\n" - "__finally {\n" - " // something\n" - "}", - Style); - verifyFormat("@try {\n" - " // something\n" - "}\n" - "@finally {\n" - " // something\n" - "}", - Style); - Style.BreakBeforeBraces = FormatStyle::BS_Allman; - verifyFormat("try\n" - "{\n" - " // something\n" - "}\n" - "catch (...)\n" - "{\n" - " // something\n" - "}", - Style); - Style.BreakBeforeBraces = FormatStyle::BS_GNU; - verifyFormat("try\n" - " {\n" - " // something\n" - " }\n" - "catch (...)\n" - " {\n" - " // something\n" - " }", - Style); - Style.BreakBeforeBraces = FormatStyle::BS_Custom; - Style.BraceWrapping.BeforeCatch = true; - verifyFormat("try {\n" - " // something\n" - "}\n" - "catch (...) {\n" - " // something\n" - "}", - Style); -} - -TEST_F(FormatTest, StaticInitializers) { - verifyFormat("static SomeClass SC = {1, 'a'};"); - - verifyFormat("static SomeClass WithALoooooooooooooooooooongName = {\n" - " 100000000, " - "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"};"); - - // Here, everything other than the "}" would fit on a line. - verifyFormat("static int LooooooooooooooooooooooooongVariable[1] = {\n" - " 10000000000000000000000000};"); - EXPECT_EQ("S s = {a,\n" - "\n" - " b};", - format("S s = {\n" - " a,\n" - "\n" - " b\n" - "};")); - - // FIXME: This would fit into the column limit if we'd fit "{ {" on the first - // line. However, the formatting looks a bit off and this probably doesn't - // happen often in practice. - verifyFormat("static int Variable[1] = {\n" - " {1000000000000000000000000000000000000}};", - getLLVMStyleWithColumns(40)); -} - -TEST_F(FormatTest, DesignatedInitializers) { - verifyFormat("const struct A a = {.a = 1, .b = 2};"); - verifyFormat("const struct A a = {.aaaaaaaaaa = 1,\n" - " .bbbbbbbbbb = 2,\n" - " .cccccccccc = 3,\n" - " .dddddddddd = 4,\n" - " .eeeeeeeeee = 5};"); - verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n" - " .aaaaaaaaaaaaaaaaaaaaaaaaaaa = 1,\n" - " .bbbbbbbbbbbbbbbbbbbbbbbbbbb = 2,\n" - " .ccccccccccccccccccccccccccc = 3,\n" - " .ddddddddddddddddddddddddddd = 4,\n" - " .eeeeeeeeeeeeeeeeeeeeeeeeeee = 5};"); - - verifyGoogleFormat("const struct A a = {.a = 1, .b = 2};"); - - verifyFormat("const struct A a = {[0] = 1, [1] = 2};"); - verifyFormat("const struct A a = {[1] = aaaaaaaaaa,\n" - " [2] = bbbbbbbbbb,\n" - " [3] = cccccccccc,\n" - " [4] = dddddddddd,\n" - " [5] = eeeeeeeeee};"); - verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n" - " [1] = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" - " [2] = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n" - " [3] = cccccccccccccccccccccccccccccccccccccc,\n" - " [4] = dddddddddddddddddddddddddddddddddddddd,\n" - " [5] = eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee};"); -} - -TEST_F(FormatTest, NestedStaticInitializers) { - verifyFormat("static A x = {{{}}};\n"); - verifyFormat("static A x = {{{init1, init2, init3, init4},\n" - " {init1, init2, init3, init4}}};", - getLLVMStyleWithColumns(50)); - - verifyFormat("somes Status::global_reps[3] = {\n" - " {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n" - " {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n" - " {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};", - getLLVMStyleWithColumns(60)); - verifyGoogleFormat("SomeType Status::global_reps[3] = {\n" - " {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n" - " {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n" - " {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};"); - verifyFormat("CGRect cg_rect = {{rect.fLeft, rect.fTop},\n" - " {rect.fRight - rect.fLeft, rect.fBottom - " - "rect.fTop}};"); - - verifyFormat( - "SomeArrayOfSomeType a = {\n" - " {{1, 2, 3},\n" - " {1, 2, 3},\n" - " {111111111111111111111111111111, 222222222222222222222222222222,\n" - " 333333333333333333333333333333},\n" - " {1, 2, 3},\n" - " {1, 2, 3}}};"); - verifyFormat( - "SomeArrayOfSomeType a = {\n" - " {{1, 2, 3}},\n" - " {{1, 2, 3}},\n" - " {{111111111111111111111111111111, 222222222222222222222222222222,\n" - " 333333333333333333333333333333}},\n" - " {{1, 2, 3}},\n" - " {{1, 2, 3}}};"); - - verifyFormat("struct {\n" - " unsigned bit;\n" - " const char *const name;\n" - "} kBitsToOs[] = {{kOsMac, \"Mac\"},\n" - " {kOsWin, \"Windows\"},\n" - " {kOsLinux, \"Linux\"},\n" - " {kOsCrOS, \"Chrome OS\"}};"); - verifyFormat("struct {\n" - " unsigned bit;\n" - " const char *const name;\n" - "} kBitsToOs[] = {\n" - " {kOsMac, \"Mac\"},\n" - " {kOsWin, \"Windows\"},\n" - " {kOsLinux, \"Linux\"},\n" - " {kOsCrOS, \"Chrome OS\"},\n" - "};"); -} - -TEST_F(FormatTest, FormatsSmallMacroDefinitionsInSingleLine) { - verifyFormat("#define ALooooooooooooooooooooooooooooooooooooooongMacro(" - " \\\n" - " aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)"); -} - -TEST_F(FormatTest, DoesNotBreakPureVirtualFunctionDefinition) { - verifyFormat("virtual void write(ELFWriter *writerrr,\n" - " OwningPtr &buffer) = 0;"); - - // Do break defaulted and deleted functions. - verifyFormat("virtual void ~Deeeeeeeestructor() =\n" - " default;", - getLLVMStyleWithColumns(40)); - verifyFormat("virtual void ~Deeeeeeeestructor() =\n" - " delete;", - getLLVMStyleWithColumns(40)); -} - -TEST_F(FormatTest, BreaksStringLiteralsOnlyInDefine) { - verifyFormat("# 1111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\" 2 3", - getLLVMStyleWithColumns(40)); - verifyFormat("#line 11111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"", - getLLVMStyleWithColumns(40)); - EXPECT_EQ("#define Q \\\n" - " \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/\" \\\n" - " \"aaaaaaaa.cpp\"", - format("#define Q \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"", - getLLVMStyleWithColumns(40))); -} - -TEST_F(FormatTest, UnderstandsLinePPDirective) { - EXPECT_EQ("# 123 \"A string literal\"", - format(" # 123 \"A string literal\"")); -} - -TEST_F(FormatTest, LayoutUnknownPPDirective) { - EXPECT_EQ("#;", format("#;")); - verifyFormat("#\n;\n;\n;"); -} - -TEST_F(FormatTest, UnescapedEndOfLineEndsPPDirective) { - EXPECT_EQ("#line 42 \"test\"\n", - format("# \\\n line \\\n 42 \\\n \"test\"\n")); - EXPECT_EQ("#define A B\n", format("# \\\n define \\\n A \\\n B\n", - getLLVMStyleWithColumns(12))); -} - -TEST_F(FormatTest, EndOfFileEndsPPDirective) { - EXPECT_EQ("#line 42 \"test\"", - format("# \\\n line \\\n 42 \\\n \"test\"")); - EXPECT_EQ("#define A B", format("# \\\n define \\\n A \\\n B")); -} - -TEST_F(FormatTest, DoesntRemoveUnknownTokens) { - verifyFormat("#define A \\x20"); - verifyFormat("#define A \\ x20"); - EXPECT_EQ("#define A \\ x20", format("#define A \\ x20")); - verifyFormat("#define A ''"); - verifyFormat("#define A ''qqq"); - verifyFormat("#define A `qqq"); - verifyFormat("f(\"aaaa, bbbb, \"\\\"ccccc\\\"\");"); - EXPECT_EQ("const char *c = STRINGIFY(\n" - "\\na : b);", - format("const char * c = STRINGIFY(\n" - "\\na : b);")); - - verifyFormat("a\r\\"); - verifyFormat("a\v\\"); - verifyFormat("a\f\\"); -} - -TEST_F(FormatTest, IndentsPPDirectiveInReducedSpace) { - verifyFormat("#define A(BB)", getLLVMStyleWithColumns(13)); - verifyFormat("#define A( \\\n BB)", getLLVMStyleWithColumns(12)); - verifyFormat("#define A( \\\n A, B)", getLLVMStyleWithColumns(12)); - // FIXME: We never break before the macro name. - verifyFormat("#define AA( \\\n B)", getLLVMStyleWithColumns(12)); - - verifyFormat("#define A A\n#define A A"); - verifyFormat("#define A(X) A\n#define A A"); - - verifyFormat("#define Something Other", getLLVMStyleWithColumns(23)); - verifyFormat("#define Something \\\n Other", getLLVMStyleWithColumns(22)); -} - -TEST_F(FormatTest, HandlePreprocessorDirectiveContext) { - EXPECT_EQ("// somecomment\n" - "#include \"a.h\"\n" - "#define A( \\\n" - " A, B)\n" - "#include \"b.h\"\n" - "// somecomment\n", - format(" // somecomment\n" - " #include \"a.h\"\n" - "#define A(A,\\\n" - " B)\n" - " #include \"b.h\"\n" - " // somecomment\n", - getLLVMStyleWithColumns(13))); -} - -TEST_F(FormatTest, LayoutSingleHash) { EXPECT_EQ("#\na;", format("#\na;")); } - -TEST_F(FormatTest, LayoutCodeInMacroDefinitions) { - EXPECT_EQ("#define A \\\n" - " c; \\\n" - " e;\n" - "f;", - format("#define A c; e;\n" - "f;", - getLLVMStyleWithColumns(14))); -} - -TEST_F(FormatTest, LayoutRemainingTokens) { EXPECT_EQ("{}", format("{}")); } - -TEST_F(FormatTest, MacroDefinitionInsideStatement) { - EXPECT_EQ("int x,\n" - "#define A\n" - " y;", - format("int x,\n#define A\ny;")); -} - -TEST_F(FormatTest, HashInMacroDefinition) { - EXPECT_EQ("#define A(c) L#c", format("#define A(c) L#c", getLLVMStyle())); - verifyFormat("#define A \\\n b #c;", getLLVMStyleWithColumns(11)); - verifyFormat("#define A \\\n" - " { \\\n" - " f(#c); \\\n" - " }", - getLLVMStyleWithColumns(11)); - - verifyFormat("#define A(X) \\\n" - " void function##X()", - getLLVMStyleWithColumns(22)); - - verifyFormat("#define A(a, b, c) \\\n" - " void a##b##c()", - getLLVMStyleWithColumns(22)); - - verifyFormat("#define A void # ## #", getLLVMStyleWithColumns(22)); -} - -TEST_F(FormatTest, RespectWhitespaceInMacroDefinitions) { - EXPECT_EQ("#define A (x)", format("#define A (x)")); - EXPECT_EQ("#define A(x)", format("#define A(x)")); -} - -TEST_F(FormatTest, EmptyLinesInMacroDefinitions) { - EXPECT_EQ("#define A b;", format("#define A \\\n" - " \\\n" - " b;", - getLLVMStyleWithColumns(25))); - EXPECT_EQ("#define A \\\n" - " \\\n" - " a; \\\n" - " b;", - format("#define A \\\n" - " \\\n" - " a; \\\n" - " b;", - getLLVMStyleWithColumns(11))); - EXPECT_EQ("#define A \\\n" - " a; \\\n" - " \\\n" - " b;", - format("#define A \\\n" - " a; \\\n" - " \\\n" - " b;", - getLLVMStyleWithColumns(11))); -} - -TEST_F(FormatTest, MacroDefinitionsWithIncompleteCode) { - verifyIncompleteFormat("#define A :"); - verifyFormat("#define SOMECASES \\\n" - " case 1: \\\n" - " case 2\n", - getLLVMStyleWithColumns(20)); - verifyFormat("#define MACRO(a) \\\n" - " if (a) \\\n" - " f(); \\\n" - " else \\\n" - " g()", - getLLVMStyleWithColumns(18)); - verifyFormat("#define A template "); - verifyIncompleteFormat("#define STR(x) #x\n" - "f(STR(this_is_a_string_literal{));"); - verifyFormat("#pragma omp threadprivate( \\\n" - " y)), // expected-warning", - getLLVMStyleWithColumns(28)); - verifyFormat("#d, = };"); - verifyFormat("#if \"a"); - verifyIncompleteFormat("({\n" - "#define b \\\n" - " } \\\n" - " a\n" - "a", - getLLVMStyleWithColumns(15)); - verifyFormat("#define A \\\n" - " { \\\n" - " {\n" - "#define B \\\n" - " } \\\n" - " }", - getLLVMStyleWithColumns(15)); - verifyNoCrash("#if a\na(\n#else\n#endif\n{a"); - verifyNoCrash("a={0,1\n#if a\n#else\n;\n#endif\n}"); - verifyNoCrash("#if a\na(\n#else\n#endif\n) a {a,b,c,d,f,g};"); - verifyNoCrash("#ifdef A\n a(\n #else\n #endif\n) = []() { \n)}"); -} - -TEST_F(FormatTest, MacrosWithoutTrailingSemicolon) { - verifyFormat("SOME_TYPE_NAME abc;"); // Gated on the newline. - EXPECT_EQ("class A : public QObject {\n" - " Q_OBJECT\n" - "\n" - " A() {}\n" - "};", - format("class A : public QObject {\n" - " Q_OBJECT\n" - "\n" - " A() {\n}\n" - "} ;")); - EXPECT_EQ("MACRO\n" - "/*static*/ int i;", - format("MACRO\n" - " /*static*/ int i;")); - EXPECT_EQ("SOME_MACRO\n" - "namespace {\n" - "void f();\n" - "} // namespace", - format("SOME_MACRO\n" - " namespace {\n" - "void f( );\n" - "} // namespace")); - // Only if the identifier contains at least 5 characters. - EXPECT_EQ("HTTP f();", format("HTTP\nf();")); - EXPECT_EQ("MACRO\nf();", format("MACRO\nf();")); - // Only if everything is upper case. - EXPECT_EQ("class A : public QObject {\n" - " Q_Object A() {}\n" - "};", - format("class A : public QObject {\n" - " Q_Object\n" - " A() {\n}\n" - "} ;")); - - // Only if the next line can actually start an unwrapped line. - EXPECT_EQ("SOME_WEIRD_LOG_MACRO << SomeThing;", - format("SOME_WEIRD_LOG_MACRO\n" - "<< SomeThing;")); - - verifyFormat("VISIT_GL_CALL(GenBuffers, void, (GLsizei n, GLuint* buffers), " - "(n, buffers))\n", - getChromiumStyle(FormatStyle::LK_Cpp)); -} - -TEST_F(FormatTest, MacroCallsWithoutTrailingSemicolon) { - EXPECT_EQ("INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n" - "INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n" - "INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n" - "class X {};\n" - "INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n" - "int *createScopDetectionPass() { return 0; }", - format(" INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n" - " INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n" - " INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n" - " class X {};\n" - " INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n" - " int *createScopDetectionPass() { return 0; }")); - // FIXME: We could probably treat IPC_BEGIN_MESSAGE_MAP/IPC_END_MESSAGE_MAP as - // braces, so that inner block is indented one level more. - EXPECT_EQ("int q() {\n" - " IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n" - " IPC_MESSAGE_HANDLER(xxx, qqq)\n" - " IPC_END_MESSAGE_MAP()\n" - "}", - format("int q() {\n" - " IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n" - " IPC_MESSAGE_HANDLER(xxx, qqq)\n" - " IPC_END_MESSAGE_MAP()\n" - "}")); - - // Same inside macros. - EXPECT_EQ("#define LIST(L) \\\n" - " L(A) \\\n" - " L(B) \\\n" - " L(C)", - format("#define LIST(L) \\\n" - " L(A) \\\n" - " L(B) \\\n" - " L(C)", - getGoogleStyle())); - - // These must not be recognized as macros. - EXPECT_EQ("int q() {\n" - " f(x);\n" - " f(x) {}\n" - " f(x)->g();\n" - " f(x)->*g();\n" - " f(x).g();\n" - " f(x) = x;\n" - " f(x) += x;\n" - " f(x) -= x;\n" - " f(x) *= x;\n" - " f(x) /= x;\n" - " f(x) %= x;\n" - " f(x) &= x;\n" - " f(x) |= x;\n" - " f(x) ^= x;\n" - " f(x) >>= x;\n" - " f(x) <<= x;\n" - " f(x)[y].z();\n" - " LOG(INFO) << x;\n" - " ifstream(x) >> x;\n" - "}\n", - format("int q() {\n" - " f(x)\n;\n" - " f(x)\n {}\n" - " f(x)\n->g();\n" - " f(x)\n->*g();\n" - " f(x)\n.g();\n" - " f(x)\n = x;\n" - " f(x)\n += x;\n" - " f(x)\n -= x;\n" - " f(x)\n *= x;\n" - " f(x)\n /= x;\n" - " f(x)\n %= x;\n" - " f(x)\n &= x;\n" - " f(x)\n |= x;\n" - " f(x)\n ^= x;\n" - " f(x)\n >>= x;\n" - " f(x)\n <<= x;\n" - " f(x)\n[y].z();\n" - " LOG(INFO)\n << x;\n" - " ifstream(x)\n >> x;\n" - "}\n")); - EXPECT_EQ("int q() {\n" - " F(x)\n" - " if (1) {\n" - " }\n" - " F(x)\n" - " while (1) {\n" - " }\n" - " F(x)\n" - " G(x);\n" - " F(x)\n" - " try {\n" - " Q();\n" - " } catch (...) {\n" - " }\n" - "}\n", - format("int q() {\n" - "F(x)\n" - "if (1) {}\n" - "F(x)\n" - "while (1) {}\n" - "F(x)\n" - "G(x);\n" - "F(x)\n" - "try { Q(); } catch (...) {}\n" - "}\n")); - EXPECT_EQ("class A {\n" - " A() : t(0) {}\n" - " A(int i) noexcept() : {}\n" - " A(X x)\n" // FIXME: function-level try blocks are broken. - " try : t(0) {\n" - " } catch (...) {\n" - " }\n" - "};", - format("class A {\n" - " A()\n : t(0) {}\n" - " A(int i)\n noexcept() : {}\n" - " A(X x)\n" - " try : t(0) {} catch (...) {}\n" - "};")); - EXPECT_EQ("class SomeClass {\n" - "public:\n" - " SomeClass() EXCLUSIVE_LOCK_FUNCTION(mu_);\n" - "};", - format("class SomeClass {\n" - "public:\n" - " SomeClass()\n" - " EXCLUSIVE_LOCK_FUNCTION(mu_);\n" - "};")); - EXPECT_EQ("class SomeClass {\n" - "public:\n" - " SomeClass()\n" - " EXCLUSIVE_LOCK_FUNCTION(mu_);\n" - "};", - format("class SomeClass {\n" - "public:\n" - " SomeClass()\n" - " EXCLUSIVE_LOCK_FUNCTION(mu_);\n" - "};", - getLLVMStyleWithColumns(40))); - - verifyFormat("MACRO(>)"); -} - -TEST_F(FormatTest, LayoutMacroDefinitionsStatementsSpanningBlocks) { - verifyFormat("#define A \\\n" - " f({ \\\n" - " g(); \\\n" - " });", - getLLVMStyleWithColumns(11)); -} - -TEST_F(FormatTest, IndentPreprocessorDirectivesAtZero) { - EXPECT_EQ("{\n {\n#define A\n }\n}", format("{{\n#define A\n}}")); -} - -TEST_F(FormatTest, FormatHashIfNotAtStartOfLine) { - verifyFormat("{\n { a #c; }\n}"); -} - -TEST_F(FormatTest, FormatUnbalancedStructuralElements) { - EXPECT_EQ("#define A \\\n { \\\n {\nint i;", - format("#define A { {\nint i;", getLLVMStyleWithColumns(11))); - EXPECT_EQ("#define A \\\n } \\\n }\nint i;", - format("#define A } }\nint i;", getLLVMStyleWithColumns(11))); -} - -TEST_F(FormatTest, EscapedNewlines) { - EXPECT_EQ( - "#define A \\\n int i; \\\n int j;", - format("#define A \\\nint i;\\\n int j;", getLLVMStyleWithColumns(11))); - EXPECT_EQ("#define A\n\nint i;", format("#define A \\\n\n int i;")); - EXPECT_EQ("template f();", format("\\\ntemplate f();")); - EXPECT_EQ("/* \\ \\ \\\n */", format("\\\n/* \\ \\ \\\n */")); - EXPECT_EQ("", format("")); - - FormatStyle DontAlign = getLLVMStyle(); - DontAlign.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign; - DontAlign.MaxEmptyLinesToKeep = 3; - // FIXME: can't use verifyFormat here because the newline before - // "public:" is not inserted the first time it's reformatted - EXPECT_EQ("#define A \\\n" - " class Foo { \\\n" - " void bar(); \\\n" - "\\\n" - "\\\n" - "\\\n" - " public: \\\n" - " void baz(); \\\n" - " };", - format("#define A \\\n" - " class Foo { \\\n" - " void bar(); \\\n" - "\\\n" - "\\\n" - "\\\n" - " public: \\\n" - " void baz(); \\\n" - " };", DontAlign)); -} - -TEST_F(FormatTest, CalculateSpaceOnConsecutiveLinesInMacro) { - verifyFormat("#define A \\\n" - " int v( \\\n" - " a); \\\n" - " int i;", - getLLVMStyleWithColumns(11)); -} - -TEST_F(FormatTest, MixingPreprocessorDirectivesAndNormalCode) { - EXPECT_EQ( - "#define ALooooooooooooooooooooooooooooooooooooooongMacro(" - " \\\n" - " aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n" - "\n" - "AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n" - " aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n", - format(" #define ALooooooooooooooooooooooooooooooooooooooongMacro(" - "\\\n" - "aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n" - " \n" - " AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n" - " aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n")); -} - -TEST_F(FormatTest, LayoutStatementsAroundPreprocessorDirectives) { - EXPECT_EQ("int\n" - "#define A\n" - " a;", - format("int\n#define A\na;")); - verifyFormat("functionCallTo(\n" - " someOtherFunction(\n" - " withSomeParameters, whichInSequence,\n" - " areLongerThanALine(andAnotherCall,\n" - "#define A B\n" - " withMoreParamters,\n" - " whichStronglyInfluenceTheLayout),\n" - " andMoreParameters),\n" - " trailing);", - getLLVMStyleWithColumns(69)); - verifyFormat("Foo::Foo()\n" - "#ifdef BAR\n" - " : baz(0)\n" - "#endif\n" - "{\n" - "}"); - verifyFormat("void f() {\n" - " if (true)\n" - "#ifdef A\n" - " f(42);\n" - " x();\n" - "#else\n" - " g();\n" - " x();\n" - "#endif\n" - "}"); - verifyFormat("void f(param1, param2,\n" - " param3,\n" - "#ifdef A\n" - " param4(param5,\n" - "#ifdef A1\n" - " param6,\n" - "#ifdef A2\n" - " param7),\n" - "#else\n" - " param8),\n" - " param9,\n" - "#endif\n" - " param10,\n" - "#endif\n" - " param11)\n" - "#else\n" - " param12)\n" - "#endif\n" - "{\n" - " x();\n" - "}", - getLLVMStyleWithColumns(28)); - verifyFormat("#if 1\n" - "int i;"); - verifyFormat("#if 1\n" - "#endif\n" - "#if 1\n" - "#else\n" - "#endif\n"); - verifyFormat("DEBUG({\n" - " return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n" - "});\n" - "#if a\n" - "#else\n" - "#endif"); - - verifyIncompleteFormat("void f(\n" - "#if A\n" - ");\n" - "#else\n" - "#endif"); -} - -TEST_F(FormatTest, GraciouslyHandleIncorrectPreprocessorConditions) { - verifyFormat("#endif\n" - "#if B"); -} - -TEST_F(FormatTest, FormatsJoinedLinesOnSubsequentRuns) { - FormatStyle SingleLine = getLLVMStyle(); - SingleLine.AllowShortIfStatementsOnASingleLine = true; - verifyFormat("#if 0\n" - "#elif 1\n" - "#endif\n" - "void foo() {\n" - " if (test) foo2();\n" - "}", - SingleLine); -} - -TEST_F(FormatTest, LayoutBlockInsideParens) { - verifyFormat("functionCall({ int i; });"); - verifyFormat("functionCall({\n" - " int i;\n" - " int j;\n" - "});"); - verifyFormat("functionCall(\n" - " {\n" - " int i;\n" - " int j;\n" - " },\n" - " aaaa, bbbb, cccc);"); - verifyFormat("functionA(functionB({\n" - " int i;\n" - " int j;\n" - " }),\n" - " aaaa, bbbb, cccc);"); - verifyFormat("functionCall(\n" - " {\n" - " int i;\n" - " int j;\n" - " },\n" - " aaaa, bbbb, // comment\n" - " cccc);"); - verifyFormat("functionA(functionB({\n" - " int i;\n" - " int j;\n" - " }),\n" - " aaaa, bbbb, // comment\n" - " cccc);"); - verifyFormat("functionCall(aaaa, bbbb, { int i; });"); - verifyFormat("functionCall(aaaa, bbbb, {\n" - " int i;\n" - " int j;\n" - "});"); - verifyFormat( - "Aaa(\n" // FIXME: There shouldn't be a linebreak here. - " {\n" - " int i; // break\n" - " },\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n" - " ccccccccccccccccc));"); - verifyFormat("DEBUG({\n" - " if (a)\n" - " f();\n" - "});"); -} - -TEST_F(FormatTest, LayoutBlockInsideStatement) { - EXPECT_EQ("SOME_MACRO { int i; }\n" - "int i;", - format(" SOME_MACRO {int i;} int i;")); -} - -TEST_F(FormatTest, LayoutNestedBlocks) { - verifyFormat("void AddOsStrings(unsigned bitmask) {\n" - " struct s {\n" - " int i;\n" - " };\n" - " s kBitsToOs[] = {{10}};\n" - " for (int i = 0; i < 10; ++i)\n" - " return;\n" - "}"); - verifyFormat("call(parameter, {\n" - " something();\n" - " // Comment using all columns.\n" - " somethingelse();\n" - "});", - getLLVMStyleWithColumns(40)); - verifyFormat("DEBUG( //\n" - " { f(); }, a);"); - verifyFormat("DEBUG( //\n" - " {\n" - " f(); //\n" - " },\n" - " a);"); - - EXPECT_EQ("call(parameter, {\n" - " something();\n" - " // Comment too\n" - " // looooooooooong.\n" - " somethingElse();\n" - "});", - format("call(parameter, {\n" - " something();\n" - " // Comment too looooooooooong.\n" - " somethingElse();\n" - "});", - getLLVMStyleWithColumns(29))); - EXPECT_EQ("DEBUG({ int i; });", format("DEBUG({ int i; });")); - EXPECT_EQ("DEBUG({ // comment\n" - " int i;\n" - "});", - format("DEBUG({ // comment\n" - "int i;\n" - "});")); - EXPECT_EQ("DEBUG({\n" - " int i;\n" - "\n" - " // comment\n" - " int j;\n" - "});", - format("DEBUG({\n" - " int i;\n" - "\n" - " // comment\n" - " int j;\n" - "});")); - - verifyFormat("DEBUG({\n" - " if (a)\n" - " return;\n" - "});"); - verifyGoogleFormat("DEBUG({\n" - " if (a) return;\n" - "});"); - FormatStyle Style = getGoogleStyle(); - Style.ColumnLimit = 45; - verifyFormat("Debug(aaaaa,\n" - " {\n" - " if (aaaaaaaaaaaaaaaaaaaaaaaa) return;\n" - " },\n" - " a);", - Style); - - verifyFormat("SomeFunction({MACRO({ return output; }), b});"); - - verifyNoCrash("^{v^{a}}"); -} - -TEST_F(FormatTest, FormatNestedBlocksInMacros) { - EXPECT_EQ("#define MACRO() \\\n" - " Debug(aaa, /* force line break */ \\\n" - " { \\\n" - " int i; \\\n" - " int j; \\\n" - " })", - format("#define MACRO() Debug(aaa, /* force line break */ \\\n" - " { int i; int j; })", - getGoogleStyle())); - - EXPECT_EQ("#define A \\\n" - " [] { \\\n" - " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n" - " xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); \\\n" - " }", - format("#define A [] { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n" - "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); }", - getGoogleStyle())); -} - -TEST_F(FormatTest, PutEmptyBlocksIntoOneLine) { - EXPECT_EQ("{}", format("{}")); - verifyFormat("enum E {};"); - verifyFormat("enum E {}"); -} - -TEST_F(FormatTest, FormatBeginBlockEndMacros) { - FormatStyle Style = getLLVMStyle(); - Style.MacroBlockBegin = "^[A-Z_]+_BEGIN$"; - Style.MacroBlockEnd = "^[A-Z_]+_END$"; - verifyFormat("FOO_BEGIN\n" - " FOO_ENTRY\n" - "FOO_END", Style); - verifyFormat("FOO_BEGIN\n" - " NESTED_FOO_BEGIN\n" - " NESTED_FOO_ENTRY\n" - " NESTED_FOO_END\n" - "FOO_END", Style); - verifyFormat("FOO_BEGIN(Foo, Bar)\n" - " int x;\n" - " x = 1;\n" - "FOO_END(Baz)", Style); -} - -//===----------------------------------------------------------------------===// -// Line break tests. -//===----------------------------------------------------------------------===// - -TEST_F(FormatTest, PreventConfusingIndents) { - verifyFormat( - "void f() {\n" - " SomeLongMethodName(SomeReallyLongMethod(CallOtherReallyLongMethod(\n" - " parameter, parameter, parameter)),\n" - " SecondLongCall(parameter));\n" - "}"); - verifyFormat( - "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" - " aaaaaaaaaaaaaaaaaaaaaaaa(\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" - " aaaaaaaaaaaaaaaaaaaaaaaa);"); - verifyFormat( - "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" - " [aaaaaaaaaaaaaaaaaaaaaaaa\n" - " [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n" - " [aaaaaaaaaaaaaaaaaaaaaaaa]];"); - verifyFormat( - "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n" - " aaaaaaaaaaaaaaaaaaaaaaaa<\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>,\n" - " aaaaaaaaaaaaaaaaaaaaaaaa>;"); - verifyFormat("int a = bbbb && ccc &&\n" - " fffff(\n" - "#define A Just forcing a new line\n" - " ddd);"); -} - -TEST_F(FormatTest, LineBreakingInBinaryExpressions) { - verifyFormat( - "bool aaaaaaa =\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() ||\n" - " bbbbbbbb();"); - verifyFormat( - "bool aaaaaaa =\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() or\n" - " bbbbbbbb();"); - - verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb &&\n" - " ccccccccc == ddddddddddd;"); - verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb and\n" - " ccccccccc == ddddddddddd;"); - verifyFormat( - "bool aaaaaaaaaaaaaaaaaaaaa =\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa not_eq bbbbbbbbbbbbbbbbbb and\n" - " ccccccccc == ddddddddddd;"); - - verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n" - " aaaaaa) &&\n" - " bbbbbb && cccccc;"); - verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n" - " aaaaaa) >>\n" - " bbbbbb;"); - verifyFormat("aa = Whitespaces.addUntouchableComment(\n" - " SourceMgr.getSpellingColumnNumber(\n" - " TheLine.Last->FormatTok.Tok.getLocation()) -\n" - " 1);"); - - verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" - " bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaaaaaaa\n" - " cccccc) {\n}"); - verifyFormat("if constexpr ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" - " bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaa\n" - " cccccc) {\n}"); - verifyFormat("b = a &&\n" - " // Comment\n" - " b.c && d;"); - - // If the LHS of a comparison is not a binary expression itself, the - // additional linebreak confuses many people. - verifyFormat( - "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) > 5) {\n" - "}"); - verifyFormat( - "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n" - "}"); - verifyFormat( - "if (aaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaa(\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n" - "}"); - // Even explicit parentheses stress the precedence enough to make the - // additional break unnecessary. - verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n" - "}"); - // This cases is borderline, but with the indentation it is still readable. - verifyFormat( - "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" - " aaaaaaaaaaaaaaa) > aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n" - "}", - getLLVMStyleWithColumns(75)); - - // If the LHS is a binary expression, we should still use the additional break - // as otherwise the formatting hides the operator precedence. - verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" - " 5) {\n" - "}"); - - FormatStyle OnePerLine = getLLVMStyle(); - OnePerLine.BinPackParameters = false; - verifyFormat( - "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}", - OnePerLine); - - verifyFormat("int i = someFunction(aaaaaaa, 0)\n" - " .aaa(aaaaaaaaaaaaa) *\n" - " aaaaaaa +\n" - " aaaaaaa;", - getLLVMStyleWithColumns(40)); -} - -TEST_F(FormatTest, ExpressionIndentation) { - verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" - " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb +\n" - " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb &&\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >\n" - " ccccccccccccccccccccccccccccccccccccccccc;"); - verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" - " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}"); - verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" - " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}"); - verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" - " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}"); - verifyFormat("if () {\n" - "} else if (aaaaa && bbbbb > // break\n" - " ccccc) {\n" - "}"); - verifyFormat("if () {\n" - "} else if (aaaaa &&\n" - " bbbbb > // break\n" - " ccccc &&\n" - " ddddd) {\n" - "}"); - - // Presence of a trailing comment used to change indentation of b. - verifyFormat("return aaaaaaaaaaaaaaaaaaa +\n" - " b;\n" - "return aaaaaaaaaaaaaaaaaaa +\n" - " b; //", - getLLVMStyleWithColumns(30)); -} - -TEST_F(FormatTest, ExpressionIndentationBreakingBeforeOperators) { - // Not sure what the best system is here. Like this, the LHS can be found - // immediately above an operator (everything with the same or a higher - // indent). The RHS is aligned right of the operator and so compasses - // everything until something with the same indent as the operator is found. - // FIXME: Is this a good system? - FormatStyle Style = getLLVMStyle(); - Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; - verifyFormat( - "bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" - " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" - " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" - " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" - " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" - " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" - " && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" - " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" - " > ccccccccccccccccccccccccccccccccccccccccc;", - Style); - verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" - " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" - " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" - " == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", - Style); - verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" - " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" - " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" - " == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", - Style); - verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" - " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" - " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" - " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}", - Style); - verifyFormat("if () {\n" - "} else if (aaaaa\n" - " && bbbbb // break\n" - " > ccccc) {\n" - "}", - Style); - verifyFormat("return (a)\n" - " // comment\n" - " + b;", - Style); - verifyFormat( - "int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" - " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" - " + cc;", - Style); - - verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" - " = aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaa;", - Style); - - // Forced by comments. - verifyFormat( - "unsigned ContentSize =\n" - " sizeof(int16_t) // DWARF ARange version number\n" - " + sizeof(int32_t) // Offset of CU in the .debug_info section\n" - " + sizeof(int8_t) // Pointer Size (in bytes)\n" - " + sizeof(int8_t); // Segment Size (in bytes)"); - - verifyFormat("return boost::fusion::at_c<0>(iiii).second\n" - " == boost::fusion::at_c<1>(iiii).second;", - Style); - - Style.ColumnLimit = 60; - verifyFormat("zzzzzzzzzz\n" - " = bbbbbbbbbbbbbbbbb\n" - " >> aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa);", - Style); -} - -TEST_F(FormatTest, EnforcedOperatorWraps) { - // Here we'd like to wrap after the || operators, but a comment is forcing an - // earlier wrap. - verifyFormat("bool x = aaaaa //\n" - " || bbbbb\n" - " //\n" - " || cccc;"); -} - -TEST_F(FormatTest, NoOperandAlignment) { - FormatStyle Style = getLLVMStyle(); - Style.AlignOperands = false; - verifyFormat("aaaaaaaaaaaaaa(aaaaaaaaaaaa,\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", - Style); - Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment; - verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" - " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" - " + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" - " == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" - " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" - " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" - " && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" - " * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" - " > ccccccccccccccccccccccccccccccccccccccccc;", - Style); - - verifyFormat("int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" - " * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" - " + cc;", - Style); - verifyFormat("int a = aa\n" - " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n" - " * cccccccccccccccccccccccccccccccccccc;\n", - Style); - - Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; - verifyFormat("return (a > b\n" - " // comment1\n" - " // comment2\n" - " || c);", - Style); -} - -TEST_F(FormatTest, BreakingBeforeNonAssigmentOperators) { - FormatStyle Style = getLLVMStyle(); - Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment; - verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" - " + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;", - Style); -} - -TEST_F(FormatTest, AllowBinPackingInsideArguments) { - FormatStyle Style = getLLVMStyle(); - Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment; - Style.BinPackArguments = false; - Style.ColumnLimit = 40; - verifyFormat("void test() {\n" - " someFunction(\n" - " this + argument + is + quite\n" - " + long + so + it + gets + wrapped\n" - " + but + remains + bin - packed);\n" - "}", - Style); - verifyFormat("void test() {\n" - " someFunction(arg1,\n" - " this + argument + is\n" - " + quite + long + so\n" - " + it + gets + wrapped\n" - " + but + remains + bin\n" - " - packed,\n" - " arg3);\n" - "}", - Style); - verifyFormat("void test() {\n" - " someFunction(\n" - " arg1,\n" - " this + argument + has\n" - " + anotherFunc(nested,\n" - " calls + whose\n" - " + arguments\n" - " + are + also\n" - " + wrapped,\n" - " in + addition)\n" - " + to + being + bin - packed,\n" - " arg3);\n" - "}", - Style); - - Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None; - verifyFormat("void test() {\n" - " someFunction(\n" - " arg1,\n" - " this + argument + has +\n" - " anotherFunc(nested,\n" - " calls + whose +\n" - " arguments +\n" - " are + also +\n" - " wrapped,\n" - " in + addition) +\n" - " to + being + bin - packed,\n" - " arg3);\n" - "}", - Style); -} - -TEST_F(FormatTest, ConstructorInitializers) { - verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}"); - verifyFormat("Constructor() : Inttializer(FitsOnTheLine) {}", - getLLVMStyleWithColumns(45)); - verifyFormat("Constructor()\n" - " : Inttializer(FitsOnTheLine) {}", - getLLVMStyleWithColumns(44)); - verifyFormat("Constructor()\n" - " : Inttializer(FitsOnTheLine) {}", - getLLVMStyleWithColumns(43)); - - verifyFormat("template \n" - "Constructor() : Initializer(FitsOnTheLine) {}", - getLLVMStyleWithColumns(45)); - - verifyFormat( - "SomeClass::Constructor()\n" - " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}"); - - verifyFormat( - "SomeClass::Constructor()\n" - " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" - " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}"); - verifyFormat( - "SomeClass::Constructor()\n" - " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" - " aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}"); - verifyFormat("Constructor(aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" - " aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" - " : aaaaaaaaaa(aaaaaa) {}"); - - verifyFormat("Constructor()\n" - " : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" - " aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" - " aaaaaaaaaaaaaaaaaaaaaaa() {}"); - - verifyFormat("Constructor()\n" - " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}"); - - verifyFormat("Constructor(int Parameter = 0)\n" - " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n" - " aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}"); - verifyFormat("Constructor()\n" - " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbbbbb(b) {\n" - "}", - getLLVMStyleWithColumns(60)); - verifyFormat("Constructor()\n" - " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" - " aaaaaaaaaaaaaaaaaaaaaaaaa(aaaa, aaaa)) {}"); - - // Here a line could be saved by splitting the second initializer onto two - // lines, but that is not desirable. - verifyFormat("Constructor()\n" - " : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n" - " aaaaaaaaaaa(aaaaaaaaaaa),\n" - " aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}"); - - FormatStyle OnePerLine = getLLVMStyle(); - OnePerLine.ConstructorInitializerAllOnOneLineOrOnePerLine = true; - OnePerLine.AllowAllParametersOfDeclarationOnNextLine = false; - verifyFormat("SomeClass::Constructor()\n" - " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" - " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" - " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", - OnePerLine); - verifyFormat("SomeClass::Constructor()\n" - " : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n" - " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" - " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", - OnePerLine); - verifyFormat("MyClass::MyClass(int var)\n" - " : some_var_(var), // 4 space indent\n" - " some_other_var_(var + 1) { // lined up\n" - "}", - OnePerLine); - verifyFormat("Constructor()\n" - " : aaaaa(aaaaaa),\n" - " aaaaa(aaaaaa),\n" - " aaaaa(aaaaaa),\n" - " aaaaa(aaaaaa),\n" - " aaaaa(aaaaaa) {}", - OnePerLine); - verifyFormat("Constructor()\n" - " : aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n" - " aaaaaaaaaaaaaaaaaaaaaa) {}", - OnePerLine); - OnePerLine.BinPackParameters = false; - verifyFormat( - "Constructor()\n" - " : aaaaaaaaaaaaaaaaaaaaaaaa(\n" - " aaaaaaaaaaa().aaa(),\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", - OnePerLine); - OnePerLine.ColumnLimit = 60; - verifyFormat("Constructor()\n" - " : aaaaaaaaaaaaaaaaaaaa(a),\n" - " bbbbbbbbbbbbbbbbbbbbbbbb(b) {}", - OnePerLine); - - EXPECT_EQ("Constructor()\n" - " : // Comment forcing unwanted break.\n" - " aaaa(aaaa) {}", - format("Constructor() :\n" - " // Comment forcing unwanted break.\n" - " aaaa(aaaa) {}")); -} - -TEST_F(FormatTest, BreakConstructorInitializersAfterColon) { - FormatStyle Style = getLLVMStyle(); - Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon; - - verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}"); - verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}", - getStyleWithColumns(Style, 45)); - verifyFormat("Constructor() :\n" - " Initializer(FitsOnTheLine) {}", - getStyleWithColumns(Style, 44)); - verifyFormat("Constructor() :\n" - " Initializer(FitsOnTheLine) {}", - getStyleWithColumns(Style, 43)); - - verifyFormat("template \n" - "Constructor() : Initializer(FitsOnTheLine) {}", - getStyleWithColumns(Style, 50)); - - verifyFormat( - "SomeClass::Constructor() :\n" - " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}", - Style); - - verifyFormat( - "SomeClass::Constructor() :\n" - " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" - " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", - Style); - verifyFormat( - "SomeClass::Constructor() :\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" - " aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}", - Style); - verifyFormat("Constructor(aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" - " aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n" - " aaaaaaaaaa(aaaaaa) {}", - Style); - - verifyFormat("Constructor() :\n" - " aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" - " aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" - " aaaaaaaaaaaaaaaaaaaaaaa() {}", - Style); - - verifyFormat("Constructor() :\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", - Style); - - verifyFormat("Constructor(int Parameter = 0) :\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n" - " aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}", - Style); - verifyFormat("Constructor() :\n" - " aaaaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbbbbb(b) {\n" - "}", - getStyleWithColumns(Style, 60)); - verifyFormat("Constructor() :\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" - " aaaaaaaaaaaaaaaaaaaaaaaaa(aaaa, aaaa)) {}", - Style); - - // Here a line could be saved by splitting the second initializer onto two - // lines, but that is not desirable. - verifyFormat("Constructor() :\n" - " aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n" - " aaaaaaaaaaa(aaaaaaaaaaa),\n" - " aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", - Style); - - FormatStyle OnePerLine = Style; - OnePerLine.ConstructorInitializerAllOnOneLineOrOnePerLine = true; - OnePerLine.AllowAllParametersOfDeclarationOnNextLine = false; - verifyFormat("SomeClass::Constructor() :\n" - " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" - " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" - " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", - OnePerLine); - verifyFormat("SomeClass::Constructor() :\n" - " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n" - " aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n" - " aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}", - OnePerLine); - verifyFormat("MyClass::MyClass(int var) :\n" - " some_var_(var), // 4 space indent\n" - " some_other_var_(var + 1) { // lined up\n" - "}", - OnePerLine); - verifyFormat("Constructor() :\n" - " aaaaa(aaaaaa),\n" - " aaaaa(aaaaaa),\n" - " aaaaa(aaaaaa),\n" - " aaaaa(aaaaaa),\n" - " aaaaa(aaaaaa) {}", - OnePerLine); - verifyFormat("Constructor() :\n" - " aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n" - " aaaaaaaaaaaaaaaaaaaaaa) {}", - OnePerLine); - OnePerLine.BinPackParameters = false; - verifyFormat( - "Constructor() :\n" - " aaaaaaaaaaaaaaaaaaaaaaaa(\n" - " aaaaaaaaaaa().aaa(),\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", - OnePerLine); - OnePerLine.ColumnLimit = 60; - verifyFormat("Constructor() :\n" - " aaaaaaaaaaaaaaaaaaaa(a),\n" - " bbbbbbbbbbbbbbbbbbbbbbbb(b) {}", - OnePerLine); - - EXPECT_EQ("Constructor() :\n" - " // Comment forcing unwanted break.\n" - " aaaa(aaaa) {}", - format("Constructor() :\n" - " // Comment forcing unwanted break.\n" - " aaaa(aaaa) {}", - Style)); - - Style.ColumnLimit = 0; - verifyFormat("SomeClass::Constructor() :\n" - " a(a) {}", - Style); - verifyFormat("SomeClass::Constructor() noexcept :\n" - " a(a) {}", - Style); - verifyFormat("SomeClass::Constructor() :\n" - " a(a), b(b), c(c) {}", - Style); - verifyFormat("SomeClass::Constructor() :\n" - " a(a) {\n" - " foo();\n" - " bar();\n" - "}", - Style); - - Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; - verifyFormat("SomeClass::Constructor() :\n" - " a(a), b(b), c(c) {\n" - "}", - Style); - verifyFormat("SomeClass::Constructor() :\n" - " a(a) {\n" - "}", - Style); - - Style.ColumnLimit = 80; - Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; - Style.ConstructorInitializerIndentWidth = 2; - verifyFormat("SomeClass::Constructor() : a(a), b(b), c(c) {}", - Style); - verifyFormat("SomeClass::Constructor() :\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" - " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {}", - Style); -} - -TEST_F(FormatTest, MemoizationTests) { - // This breaks if the memoization lookup does not take \c Indent and - // \c LastSpace into account. - verifyFormat( - "extern CFRunLoopTimerRef\n" - "CFRunLoopTimerCreate(CFAllocatorRef allocato, CFAbsoluteTime fireDate,\n" - " CFTimeInterval interval, CFOptionFlags flags,\n" - " CFIndex order, CFRunLoopTimerCallBack callout,\n" - " CFRunLoopTimerContext *context) {}"); - - // Deep nesting somewhat works around our memoization. - verifyFormat( - "aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n" - " aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n" - " aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n" - " aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n" - " aaaaa())))))))))))))))))))))))))))))))))))))));", - getLLVMStyleWithColumns(65)); - verifyFormat( - "aaaaa(\n" - " aaaaa,\n" - " aaaaa(\n" - " aaaaa,\n" - " aaaaa(\n" - " aaaaa,\n" - " aaaaa(\n" - " aaaaa,\n" - " aaaaa(\n" - " aaaaa,\n" - " aaaaa(\n" - " aaaaa,\n" - " aaaaa(\n" - " aaaaa,\n" - " aaaaa(\n" - " aaaaa,\n" - " aaaaa(\n" - " aaaaa,\n" - " aaaaa(\n" - " aaaaa,\n" - " aaaaa(\n" - " aaaaa,\n" - " aaaaa(\n" - " aaaaa,\n" - " aaaaa))))))))))));", - getLLVMStyleWithColumns(65)); - verifyFormat( - "a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(), a), a), a), a),\n" - " a),\n" - " a),\n" - " a),\n" - " a),\n" - " a),\n" - " a),\n" - " a),\n" - " a),\n" - " a),\n" - " a),\n" - " a),\n" - " a),\n" - " a),\n" - " a),\n" - " a),\n" - " a),\n" - " a)", - getLLVMStyleWithColumns(65)); - - // This test takes VERY long when memoization is broken. - FormatStyle OnePerLine = getLLVMStyle(); - OnePerLine.ConstructorInitializerAllOnOneLineOrOnePerLine = true; - OnePerLine.BinPackParameters = false; - std::string input = "Constructor()\n" - " : aaaa(a,\n"; - for (unsigned i = 0, e = 80; i != e; ++i) { - input += " a,\n"; - } - input += " a) {}"; - verifyFormat(input, OnePerLine); -} - -TEST_F(FormatTest, BreaksAsHighAsPossible) { - verifyFormat( - "void f() {\n" - " if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaa && aaaaaaaaaaaaaaaaaaaaaaaaaa) ||\n" - " (bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb && bbbbbbbbbbbbbbbbbbbbbbbbbb))\n" - " f();\n" - "}"); - verifyFormat("if (Intervals[i].getRange().getFirst() <\n" - " Intervals[i - 1].getRange().getLast()) {\n}"); -} - -TEST_F(FormatTest, BreaksFunctionDeclarations) { - // Principially, we break function declarations in a certain order: - // 1) break amongst arguments. - verifyFormat("Aaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccc,\n" - " Cccccccccccccc cccccccccccccc);"); - verifyFormat("template \n" - "SomeReturnType SomeFunction(TemplateIt begin, TemplateIt end,\n" - " TemplateIt *stop) {}"); - - // 2) break after return type. - verifyFormat( - "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" - "bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccccccccccccccc);", - getGoogleStyle()); - - // 3) break after (. - verifyFormat( - "Aaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbb(\n" - " Cccccccccccccccccccccccccccccc cccccccccccccccccccccccccccccccc);", - getGoogleStyle()); - - // 4) break before after nested name specifiers. - verifyFormat( - "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" - "SomeClasssssssssssssssssssssssssssssssssssssss::\n" - " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc);", - getGoogleStyle()); - - // However, there are exceptions, if a sufficient amount of lines can be - // saved. - // FIXME: The precise cut-offs wrt. the number of saved lines might need some - // more adjusting. - verifyFormat("Aaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n" - " Cccccccccccccc cccccccccc,\n" - " Cccccccccccccc cccccccccc,\n" - " Cccccccccccccc cccccccccc,\n" - " Cccccccccccccc cccccccccc);"); - verifyFormat( - "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" - "bbbbbbbbbbb(Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" - " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" - " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);", - getGoogleStyle()); - verifyFormat( - "Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n" - " Cccccccccccccc cccccccccc,\n" - " Cccccccccccccc cccccccccc,\n" - " Cccccccccccccc cccccccccc,\n" - " Cccccccccccccc cccccccccc,\n" - " Cccccccccccccc cccccccccc,\n" - " Cccccccccccccc cccccccccc);"); - verifyFormat("Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n" - " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" - " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" - " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n" - " Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);"); - - // Break after multi-line parameters. - verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" - " bbbb bbbb);"); - verifyFormat("void SomeLoooooooooooongFunction(\n" - " std::unique_ptr\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaa,\n" - " int bbbbbbbbbbbbb);"); - - // Treat overloaded operators like other functions. - verifyFormat("SomeLoooooooooooooooooooooooooogType\n" - "operator>(const SomeLoooooooooooooooooooooooooogType &other);"); - verifyFormat("SomeLoooooooooooooooooooooooooogType\n" - "operator>>(const SomeLooooooooooooooooooooooooogType &other);"); - verifyFormat("SomeLoooooooooooooooooooooooooogType\n" - "operator<<(const SomeLooooooooooooooooooooooooogType &other);"); - verifyGoogleFormat( - "SomeLoooooooooooooooooooooooooooooogType operator>>(\n" - " const SomeLooooooooogType &a, const SomeLooooooooogType &b);"); - verifyGoogleFormat( - "SomeLoooooooooooooooooooooooooooooogType operator<<(\n" - " const SomeLooooooooogType &a, const SomeLooooooooogType &b);"); - verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" - " int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa = 1);"); - verifyFormat("aaaaaaaaaaaaaaaaaaaaaa\n" - "aaaaaaaaaaaaaaaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaa = 1);"); - verifyGoogleFormat( - "typename aaaaaaaaaa::aaaaaaaaaaa\n" - "aaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" - " bool *aaaaaaaaaaaaaaaaaa, bool *aa) {}"); - verifyGoogleFormat( - "template \n" - "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" - "aaaaaaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaa(\n" - " aaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaa);"); - - FormatStyle Style = getLLVMStyle(); - Style.PointerAlignment = FormatStyle::PAS_Left; - verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" - " aaaaaaaaaaaaaaaaaaaaaaaaa* const aaaaaaaaaaaa) {}", - Style); - verifyFormat("void aaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa*\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", - Style); -} - -TEST_F(FormatTest, TrailingReturnType) { - verifyFormat("auto foo() -> int;\n"); - verifyFormat("struct S {\n" - " auto bar() const -> int;\n" - "};"); - verifyFormat("template \n" - "auto load_img(const std::string &filename)\n" - " -> alias::tensor {}"); - verifyFormat("auto SomeFunction(A aaaaaaaaaaaaaaaaaaaaa) const\n" - " -> decltype(f(aaaaaaaaaaaaaaaaaaaaa)) {}"); - verifyFormat("auto doSomething(Aaaaaa *aaaaaa) -> decltype(aaaaaa->f()) {}"); - verifyFormat("template \n" - "auto aaaaaaaaaaaaaaaaaaaaaa(T t)\n" - " -> decltype(eaaaaaaaaaaaaaaa(t.a).aaaaaaaa());"); - - // Not trailing return types. - verifyFormat("void f() { auto a = b->c(); }"); -} - -TEST_F(FormatTest, BreaksFunctionDeclarationsWithTrailingTokens) { - // Avoid breaking before trailing 'const' or other trailing annotations, if - // they are not function-like. - FormatStyle Style = getGoogleStyle(); - Style.ColumnLimit = 47; - verifyFormat("void someLongFunction(\n" - " int someLoooooooooooooongParameter) const {\n}", - getLLVMStyleWithColumns(47)); - verifyFormat("LoooooongReturnType\n" - "someLoooooooongFunction() const {}", - getLLVMStyleWithColumns(47)); - verifyFormat("LoooooongReturnType someLoooooooongFunction()\n" - " const {}", - Style); - verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n" - " aaaaa aaaaaaaaaaaaaaaaaaaa) OVERRIDE;"); - verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n" - " aaaaa aaaaaaaaaaaaaaaaaaaa) OVERRIDE FINAL;"); - verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n" - " aaaaa aaaaaaaaaaaaaaaaaaaa) override final;"); - verifyFormat("virtual void aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa,\n" - " aaaaaaaaaaa aaaaa) const override;"); - verifyGoogleFormat( - "virtual void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" - " const override;"); - - // Even if the first parameter has to be wrapped. - verifyFormat("void someLongFunction(\n" - " int someLongParameter) const {}", - getLLVMStyleWithColumns(46)); - verifyFormat("void someLongFunction(\n" - " int someLongParameter) const {}", - Style); - verifyFormat("void someLongFunction(\n" - " int someLongParameter) override {}", - Style); - verifyFormat("void someLongFunction(\n" - " int someLongParameter) OVERRIDE {}", - Style); - verifyFormat("void someLongFunction(\n" - " int someLongParameter) final {}", - Style); - verifyFormat("void someLongFunction(\n" - " int someLongParameter) FINAL {}", - Style); - verifyFormat("void someLongFunction(\n" - " int parameter) const override {}", - Style); - - Style.BreakBeforeBraces = FormatStyle::BS_Allman; - verifyFormat("void someLongFunction(\n" - " int someLongParameter) const\n" - "{\n" - "}", - Style); - - // Unless these are unknown annotations. - verifyFormat("void SomeFunction(aaaaaaaaaa aaaaaaaaaaaaaaa,\n" - " aaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" - " LONG_AND_UGLY_ANNOTATION;"); - - // Breaking before function-like trailing annotations is fine to keep them - // close to their arguments. - verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" - " LOCKS_EXCLUDED(aaaaaaaaaaaaa);"); - verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n" - " LOCKS_EXCLUDED(aaaaaaaaaaaaa);"); - verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n" - " LOCKS_EXCLUDED(aaaaaaaaaaaaa) {}"); - verifyGoogleFormat("void aaaaaaaaaaaaaa(aaaaaaaa aaa) override\n" - " AAAAAAAAAAAAAAAAAAAAAAAA(aaaaaaaaaaaaaaa);"); - verifyFormat("SomeFunction([](int i) LOCKS_EXCLUDED(a) {});"); - - verifyFormat( - "void aaaaaaaaaaaaaaaaaa()\n" - " __attribute__((aaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaa,\n" - " aaaaaaaaaaaaaaaaaaaaaaaaa));"); - verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" - " __attribute__((unused));"); - verifyGoogleFormat( - "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" - " GUARDED_BY(aaaaaaaaaaaa);"); - verifyGoogleFormat( - "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" - " GUARDED_BY(aaaaaaaaaaaa);"); - verifyGoogleFormat( - "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa GUARDED_BY(aaaaaaaaaaaa) =\n" - " aaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); - verifyGoogleFormat( - "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa GUARDED_BY(aaaaaaaaaaaa) =\n" - " aaaaaaaaaaaaaaaaaaaaaaaaa;"); -} - -TEST_F(FormatTest, FunctionAnnotations) { - verifyFormat("DEPRECATED(\"Use NewClass::NewFunction instead.\")\n" - "int OldFunction(const string ¶meter) {}"); - verifyFormat("DEPRECATED(\"Use NewClass::NewFunction instead.\")\n" - "string OldFunction(const string ¶meter) {}"); - verifyFormat("template \n" - "DEPRECATED(\"Use NewClass::NewFunction instead.\")\n" - "string OldFunction(const string ¶meter) {}"); - - // Not function annotations. - verifyFormat("ASSERT(\"aaaaa\") << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" - " << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"); - verifyFormat("TEST_F(ThisIsATestFixtureeeeeeeeeeeee,\n" - " ThisIsATestWithAReallyReallyReallyReallyLongName) {}"); - verifyFormat("MACRO(abc).function() // wrap\n" - " << abc;"); - verifyFormat("MACRO(abc)->function() // wrap\n" - " << abc;"); - verifyFormat("MACRO(abc)::function() // wrap\n" - " << abc;"); -} - -TEST_F(FormatTest, BreaksDesireably) { - verifyFormat("if (aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n" - " aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n" - " aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa)) {\n}"); - verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n" - "}"); - - verifyFormat( - "aaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}"); - - verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));"); - - verifyFormat( - "aaaaaaaa(aaaaaaaaaaaaa,\n" - " aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n" - " aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));"); - - verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n" - " (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); - - verifyFormat( - "void f() {\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa &&\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n" - "}"); - verifyFormat( - "aaaaaa(new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));"); - verifyFormat( - "aaaaaa(aaa, new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));"); - verifyFormat( - "aaaaaa(aaa,\n" - " new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" - " aaaa);"); - verifyFormat("aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); - - // Indent consistently independent of call expression and unary operator. - verifyFormat("aaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n" - " dddddddddddddddddddddddddddddd));"); - verifyFormat("aaaaaaaaaaa(!bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n" - " dddddddddddddddddddddddddddddd));"); - verifyFormat("aaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbb.ccccccccccccccccc(\n" - " dddddddddddddddddddddddddddddd));"); - - // This test case breaks on an incorrect memoization, i.e. an optimization not - // taking into account the StopAt value. - verifyFormat( - "return aaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n" - " aaaaaaaaaaa(aaaaaaaaa) || aaaaaaaaaaaaaaaaaaaaaaa ||\n" - " aaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n" - " (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); - - verifyFormat("{\n {\n {\n" - " Annotation.SpaceRequiredBefore =\n" - " Line.Tokens[i - 1].Tok.isNot(tok::l_paren) &&\n" - " Line.Tokens[i - 1].Tok.isNot(tok::l_square);\n" - " }\n }\n}"); - - // Break on an outer level if there was a break on an inner level. - EXPECT_EQ("f(g(h(a, // comment\n" - " b, c),\n" - " d, e),\n" - " x, y);", - format("f(g(h(a, // comment\n" - " b, c), d, e), x, y);")); - - // Prefer breaking similar line breaks. - verifyFormat( - "const int kTrackingOptions = NSTrackingMouseMoved |\n" - " NSTrackingMouseEnteredAndExited |\n" - " NSTrackingActiveAlways;"); -} - -TEST_F(FormatTest, FormatsDeclarationsOnePerLine) { - FormatStyle NoBinPacking = getGoogleStyle(); - NoBinPacking.BinPackParameters = false; - NoBinPacking.BinPackArguments = true; - verifyFormat("void f() {\n" - " f(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaa,\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n" - "}", - NoBinPacking); - verifyFormat("void f(int aaaaaaaaaaaaaaaaaaaa,\n" - " int aaaaaaaaaaaaaaaaaaaa,\n" - " int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", - NoBinPacking); - - NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false; - verifyFormat("void aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" - " vector bbbbbbbbbbbbbbb);", - NoBinPacking); - // FIXME: This behavior difference is probably not wanted. However, currently - // we cannot distinguish BreakBeforeParameter being set because of the wrapped - // template arguments from BreakBeforeParameter being set because of the - // one-per-line formatting. - verifyFormat( - "void fffffffffff(aaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaa);", - NoBinPacking); - verifyFormat( - "void fffffffffff(\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaa\n" - " aaaaaaaaaa);"); -} - -TEST_F(FormatTest, FormatsOneParameterPerLineIfNecessary) { - FormatStyle NoBinPacking = getGoogleStyle(); - NoBinPacking.BinPackParameters = false; - NoBinPacking.BinPackArguments = false; - verifyFormat("f(aaaaaaaaaaaaaaaaaaaa,\n" - " aaaaaaaaaaaaaaaaaaaa,\n" - " aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaa);", - NoBinPacking); - verifyFormat("aaaaaaa(aaaaaaaaaaaaa,\n" - " aaaaaaaaaaaaa,\n" - " aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));", - NoBinPacking); - verifyFormat( - "aaaaaaaa(aaaaaaaaaaaaa,\n" - " aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n" - " aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));", - NoBinPacking); - verifyFormat("aaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n" - " .aaaaaaaaaaaaaaaaaa();", - NoBinPacking); - verifyFormat("void f() {\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" - " aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaa);\n" - "}", - NoBinPacking); - - verifyFormat( - "aaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa,\n" - " aaaaaaaaaaaa,\n" - " aaaaaaaaaaaa);", - NoBinPacking); - verifyFormat( - "somefunction(someotherFunction(ddddddddddddddddddddddddddddddddddd,\n" - " ddddddddddddddddddddddddddddd),\n" - " test);", - NoBinPacking); - - verifyFormat("std::vector\n" - " aaaaaaaaaaaaaaaaaa;", - NoBinPacking); - verifyFormat("a(\"a\"\n" - " \"a\",\n" - " a);"); - - NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false; - verifyFormat("void aaaaaaaaaa(aaaaaaaaa,\n" - " aaaaaaaaa,\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", - NoBinPacking); - verifyFormat( - "void f() {\n" - " aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n" - " .aaaaaaa();\n" - "}", - NoBinPacking); - verifyFormat( - "template \n" - "SomeType SomeFunction(SomeType Type, SomeOtherType OtherType) {}", - NoBinPacking); -} - -TEST_F(FormatTest, AdaptiveOnePerLineFormatting) { - FormatStyle Style = getLLVMStyleWithColumns(15); - Style.ExperimentalAutoDetectBinPacking = true; - EXPECT_EQ("aaa(aaaa,\n" - " aaaa,\n" - " aaaa);\n" - "aaa(aaaa,\n" - " aaaa,\n" - " aaaa);", - format("aaa(aaaa,\n" // one-per-line - " aaaa,\n" - " aaaa );\n" - "aaa(aaaa, aaaa, aaaa);", // inconclusive - Style)); - EXPECT_EQ("aaa(aaaa, aaaa,\n" - " aaaa);\n" - "aaa(aaaa, aaaa,\n" - " aaaa);", - format("aaa(aaaa, aaaa,\n" // bin-packed - " aaaa );\n" - "aaa(aaaa, aaaa, aaaa);", // inconclusive - Style)); -} - -TEST_F(FormatTest, FormatsBuilderPattern) { - verifyFormat("return llvm::StringSwitch(name)\n" - " .StartsWith(\".eh_frame_hdr\", ORDER_EH_FRAMEHDR)\n" - " .StartsWith(\".eh_frame\", ORDER_EH_FRAME)\n" - " .StartsWith(\".init\", ORDER_INIT)\n" - " .StartsWith(\".fini\", ORDER_FINI)\n" - " .StartsWith(\".hash\", ORDER_HASH)\n" - " .Default(ORDER_TEXT);\n"); - - verifyFormat("return aaaaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa() <\n" - " aaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa();"); - verifyFormat( - "aaaaaaa->aaaaaaa\n" - " ->aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" - " ->aaaaaaaa(aaaaaaaaaaaaaaa);"); - verifyFormat( - "aaaaaaa->aaaaaaa\n" - " ->aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" - " ->aaaaaaaa(aaaaaaaaaaaaaaa);"); - verifyFormat( - "aaaaaaaaaaaaaaaaaaa()->aaaaaa(bbbbb)->aaaaaaaaaaaaaaaaaaa( // break\n" - " aaaaaaaaaaaaaa);"); - verifyFormat( - "aaaaaaaaaaaaaaaaaaaaaaa *aaaaaaaaa =\n" - " aaaaaa->aaaaaaaaaaaa()\n" - " ->aaaaaaaaaaaaaaaa(\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" - " ->aaaaaaaaaaaaaaaaa();"); - verifyGoogleFormat( - "void f() {\n" - " someo->Add((new util::filetools::Handler(dir))\n" - " ->OnEvent1(NewPermanentCallback(\n" - " this, &HandlerHolderClass::EventHandlerCBA))\n" - " ->OnEvent2(NewPermanentCallback(\n" - " this, &HandlerHolderClass::EventHandlerCBB))\n" - " ->OnEvent3(NewPermanentCallback(\n" - " this, &HandlerHolderClass::EventHandlerCBC))\n" - " ->OnEvent5(NewPermanentCallback(\n" - " this, &HandlerHolderClass::EventHandlerCBD))\n" - " ->OnEvent6(NewPermanentCallback(\n" - " this, &HandlerHolderClass::EventHandlerCBE)));\n" - "}"); - - verifyFormat( - "aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa();"); - verifyFormat("aaaaaaaaaaaaaaa()\n" - " .aaaaaaaaaaaaaaa()\n" - " .aaaaaaaaaaaaaaa()\n" - " .aaaaaaaaaaaaaaa()\n" - " .aaaaaaaaaaaaaaa();"); - verifyFormat("aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n" - " .aaaaaaaaaaaaaaa()\n" - " .aaaaaaaaaaaaaaa()\n" - " .aaaaaaaaaaaaaaa();"); - verifyFormat("aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n" - " .aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n" - " .aaaaaaaaaaaaaaa();"); - verifyFormat("aaaaaaaaaaaaa->aaaaaaaaaaaaaaaaaaaaaaaa()\n" - " ->aaaaaaaaaaaaaae(0)\n" - " ->aaaaaaaaaaaaaaa();"); - - // Don't linewrap after very short segments. - verifyFormat("a().aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" - " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" - " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); - verifyFormat("aa().aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" - " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" - " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); - verifyFormat("aaa()\n" - " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" - " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" - " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); - - verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaa()\n" - " .aaaaaaaaaaaaaaaaaaaaaaaaaa()\n" - " .has();"); - verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaa()\n" - " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>();"); - - // Prefer not to break after empty parentheses. - verifyFormat("FirstToken->WhitespaceRange.getBegin().getLocWithOffset(\n" - " First->LastNewlineOffset);"); - - // Prefer not to create "hanging" indents. - verifyFormat( - "return !soooooooooooooome_map\n" - " .insert(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" - " .second;"); - verifyFormat( - "return aaaaaaaaaaaaaaaa\n" - " .aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa)\n" - " .aaaa(aaaaaaaaaaaaaa);"); - // No hanging indent here. - verifyFormat("aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaa.aaaaaaaaaaaaaaa(\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); - verifyFormat("aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaa().aaaaaaaaaaaaaaa(\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); - verifyFormat("aaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa)\n" - " .aaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", - getLLVMStyleWithColumns(60)); - verifyFormat("aaaaaaaaaaaaaaaaaa\n" - " .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa)\n" - " .aaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", - getLLVMStyleWithColumns(59)); - verifyFormat("aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" - " .aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); -} - -TEST_F(FormatTest, BreaksAccordingToOperatorPrecedence) { - verifyFormat( - "if (aaaaaaaaaaaaaaaaaaaaaaaaa ||\n" - " bbbbbbbbbbbbbbbbbbbbbbbbb && ccccccccccccccccccccccccc) {\n}"); - verifyFormat( - "if (aaaaaaaaaaaaaaaaaaaaaaaaa or\n" - " bbbbbbbbbbbbbbbbbbbbbbbbb and cccccccccccccccccccccccc) {\n}"); - - verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa && bbbbbbbbbbbbbbbbbbbbbbbbb ||\n" - " ccccccccccccccccccccccccc) {\n}"); - verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa and bbbbbbbbbbbbbbbbbbbbbbbb or\n" - " ccccccccccccccccccccccccc) {\n}"); - - verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb ||\n" - " ccccccccccccccccccccccccc) {\n}"); - verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa or bbbbbbbbbbbbbbbbbbbbbbbbb or\n" - " ccccccccccccccccccccccccc) {\n}"); - - verifyFormat( - "if ((aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb) &&\n" - " ccccccccccccccccccccccccc) {\n}"); - verifyFormat( - "if ((aaaaaaaaaaaaaaaaaaaaaaaaa or bbbbbbbbbbbbbbbbbbbbbbbbb) and\n" - " ccccccccccccccccccccccccc) {\n}"); - - verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA ||\n" - " bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB ||\n" - " cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC ||\n" - " dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;"); - verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA or\n" - " bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB or\n" - " cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC or\n" - " dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;"); - - verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa ||\n" - " aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) &&\n" - " aaaaaaaaaaaaaaa != aa) {\n}"); - verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa or\n" - " aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) and\n" - " aaaaaaaaaaaaaaa != aa) {\n}"); -} - -TEST_F(FormatTest, BreaksAfterAssignments) { - verifyFormat( - "unsigned Cost =\n" - " TTI.getMemoryOpCost(I->getOpcode(), VectorTy, SI->getAlignment(),\n" - " SI->getPointerAddressSpaceee());\n"); - verifyFormat( - "CharSourceRange LineRange = CharSourceRange::getTokenRange(\n" - " Line.Tokens.front().Tok.getLo(), Line.Tokens.back().Tok.getLoc());"); - - verifyFormat( - "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa = aaaaaaaaaaaaaa(0).aaaa().aaaaaaaaa(\n" - " aaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaa);"); - verifyFormat("unsigned OriginalStartColumn =\n" - " SourceMgr.getSpellingColumnNumber(\n" - " Current.FormatTok.getStartOfNonWhitespace()) -\n" - " 1;"); -} - -TEST_F(FormatTest, ConfigurableBreakAssignmentPenalty) { - FormatStyle Style = getLLVMStyle(); - verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaa =\n" - " bbbbbbbbbbbbbbbbbbbbbbbbbb + cccccccccccccccccccccccccc;", - Style); - - Style.PenaltyBreakAssignment = 20; - verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaa = bbbbbbbbbbbbbbbbbbbbbbbbbb +\n" - " cccccccccccccccccccccccccc;", - Style); -} - -TEST_F(FormatTest, AlignsAfterAssignments) { - verifyFormat( - "int Result = aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" - " aaaaaaaaaaaaaaaaaaaaaaaaa;"); - verifyFormat( - "Result += aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" - " aaaaaaaaaaaaaaaaaaaaaaaaa;"); - verifyFormat( - "Result >>= aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" - " aaaaaaaaaaaaaaaaaaaaaaaaa;"); - verifyFormat( - "int Result = (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" - " aaaaaaaaaaaaaaaaaaaaaaaaa);"); - verifyFormat( - "double LooooooooooooooooooooooooongResult = aaaaaaaaaaaaaaaaaaaaaaaa +\n" - " aaaaaaaaaaaaaaaaaaaaaaaa +\n" - " aaaaaaaaaaaaaaaaaaaaaaaa;"); -} - -TEST_F(FormatTest, AlignsAfterReturn) { - verifyFormat( - "return aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" - " aaaaaaaaaaaaaaaaaaaaaaaaa;"); - verifyFormat( - "return (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n" - " aaaaaaaaaaaaaaaaaaaaaaaaa);"); - verifyFormat( - "return aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n" - " aaaaaaaaaaaaaaaaaaaaaa();"); - verifyFormat( - "return (aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n" - " aaaaaaaaaaaaaaaaaaaaaa());"); - verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); - verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) &&\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); - verifyFormat("return\n" - " // true if code is one of a or b.\n" - " code == a || code == b;"); -} - -TEST_F(FormatTest, AlignsAfterOpenBracket) { - verifyFormat( - "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaa aaaaaaaa,\n" - " aaaaaaaaa aaaaaaa) {}"); - verifyFormat( - "SomeLongVariableName->someVeryLongFunctionName(aaaaaaaaaaa aaaaaaaaa,\n" - " aaaaaaaaaaa aaaaaaaaa);"); - verifyFormat( - "SomeLongVariableName->someFunction(foooooooo(aaaaaaaaaaaaaaa,\n" - " aaaaaaaaaaaaaaaaaaaaa));"); - FormatStyle Style = getLLVMStyle(); - Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; - verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" - " aaaaaaaaaaa aaaaaaaa, aaaaaaaaa aaaaaaa) {}", - Style); - verifyFormat("SomeLongVariableName->someVeryLongFunctionName(\n" - " aaaaaaaaaaa aaaaaaaaa, aaaaaaaaaaa aaaaaaaaa);", - Style); - verifyFormat("SomeLongVariableName->someFunction(\n" - " foooooooo(aaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa));", - Style); - verifyFormat( - "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaa aaaaaaaa,\n" - " aaaaaaaaa aaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", - Style); - verifyFormat( - "SomeLongVariableName->someVeryLongFunctionName(aaaaaaaaaaa aaaaaaaaa,\n" - " aaaaaaaaaaa aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", - Style); - verifyFormat( - "SomeLongVariableName->someFunction(foooooooo(aaaaaaaaaaaaaaa,\n" - " aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));", - Style); - - verifyFormat("bbbbbbbbbbbb(aaaaaaaaaaaaaaaaaaaaaaaa, //\n" - " ccccccc(aaaaaaaaaaaaaaaaa, //\n" - " b));", - Style); - - Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; - Style.BinPackArguments = false; - Style.BinPackParameters = false; - verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" - " aaaaaaaaaaa aaaaaaaa,\n" - " aaaaaaaaa aaaaaaa,\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}", - Style); - verifyFormat("SomeLongVariableName->someVeryLongFunctionName(\n" - " aaaaaaaaaaa aaaaaaaaa,\n" - " aaaaaaaaaaa aaaaaaaaa,\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", - Style); - verifyFormat("SomeLongVariableName->someFunction(foooooooo(\n" - " aaaaaaaaaaaaaaa,\n" - " aaaaaaaaaaaaaaaaaaaaa,\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));", - Style); - verifyFormat( - "aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa(\n" - " aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)));", - Style); - verifyFormat( - "aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaa.aaaaaaaaaa(\n" - " aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)));", - Style); - verifyFormat( - "aaaaaaaaaaaaaaaaaaaaaaaa(\n" - " aaaaaaaaaaaaaaaaaaaaa(\n" - " aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)),\n" - " aaaaaaaaaaaaaaaa);", - Style); - verifyFormat( - "aaaaaaaaaaaaaaaaaaaaaaaa(\n" - " aaaaaaaaaaaaaaaaaaaaa(\n" - " aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)) &&\n" - " aaaaaaaaaaaaaaaa);", - Style); -} - -TEST_F(FormatTest, ParenthesesAndOperandAlignment) { - FormatStyle Style = getLLVMStyleWithColumns(40); - verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n" - " bbbbbbbbbbbbbbbbbbbbbb);", - Style); - Style.AlignAfterOpenBracket = FormatStyle::BAS_Align; - Style.AlignOperands = false; - verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n" - " bbbbbbbbbbbbbbbbbbbbbb);", - Style); - Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; - Style.AlignOperands = true; - verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n" - " bbbbbbbbbbbbbbbbbbbbbb);", - Style); - Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; - Style.AlignOperands = false; - verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n" - " bbbbbbbbbbbbbbbbbbbbbb);", - Style); -} - -TEST_F(FormatTest, BreaksConditionalExpressions) { - verifyFormat( - "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa\n" - " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" - " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); - verifyFormat( - "aaaa(aaaaaaaaaa, aaaaaaaa,\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" - " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); - verifyFormat( - "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" - " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); - verifyFormat( - "aaaa(aaaaaaaaa, aaaaaaaaa,\n" - " aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" - " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); - verifyFormat( - "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa)\n" - " : aaaaaaaaaaaaa);"); - verifyFormat( - "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" - " aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" - " : aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" - " aaaaaaaaaaaaa);"); - verifyFormat( - "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" - " aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" - " aaaaaaaaaaaaa);"); - verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" - " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" - " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); - verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" - " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" - " : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaa);"); - verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" - " ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaa);"); - verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" - " ? aaaaaaaaaaaaaaaaaaaaaaaaaaa\n" - " : aaaaaaaaaaaaaaaaaaaaaaaaaaa;"); - verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" - " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" - " : aaaaaaaaaaaaaaaa;"); - verifyFormat( - "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" - " ? aaaaaaaaaaaaaaa\n" - " : aaaaaaaaaaaaaaa;"); - verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n" - " aaaaaaaaa\n" - " ? b\n" - " : c);"); - verifyFormat("return aaaa == bbbb\n" - " // comment\n" - " ? aaaa\n" - " : bbbb;"); - verifyFormat("unsigned Indent =\n" - " format(TheLine.First,\n" - " IndentForLevel[TheLine.Level] >= 0\n" - " ? IndentForLevel[TheLine.Level]\n" - " : TheLine * 2,\n" - " TheLine.InPPDirective, PreviousEndOfLineColumn);", - getLLVMStyleWithColumns(60)); - verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n" - " ? aaaaaaaaaaaaaaa\n" - " : bbbbbbbbbbbbbbb //\n" - " ? ccccccccccccccc\n" - " : ddddddddddddddd;"); - verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n" - " ? aaaaaaaaaaaaaaa\n" - " : (bbbbbbbbbbbbbbb //\n" - " ? ccccccccccccccc\n" - " : ddddddddddddddd);"); - verifyFormat( - "int aaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" - " ? aaaaaaaaaaaaaaaaaaaaaaaaa +\n" - " aaaaaaaaaaaaaaaaaaaaa +\n" - " aaaaaaaaaaaaaaaaaaaaa\n" - " : aaaaaaaaaa;"); - verifyFormat( - "aaaaaa = aaaaaaaaaaaa ? aaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" - " : aaaaaaaaaaaaaaaaaaaaaa\n" - " : aaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); - - FormatStyle NoBinPacking = getLLVMStyle(); - NoBinPacking.BinPackArguments = false; - verifyFormat( - "void f() {\n" - " g(aaa,\n" - " aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" - " ? aaaaaaaaaaaaaaa\n" - " : aaaaaaaaaaaaaaa);\n" - "}", - NoBinPacking); - verifyFormat( - "void f() {\n" - " g(aaa,\n" - " aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" - " ?: aaaaaaaaaaaaaaa);\n" - "}", - NoBinPacking); - - verifyFormat("SomeFunction(aaaaaaaaaaaaaaaaa,\n" - " // comment.\n" - " ccccccccccccccccccccccccccccccccccccccc\n" - " ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" - " : bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);"); - - // Assignments in conditional expressions. Apparently not uncommon :-(. - verifyFormat("return a != b\n" - " // comment\n" - " ? a = b\n" - " : a = b;"); - verifyFormat("return a != b\n" - " // comment\n" - " ? a = a != b\n" - " // comment\n" - " ? a = b\n" - " : a\n" - " : a;\n"); - verifyFormat("return a != b\n" - " // comment\n" - " ? a\n" - " : a = a != b\n" - " // comment\n" - " ? a = b\n" - " : a;"); -} - -TEST_F(FormatTest, BreaksConditionalExpressionsAfterOperator) { - FormatStyle Style = getLLVMStyle(); - Style.BreakBeforeTernaryOperators = false; - Style.ColumnLimit = 70; - verifyFormat( - "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", - Style); - verifyFormat( - "aaaa(aaaaaaaaaa, aaaaaaaa,\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", - Style); - verifyFormat( - "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", - Style); - verifyFormat( - "aaaa(aaaaaaaa, aaaaaaaaaa,\n" - " aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", - Style); - verifyFormat( - "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa) :\n" - " aaaaaaaaaaaaa);", - Style); - verifyFormat( - "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" - " aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" - " aaaaaaaaaaaaa);", - Style); - verifyFormat( - "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n" - " aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" - " aaaaaaaaaaaaa);", - Style); - verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", - Style); - verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaa);", - Style); - verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?:\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaa);", - Style); - verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaa;", - Style); - verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;", - Style); - verifyFormat( - "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" - " aaaaaaaaaaaaaaa :\n" - " aaaaaaaaaaaaaaa;", - Style); - verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n" - " aaaaaaaaa ?\n" - " b :\n" - " c);", - Style); - verifyFormat("unsigned Indent =\n" - " format(TheLine.First,\n" - " IndentForLevel[TheLine.Level] >= 0 ?\n" - " IndentForLevel[TheLine.Level] :\n" - " TheLine * 2,\n" - " TheLine.InPPDirective, PreviousEndOfLineColumn);", - Style); - verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n" - " aaaaaaaaaaaaaaa :\n" - " bbbbbbbbbbbbbbb ? //\n" - " ccccccccccccccc :\n" - " ddddddddddddddd;", - Style); - verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n" - " aaaaaaaaaaaaaaa :\n" - " (bbbbbbbbbbbbbbb ? //\n" - " ccccccccccccccc :\n" - " ddddddddddddddd);", - Style); - verifyFormat("int i = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" - " /*bbbbbbbbbbbbbbb=*/bbbbbbbbbbbbbbbbbbbbbbbbb :\n" - " ccccccccccccccccccccccccccc;", - Style); - verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n" - " aaaaa :\n" - " bbbbbbbbbbbbbbb + cccccccccccccccc;", - Style); -} - -TEST_F(FormatTest, DeclarationsOfMultipleVariables) { - verifyFormat("bool aaaaaaaaaaaaaaaaa = aaaaaa->aaaaaaaaaaaaaaaaa(),\n" - " aaaaaaaaaaa = aaaaaa->aaaaaaaaaaa();"); - verifyFormat("bool a = true, b = false;"); - - verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaa =\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa),\n" - " bbbbbbbbbbbbbbbbbbbbbbbbb =\n" - " bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(bbbbbbbbbbbbbbbb);"); - verifyFormat( - "bool aaaaaaaaaaaaaaaaaaaaa =\n" - " bbbbbbbbbbbbbbbbbbbbbbbbbbbb && cccccccccccccccccccccccccccc,\n" - " d = e && f;"); - verifyFormat("aaaaaaaaa a = aaaaaaaaaaaaaaaaaaaa, b = bbbbbbbbbbbbbbbbbbbb,\n" - " c = cccccccccccccccccccc, d = dddddddddddddddddddd;"); - verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n" - " *c = ccccccccccccccccccc, *d = ddddddddddddddddddd;"); - verifyFormat("aaaaaaaaa ***a = aaaaaaaaaaaaaaaaaaa, ***b = bbbbbbbbbbbbbbb,\n" - " ***c = ccccccccccccccccccc, ***d = ddddddddddddddd;"); - - FormatStyle Style = getGoogleStyle(); - Style.PointerAlignment = FormatStyle::PAS_Left; - Style.DerivePointerAlignment = false; - verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" - " *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaa,\n" - " *b = bbbbbbbbbbbbbbbbbbb;", - Style); - verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n" - " *b = bbbbbbbbbbbbbbbbbbb, *d = ddddddddddddddddddd;", - Style); - verifyFormat("vector a, b;", Style); - verifyFormat("for (int *p, *q; p != q; p = p->next) {\n}", Style); -} - -TEST_F(FormatTest, ConditionalExpressionsInBrackets) { - verifyFormat("arr[foo ? bar : baz];"); - verifyFormat("f()[foo ? bar : baz];"); - verifyFormat("(a + b)[foo ? bar : baz];"); - verifyFormat("arr[foo ? (4 > 5 ? 4 : 5) : 5 < 5 ? 5 : 7];"); -} - -TEST_F(FormatTest, AlignsStringLiterals) { - verifyFormat("loooooooooooooooooooooooooongFunction(\"short literal \"\n" - " \"short literal\");"); - verifyFormat( - "looooooooooooooooooooooooongFunction(\n" - " \"short literal\"\n" - " \"looooooooooooooooooooooooooooooooooooooooooooooooong literal\");"); - verifyFormat("someFunction(\"Always break between multi-line\"\n" - " \" string literals\",\n" - " and, other, parameters);"); - EXPECT_EQ("fun + \"1243\" /* comment */\n" - " \"5678\";", - format("fun + \"1243\" /* comment */\n" - " \"5678\";", - getLLVMStyleWithColumns(28))); - EXPECT_EQ( - "aaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n" - " \"aaaaaaaaaaaaaaaaaaaaa\"\n" - " \"aaaaaaaaaaaaaaaa\";", - format("aaaaaa =" - "\"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa " - "aaaaaaaaaaaaaaaaaaaaa\" " - "\"aaaaaaaaaaaaaaaa\";")); - verifyFormat("a = a + \"a\"\n" - " \"a\"\n" - " \"a\";"); - verifyFormat("f(\"a\", \"b\"\n" - " \"c\");"); - - verifyFormat( - "#define LL_FORMAT \"ll\"\n" - "printf(\"aaaaa: %d, bbbbbb: %\" LL_FORMAT \"d, cccccccc: %\" LL_FORMAT\n" - " \"d, ddddddddd: %\" LL_FORMAT \"d\");"); - - verifyFormat("#define A(X) \\\n" - " \"aaaaa\" #X \"bbbbbb\" \\\n" - " \"ccccc\"", - getLLVMStyleWithColumns(23)); - verifyFormat("#define A \"def\"\n" - "f(\"abc\" A \"ghi\"\n" - " \"jkl\");"); - - verifyFormat("f(L\"a\"\n" - " L\"b\");"); - verifyFormat("#define A(X) \\\n" - " L\"aaaaa\" #X L\"bbbbbb\" \\\n" - " L\"ccccc\"", - getLLVMStyleWithColumns(25)); - - verifyFormat("f(@\"a\"\n" - " @\"b\");"); - verifyFormat("NSString s = @\"a\"\n" - " @\"b\"\n" - " @\"c\";"); - verifyFormat("NSString s = @\"a\"\n" - " \"b\"\n" - " \"c\";"); -} - -TEST_F(FormatTest, ReturnTypeBreakingStyle) { - FormatStyle Style = getLLVMStyle(); - // No declarations or definitions should be moved to own line. - Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_None; - verifyFormat("class A {\n" - " int f() { return 1; }\n" - " int g();\n" - "};\n" - "int f() { return 1; }\n" - "int g();\n", - Style); - - // All declarations and definitions should have the return type moved to its - // own - // line. - Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All; - verifyFormat("class E {\n" - " int\n" - " f() {\n" - " return 1;\n" - " }\n" - " int\n" - " g();\n" - "};\n" - "int\n" - "f() {\n" - " return 1;\n" - "}\n" - "int\n" - "g();\n", - Style); - - // Top-level definitions, and no kinds of declarations should have the - // return type moved to its own line. - Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevelDefinitions; - verifyFormat("class B {\n" - " int f() { return 1; }\n" - " int g();\n" - "};\n" - "int\n" - "f() {\n" - " return 1;\n" - "}\n" - "int g();\n", - Style); - - // Top-level definitions and declarations should have the return type moved - // to its own line. - Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevel; - verifyFormat("class C {\n" - " int f() { return 1; }\n" - " int g();\n" - "};\n" - "int\n" - "f() {\n" - " return 1;\n" - "}\n" - "int\n" - "g();\n", - Style); - - // All definitions should have the return type moved to its own line, but no - // kinds of declarations. - Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_AllDefinitions; - verifyFormat("class D {\n" - " int\n" - " f() {\n" - " return 1;\n" - " }\n" - " int g();\n" - "};\n" - "int\n" - "f() {\n" - " return 1;\n" - "}\n" - "int g();\n", - Style); - verifyFormat("const char *\n" - "f(void) {\n" // Break here. - " return \"\";\n" - "}\n" - "const char *bar(void);\n", // No break here. - Style); - verifyFormat("template \n" - "T *\n" - "f(T &c) {\n" // Break here. - " return NULL;\n" - "}\n" - "template T *f(T &c);\n", // No break here. - Style); - verifyFormat("class C {\n" - " int\n" - " operator+() {\n" - " return 1;\n" - " }\n" - " int\n" - " operator()() {\n" - " return 1;\n" - " }\n" - "};\n", - Style); - verifyFormat("void\n" - "A::operator()() {}\n" - "void\n" - "A::operator>>() {}\n" - "void\n" - "A::operator+() {}\n", - Style); - verifyFormat("void *operator new(std::size_t s);", // No break here. - Style); - verifyFormat("void *\n" - "operator new(std::size_t s) {}", - Style); - verifyFormat("void *\n" - "operator delete[](void *ptr) {}", - Style); - Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup; - verifyFormat("const char *\n" - "f(void)\n" // Break here. - "{\n" - " return \"\";\n" - "}\n" - "const char *bar(void);\n", // No break here. - Style); - verifyFormat("template \n" - "T *\n" // Problem here: no line break - "f(T &c)\n" // Break here. - "{\n" - " return NULL;\n" - "}\n" - "template T *f(T &c);\n", // No break here. - Style); -} - -TEST_F(FormatTest, AlwaysBreakBeforeMultilineStrings) { - FormatStyle NoBreak = getLLVMStyle(); - NoBreak.AlwaysBreakBeforeMultilineStrings = false; - FormatStyle Break = getLLVMStyle(); - Break.AlwaysBreakBeforeMultilineStrings = true; - verifyFormat("aaaa = \"bbbb\"\n" - " \"cccc\";", - NoBreak); - verifyFormat("aaaa =\n" - " \"bbbb\"\n" - " \"cccc\";", - Break); - verifyFormat("aaaa(\"bbbb\"\n" - " \"cccc\");", - NoBreak); - verifyFormat("aaaa(\n" - " \"bbbb\"\n" - " \"cccc\");", - Break); - verifyFormat("aaaa(qqq, \"bbbb\"\n" - " \"cccc\");", - NoBreak); - verifyFormat("aaaa(qqq,\n" - " \"bbbb\"\n" - " \"cccc\");", - Break); - verifyFormat("aaaa(qqq,\n" - " L\"bbbb\"\n" - " L\"cccc\");", - Break); - verifyFormat("aaaaa(aaaaaa, aaaaaaa(\"aaaa\"\n" - " \"bbbb\"));", - Break); - verifyFormat("string s = someFunction(\n" - " \"abc\"\n" - " \"abc\");", - Break); - - // As we break before unary operators, breaking right after them is bad. - verifyFormat("string foo = abc ? \"x\"\n" - " \"blah blah blah blah blah blah\"\n" - " : \"y\";", - Break); - - // Don't break if there is no column gain. - verifyFormat("f(\"aaaa\"\n" - " \"bbbb\");", - Break); - - // Treat literals with escaped newlines like multi-line string literals. - EXPECT_EQ("x = \"a\\\n" - "b\\\n" - "c\";", - format("x = \"a\\\n" - "b\\\n" - "c\";", - NoBreak)); - EXPECT_EQ("xxxx =\n" - " \"a\\\n" - "b\\\n" - "c\";", - format("xxxx = \"a\\\n" - "b\\\n" - "c\";", - Break)); - - EXPECT_EQ("NSString *const kString =\n" - " @\"aaaa\"\n" - " @\"bbbb\";", - format("NSString *const kString = @\"aaaa\"\n" - "@\"bbbb\";", - Break)); - - Break.ColumnLimit = 0; - verifyFormat("const char *hello = \"hello llvm\";", Break); -} - -TEST_F(FormatTest, AlignsPipes) { - verifyFormat( - "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" - " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" - " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); - verifyFormat( - "aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa\n" - " << aaaaaaaaaaaaaaaaaaaa;"); - verifyFormat( - "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" - " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); - verifyFormat( - "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n" - " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); - verifyFormat( - "llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"\n" - " \"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\"\n" - " << \"ccccccccccccccccccccccccccccccccccccccccccccccccc\";"); - verifyFormat( - "aaaaaaaa << (aaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" - " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" - " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); - verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" - " << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;"); - verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaaaaaa: \"\n" - " << aaaaaaaaaaaaaaaaa(aaaaaaaa, aaaaaaaaaaa);"); - verifyFormat( - "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); - verifyFormat( - "auto Diag = diag() << aaaaaaaaaaaaaaaa(aaaaaaaaaaaa, aaaaaaaaaaaaa,\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaa);"); - - verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \"\n" - " << aaaaaaaa.aaaaaaaaaaaa(aaa)->aaaaaaaaaaaaaa();"); - verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" - " aaaaaaaaaaaaaaaaaaaaa)\n" - " << aaaaaaaaaaaaaaaaaaaaaaaaaa;"); - verifyFormat("LOG_IF(aaa == //\n" - " bbb)\n" - " << a << b;"); - - // But sometimes, breaking before the first "<<" is desirable. - verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n" - " << aaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaa);"); - verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbb)\n" - " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" - " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); - verifyFormat("SemaRef.Diag(Loc, diag::note_for_range_begin_end)\n" - " << BEF << IsTemplate << Description << E->getType();"); - verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n" - " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); - verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n" - " << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" - " << aaa;"); - - verifyFormat( - "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" - " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); - - // Incomplete string literal. - EXPECT_EQ("llvm::errs() << \"\n" - " << a;", - format("llvm::errs() << \"\n<cccccc)\n" - " << \"qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\";\n" - "}"); - - // Handle 'endl'. - verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << endl\n" - " << bbbbbbbbbbbbbbbbbbbbbb << endl;"); - verifyFormat("llvm::errs() << endl << bbbbbbbbbbbbbbbbbbbbbb << endl;"); - - // Handle '\n'. - verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << \"\\n\"\n" - " << bbbbbbbbbbbbbbbbbbbbbb << \"\\n\";"); - verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << \'\\n\'\n" - " << bbbbbbbbbbbbbbbbbbbbbb << \'\\n\';"); - verifyFormat("llvm::errs() << aaaa << \"aaaaaaaaaaaaaaaaaa\\n\"\n" - " << bbbb << \"bbbbbbbbbbbbbbbbbb\\n\";"); - verifyFormat("llvm::errs() << \"\\n\" << bbbbbbbbbbbbbbbbbbbbbb << \"\\n\";"); -} - -TEST_F(FormatTest, KeepStringLabelValuePairsOnALine) { - verifyFormat("return out << \"somepacket = {\\n\"\n" - " << \" aaaaaa = \" << pkt.aaaaaa << \"\\n\"\n" - " << \" bbbb = \" << pkt.bbbb << \"\\n\"\n" - " << \" cccccc = \" << pkt.cccccc << \"\\n\"\n" - " << \" ddd = [\" << pkt.ddd << \"]\\n\"\n" - " << \"}\";"); - - verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n" - " << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n" - " << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa;"); - verifyFormat( - "llvm::outs() << \"aaaaaaaaaaaaaaaaa = \" << aaaaaaaaaaaaaaaaa\n" - " << \"bbbbbbbbbbbbbbbbb = \" << bbbbbbbbbbbbbbbbb\n" - " << \"ccccccccccccccccc = \" << ccccccccccccccccc\n" - " << \"ddddddddddddddddd = \" << ddddddddddddddddd\n" - " << \"eeeeeeeeeeeeeeeee = \" << eeeeeeeeeeeeeeeee;"); - verifyFormat("llvm::outs() << aaaaaaaaaaaaaaaaaaaaaaaa << \"=\"\n" - " << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;"); - verifyFormat( - "void f() {\n" - " llvm::outs() << \"aaaaaaaaaaaaaaaaaaaa: \"\n" - " << aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n" - "}"); - - // Breaking before the first "<<" is generally not desirable. - verifyFormat( - "llvm::errs()\n" - " << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" - " << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" - " << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" - " << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;", - getLLVMStyleWithColumns(70)); - verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaa: \"\n" - " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" - " << \"aaaaaaaaaaaaaaaaaaa: \"\n" - " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" - " << \"aaaaaaaaaaaaaaaaaaa: \"\n" - " << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;", - getLLVMStyleWithColumns(70)); - - verifyFormat("string v = \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa +\n" - " \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa +\n" - " \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa;"); - verifyFormat("string v = StrCat(\"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa,\n" - " \"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa,\n" - " \"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa);"); - verifyFormat("string v = \"aaaaaaaaaaaaaaaa: \" +\n" - " (aaaa + aaaa);", - getLLVMStyleWithColumns(40)); - verifyFormat("string v = StrCat(\"aaaaaaaaaaaa: \" +\n" - " (aaaaaaa + aaaaa));", - getLLVMStyleWithColumns(40)); - verifyFormat( - "string v = StrCat(\"aaaaaaaaaaaaaaaaaaaaaaaaaaa: \",\n" - " SomeFunction(aaaaaaaaaaaa, aaaaaaaa.aaaaaaa),\n" - " bbbbbbbbbbbbbbbbbbbbbbb);"); -} - -TEST_F(FormatTest, UnderstandsEquals) { - verifyFormat( - "aaaaaaaaaaaaaaaaa =\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;"); - verifyFormat( - "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}"); - verifyFormat( - "if (a) {\n" - " f();\n" - "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n" - "}"); - - verifyFormat("if (int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n" - " 100000000 + 10000000) {\n}"); -} - -TEST_F(FormatTest, WrapsAtFunctionCallsIfNecessary) { - verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n" - " .looooooooooooooooooooooooooooooooooooooongFunction();"); - - verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n" - " ->looooooooooooooooooooooooooooooooooooooongFunction();"); - - verifyFormat( - "LooooooooooooooooooooooooooooooooongObject->shortFunction(Parameter1,\n" - " Parameter2);"); - - verifyFormat( - "ShortObject->shortFunction(\n" - " LooooooooooooooooooooooooooooooooooooooooooooooongParameter1,\n" - " LooooooooooooooooooooooooooooooooooooooooooooooongParameter2);"); - - verifyFormat("loooooooooooooongFunction(\n" - " LoooooooooooooongObject->looooooooooooooooongFunction());"); - - verifyFormat( - "function(LoooooooooooooooooooooooooooooooooooongObject\n" - " ->loooooooooooooooooooooooooooooooooooooooongFunction());"); - - verifyFormat("EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n" - " .WillRepeatedly(Return(SomeValue));"); - verifyFormat("void f() {\n" - " EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n" - " .Times(2)\n" - " .WillRepeatedly(Return(SomeValue));\n" - "}"); - verifyFormat("SomeMap[std::pair(aaaaaaaaaaaa, bbbbbbbbbbbbbbb)].insert(\n" - " ccccccccccccccccccccccc);"); - verifyFormat("aaaaa(aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" - " .aaaaa(aaaaa),\n" - " aaaaaaaaaaaaaaaaaaaaa);"); - verifyFormat("void f() {\n" - " aaaaaaaaaaaaaaaaaaaaaaaaa(\n" - " aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa)->aaaaaaaaa());\n" - "}"); - verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" - " .aaaaaaaaaaaaaaa(aa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaa));"); - verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" - " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" - " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" - " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()) {\n" - "}"); - - // Here, it is not necessary to wrap at "." or "->". - verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaa) ||\n" - " aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}"); - verifyFormat( - "aaaaaaaaaaa->aaaaaaaaa(\n" - " aaaaaaaaaaaaaaaaaaaaaaaaa,\n" - " aaaaaaaaaaaaaaaaaa->aaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa));\n"); - - verifyFormat( - "aaaaaaaaaaaaaaaaaaaaaaaaa(\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa().aaaaaaaaaaaaaaaaa());"); - verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() *\n" - " aaaaaaaaa()->aaaaaa()->aaaaa());"); - verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() ||\n" - " aaaaaaaaa()->aaaaaa()->aaaaa());"); - - verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" - " .a();"); - - FormatStyle NoBinPacking = getLLVMStyle(); - NoBinPacking.BinPackParameters = false; - verifyFormat("aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n" - " .aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n" - " .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa,\n" - " aaaaaaaaaaaaaaaaaaa,\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);", - NoBinPacking); - - // If there is a subsequent call, change to hanging indentation. - verifyFormat( - "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" - " aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa))\n" - " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); - verifyFormat( - "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" - " aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa));"); - verifyFormat("aaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" - " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();"); - verifyFormat("aaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n" - " .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());"); -} - -TEST_F(FormatTest, WrapsTemplateDeclarations) { - verifyFormat("template \n" - "virtual void loooooooooooongFunction(int Param1, int Param2);"); - verifyFormat("template \n" - "// T should be one of {A, B}.\n" - "virtual void loooooooooooongFunction(int Param1, int Param2);"); - verifyFormat( - "template \n" - "using comment_to_xml_conversion = comment_to_xml_conversion;"); - verifyFormat("template \n" - "void f(int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram1,\n" - " int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram2);"); - verifyFormat( - "template \n" - "void looooooooooooooooooooongFunction(int Paaaaaaaaaaaaaaaaaaaaram1,\n" - " int Paaaaaaaaaaaaaaaaaaaaram2);"); - verifyFormat( - "template \n" - "aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa,\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaa::aaaaaaaaaa,\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); - verifyFormat("template \n" - "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" - " int aaaaaaaaaaaaaaaaaaaaaa);"); - verifyFormat( - "template \n" - "void f();"); - verifyFormat("template class cccccccccccccccccccccc,\n" - " typename ddddddddddddd>\n" - "class C {};"); - verifyFormat( - "aaaaaaaaaaaaaaaaaaaaaaaa(\n" - " aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); - - verifyFormat("void f() {\n" - " a(\n" - " a(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));\n" - "}"); - - verifyFormat("template class C {};"); - verifyFormat("template void f();"); - verifyFormat("template void f() {}"); - verifyFormat( - "aaaaaaaaaaaaa *aaaa =\n" - " new aaaaaaaaaaaaa(\n" - " bbbbbbbbbbbbbbbbbbbbbbbb);", - getLLVMStyleWithColumns(72)); - EXPECT_EQ("static_cast *>(\n" - "\n" - ");", - format("static_cast*>(\n" - "\n" - " );")); - verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" - " const typename aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaa);"); - - FormatStyle AlwaysBreak = getLLVMStyle(); - AlwaysBreak.AlwaysBreakTemplateDeclarations = true; - verifyFormat("template \nclass C {};", AlwaysBreak); - verifyFormat("template \nvoid f();", AlwaysBreak); - verifyFormat("template \nvoid f() {}", AlwaysBreak); - verifyFormat("void aaaaaaaaaaaaaaaaaaa(\n" - " ccccccccccccccccccccccccccccccccccccccccccccccc);"); - verifyFormat("template