diff --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp index b64d48252405..07fdcc83af12 100644 --- a/clang/lib/Format/Format.cpp +++ b/clang/lib/Format/Format.cpp @@ -1,2594 +1,2596 @@ //===--- Format.cpp - Format C++ code -------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// /// /// \file /// This file implements functions declared in Format.h. This will be /// split into separate files as we go. /// //===----------------------------------------------------------------------===// #include "clang/Format/Format.h" #include "AffectedRangeManager.h" #include "ContinuationIndenter.h" #include "FormatInternal.h" #include "FormatTokenLexer.h" #include "NamespaceEndCommentsFixer.h" #include "SortJavaScriptImports.h" #include "TokenAnalyzer.h" #include "TokenAnnotator.h" #include "UnwrappedLineFormatter.h" #include "UnwrappedLineParser.h" #include "UsingDeclarationsSorter.h" #include "WhitespaceManager.h" #include "clang/Basic/Diagnostic.h" #include "clang/Basic/DiagnosticOptions.h" #include "clang/Basic/SourceManager.h" #include "clang/Lex/Lexer.h" #include "clang/Tooling/Inclusions/HeaderIncludes.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/StringRef.h" #include "llvm/Support/Allocator.h" #include "llvm/Support/Debug.h" #include "llvm/Support/Path.h" #include "llvm/Support/Regex.h" #include "llvm/Support/VirtualFileSystem.h" #include "llvm/Support/YAMLTraits.h" #include #include #include #include #include #define DEBUG_TYPE "format-formatter" using clang::format::FormatStyle; LLVM_YAML_IS_SEQUENCE_VECTOR(clang::format::FormatStyle::RawStringFormat) namespace llvm { namespace yaml { template <> struct ScalarEnumerationTraits { static void enumeration(IO &IO, FormatStyle::LanguageKind &Value) { IO.enumCase(Value, "Cpp", FormatStyle::LK_Cpp); IO.enumCase(Value, "Java", FormatStyle::LK_Java); IO.enumCase(Value, "JavaScript", FormatStyle::LK_JavaScript); IO.enumCase(Value, "ObjC", FormatStyle::LK_ObjC); IO.enumCase(Value, "Proto", FormatStyle::LK_Proto); IO.enumCase(Value, "TableGen", FormatStyle::LK_TableGen); IO.enumCase(Value, "TextProto", FormatStyle::LK_TextProto); IO.enumCase(Value, "CSharp", FormatStyle::LK_CSharp); } }; template <> struct ScalarEnumerationTraits { static void enumeration(IO &IO, FormatStyle::LanguageStandard &Value) { IO.enumCase(Value, "Cpp03", FormatStyle::LS_Cpp03); IO.enumCase(Value, "C++03", FormatStyle::LS_Cpp03); IO.enumCase(Value, "Cpp11", FormatStyle::LS_Cpp11); IO.enumCase(Value, "C++11", FormatStyle::LS_Cpp11); IO.enumCase(Value, "Auto", FormatStyle::LS_Auto); } }; template <> struct ScalarEnumerationTraits { static void enumeration(IO &IO, FormatStyle::UseTabStyle &Value) { IO.enumCase(Value, "Never", FormatStyle::UT_Never); IO.enumCase(Value, "false", FormatStyle::UT_Never); IO.enumCase(Value, "Always", FormatStyle::UT_Always); IO.enumCase(Value, "true", FormatStyle::UT_Always); IO.enumCase(Value, "ForIndentation", FormatStyle::UT_ForIndentation); IO.enumCase(Value, "ForContinuationAndIndentation", FormatStyle::UT_ForContinuationAndIndentation); } }; template <> struct ScalarEnumerationTraits { static void enumeration(IO &IO, FormatStyle::JavaScriptQuoteStyle &Value) { IO.enumCase(Value, "Leave", FormatStyle::JSQS_Leave); IO.enumCase(Value, "Single", FormatStyle::JSQS_Single); IO.enumCase(Value, "Double", FormatStyle::JSQS_Double); } }; template <> struct ScalarEnumerationTraits { static void enumeration(IO &IO, FormatStyle::ShortBlockStyle &Value) { IO.enumCase(Value, "Never", FormatStyle::SBS_Never); IO.enumCase(Value, "false", FormatStyle::SBS_Never); IO.enumCase(Value, "Always", FormatStyle::SBS_Always); IO.enumCase(Value, "true", FormatStyle::SBS_Always); IO.enumCase(Value, "Empty", FormatStyle::SBS_Empty); } }; template <> struct ScalarEnumerationTraits { static void enumeration(IO &IO, FormatStyle::ShortFunctionStyle &Value) { IO.enumCase(Value, "None", FormatStyle::SFS_None); IO.enumCase(Value, "false", FormatStyle::SFS_None); IO.enumCase(Value, "All", FormatStyle::SFS_All); IO.enumCase(Value, "true", FormatStyle::SFS_All); IO.enumCase(Value, "Inline", FormatStyle::SFS_Inline); IO.enumCase(Value, "InlineOnly", FormatStyle::SFS_InlineOnly); IO.enumCase(Value, "Empty", FormatStyle::SFS_Empty); } }; template <> struct ScalarEnumerationTraits { static void enumeration(IO &IO, FormatStyle::ShortIfStyle &Value) { IO.enumCase(Value, "Never", FormatStyle::SIS_Never); IO.enumCase(Value, "Always", FormatStyle::SIS_Always); IO.enumCase(Value, "WithoutElse", FormatStyle::SIS_WithoutElse); // For backward compatibility. IO.enumCase(Value, "false", FormatStyle::SIS_Never); IO.enumCase(Value, "true", FormatStyle::SIS_WithoutElse); } }; template <> struct ScalarEnumerationTraits { static void enumeration(IO &IO, FormatStyle::ShortLambdaStyle &Value) { IO.enumCase(Value, "None", FormatStyle::SLS_None); IO.enumCase(Value, "false", FormatStyle::SLS_None); IO.enumCase(Value, "Empty", FormatStyle::SLS_Empty); IO.enumCase(Value, "Inline", FormatStyle::SLS_Inline); IO.enumCase(Value, "All", FormatStyle::SLS_All); IO.enumCase(Value, "true", FormatStyle::SLS_All); } }; template <> struct ScalarEnumerationTraits { static void enumeration(IO &IO, FormatStyle::BinPackStyle &Value) { IO.enumCase(Value, "Auto", FormatStyle::BPS_Auto); IO.enumCase(Value, "Always", FormatStyle::BPS_Always); IO.enumCase(Value, "Never", FormatStyle::BPS_Never); } }; template <> struct ScalarEnumerationTraits { static void enumeration(IO &IO, FormatStyle::BinaryOperatorStyle &Value) { IO.enumCase(Value, "All", FormatStyle::BOS_All); IO.enumCase(Value, "true", FormatStyle::BOS_All); IO.enumCase(Value, "None", FormatStyle::BOS_None); IO.enumCase(Value, "false", FormatStyle::BOS_None); IO.enumCase(Value, "NonAssignment", FormatStyle::BOS_NonAssignment); } }; template <> struct ScalarEnumerationTraits { static void enumeration(IO &IO, FormatStyle::BraceBreakingStyle &Value) { IO.enumCase(Value, "Attach", FormatStyle::BS_Attach); IO.enumCase(Value, "Linux", FormatStyle::BS_Linux); IO.enumCase(Value, "Mozilla", FormatStyle::BS_Mozilla); IO.enumCase(Value, "Stroustrup", FormatStyle::BS_Stroustrup); IO.enumCase(Value, "Allman", FormatStyle::BS_Allman); IO.enumCase(Value, "Whitesmiths", FormatStyle::BS_Whitesmiths); IO.enumCase(Value, "GNU", FormatStyle::BS_GNU); IO.enumCase(Value, "WebKit", FormatStyle::BS_WebKit); IO.enumCase(Value, "Custom", FormatStyle::BS_Custom); } }; template <> struct ScalarEnumerationTraits { static void enumeration(IO &IO, FormatStyle::BreakConstructorInitializersStyle &Value) { IO.enumCase(Value, "BeforeColon", FormatStyle::BCIS_BeforeColon); IO.enumCase(Value, "BeforeComma", FormatStyle::BCIS_BeforeComma); IO.enumCase(Value, "AfterColon", FormatStyle::BCIS_AfterColon); } }; template <> struct ScalarEnumerationTraits { static void enumeration(IO &IO, FormatStyle::BreakInheritanceListStyle &Value) { IO.enumCase(Value, "BeforeColon", FormatStyle::BILS_BeforeColon); IO.enumCase(Value, "BeforeComma", FormatStyle::BILS_BeforeComma); IO.enumCase(Value, "AfterColon", FormatStyle::BILS_AfterColon); } }; template <> struct ScalarEnumerationTraits { static void enumeration(IO &IO, FormatStyle::PPDirectiveIndentStyle &Value) { IO.enumCase(Value, "None", FormatStyle::PPDIS_None); IO.enumCase(Value, "AfterHash", FormatStyle::PPDIS_AfterHash); IO.enumCase(Value, "BeforeHash", FormatStyle::PPDIS_BeforeHash); } }; template <> struct ScalarEnumerationTraits { static void enumeration(IO &IO, FormatStyle::ReturnTypeBreakingStyle &Value) { IO.enumCase(Value, "None", FormatStyle::RTBS_None); IO.enumCase(Value, "All", FormatStyle::RTBS_All); IO.enumCase(Value, "TopLevel", FormatStyle::RTBS_TopLevel); IO.enumCase(Value, "TopLevelDefinitions", FormatStyle::RTBS_TopLevelDefinitions); IO.enumCase(Value, "AllDefinitions", FormatStyle::RTBS_AllDefinitions); } }; template <> struct ScalarEnumerationTraits { static void enumeration(IO &IO, FormatStyle::BreakTemplateDeclarationsStyle &Value) { IO.enumCase(Value, "No", FormatStyle::BTDS_No); IO.enumCase(Value, "MultiLine", FormatStyle::BTDS_MultiLine); IO.enumCase(Value, "Yes", FormatStyle::BTDS_Yes); // For backward compatibility. IO.enumCase(Value, "false", FormatStyle::BTDS_MultiLine); IO.enumCase(Value, "true", FormatStyle::BTDS_Yes); } }; template <> struct ScalarEnumerationTraits { static void enumeration(IO &IO, FormatStyle::DefinitionReturnTypeBreakingStyle &Value) { IO.enumCase(Value, "None", FormatStyle::DRTBS_None); IO.enumCase(Value, "All", FormatStyle::DRTBS_All); IO.enumCase(Value, "TopLevel", FormatStyle::DRTBS_TopLevel); // For backward compatibility. IO.enumCase(Value, "false", FormatStyle::DRTBS_None); IO.enumCase(Value, "true", FormatStyle::DRTBS_All); } }; template <> struct ScalarEnumerationTraits { static void enumeration(IO &IO, FormatStyle::NamespaceIndentationKind &Value) { IO.enumCase(Value, "None", FormatStyle::NI_None); IO.enumCase(Value, "Inner", FormatStyle::NI_Inner); IO.enumCase(Value, "All", FormatStyle::NI_All); } }; template <> struct ScalarEnumerationTraits { static void enumeration(IO &IO, FormatStyle::BracketAlignmentStyle &Value) { IO.enumCase(Value, "Align", FormatStyle::BAS_Align); IO.enumCase(Value, "DontAlign", FormatStyle::BAS_DontAlign); IO.enumCase(Value, "AlwaysBreak", FormatStyle::BAS_AlwaysBreak); // For backward compatibility. IO.enumCase(Value, "true", FormatStyle::BAS_Align); IO.enumCase(Value, "false", FormatStyle::BAS_DontAlign); } }; template <> struct ScalarEnumerationTraits { static void enumeration(IO &IO, FormatStyle::EscapedNewlineAlignmentStyle &Value) { IO.enumCase(Value, "DontAlign", FormatStyle::ENAS_DontAlign); IO.enumCase(Value, "Left", FormatStyle::ENAS_Left); IO.enumCase(Value, "Right", FormatStyle::ENAS_Right); // For backward compatibility. IO.enumCase(Value, "true", FormatStyle::ENAS_Left); IO.enumCase(Value, "false", FormatStyle::ENAS_Right); } }; template <> struct ScalarEnumerationTraits { static void enumeration(IO &IO, FormatStyle::PointerAlignmentStyle &Value) { IO.enumCase(Value, "Middle", FormatStyle::PAS_Middle); IO.enumCase(Value, "Left", FormatStyle::PAS_Left); IO.enumCase(Value, "Right", FormatStyle::PAS_Right); // For backward compatibility. IO.enumCase(Value, "true", FormatStyle::PAS_Left); IO.enumCase(Value, "false", FormatStyle::PAS_Right); } }; template <> struct ScalarEnumerationTraits { static void enumeration(IO &IO, FormatStyle::SpaceBeforeParensOptions &Value) { IO.enumCase(Value, "Never", FormatStyle::SBPO_Never); IO.enumCase(Value, "ControlStatements", FormatStyle::SBPO_ControlStatements); IO.enumCase(Value, "NonEmptyParentheses", FormatStyle::SBPO_NonEmptyParentheses); IO.enumCase(Value, "Always", FormatStyle::SBPO_Always); // For backward compatibility. IO.enumCase(Value, "false", FormatStyle::SBPO_Never); IO.enumCase(Value, "true", FormatStyle::SBPO_ControlStatements); } }; template <> struct MappingTraits { static void mapping(IO &IO, FormatStyle &Style) { // When reading, read the language first, we need it for getPredefinedStyle. IO.mapOptional("Language", Style.Language); if (IO.outputting()) { StringRef StylesArray[] = {"LLVM", "Google", "Chromium", "Mozilla", "WebKit", "GNU", "Microsoft"}; ArrayRef Styles(StylesArray); for (size_t i = 0, e = Styles.size(); i < e; ++i) { StringRef StyleName(Styles[i]); FormatStyle PredefinedStyle; if (getPredefinedStyle(StyleName, Style.Language, &PredefinedStyle) && Style == PredefinedStyle) { IO.mapOptional("# BasedOnStyle", StyleName); break; } } } else { StringRef BasedOnStyle; IO.mapOptional("BasedOnStyle", BasedOnStyle); if (!BasedOnStyle.empty()) { FormatStyle::LanguageKind OldLanguage = Style.Language; FormatStyle::LanguageKind Language = ((FormatStyle *)IO.getContext())->Language; if (!getPredefinedStyle(BasedOnStyle, Language, &Style)) { IO.setError(Twine("Unknown value for BasedOnStyle: ", BasedOnStyle)); return; } Style.Language = OldLanguage; } } // For backward compatibility. if (!IO.outputting()) { IO.mapOptional("AlignEscapedNewlinesLeft", Style.AlignEscapedNewlines); IO.mapOptional("DerivePointerBinding", Style.DerivePointerAlignment); IO.mapOptional("IndentFunctionDeclarationAfterType", Style.IndentWrappedFunctionNames); IO.mapOptional("PointerBindsToType", Style.PointerAlignment); IO.mapOptional("SpaceAfterControlStatementKeyword", Style.SpaceBeforeParens); } IO.mapOptional("AccessModifierOffset", Style.AccessModifierOffset); IO.mapOptional("AlignAfterOpenBracket", Style.AlignAfterOpenBracket); IO.mapOptional("AlignConsecutiveMacros", Style.AlignConsecutiveMacros); IO.mapOptional("AlignConsecutiveAssignments", Style.AlignConsecutiveAssignments); IO.mapOptional("AlignConsecutiveDeclarations", Style.AlignConsecutiveDeclarations); IO.mapOptional("AlignEscapedNewlines", Style.AlignEscapedNewlines); IO.mapOptional("AlignOperands", Style.AlignOperands); IO.mapOptional("AlignTrailingComments", Style.AlignTrailingComments); IO.mapOptional("AllowAllArgumentsOnNextLine", Style.AllowAllArgumentsOnNextLine); IO.mapOptional("AllowAllConstructorInitializersOnNextLine", Style.AllowAllConstructorInitializersOnNextLine); IO.mapOptional("AllowAllParametersOfDeclarationOnNextLine", Style.AllowAllParametersOfDeclarationOnNextLine); IO.mapOptional("AllowShortBlocksOnASingleLine", Style.AllowShortBlocksOnASingleLine); IO.mapOptional("AllowShortCaseLabelsOnASingleLine", Style.AllowShortCaseLabelsOnASingleLine); IO.mapOptional("AllowShortFunctionsOnASingleLine", Style.AllowShortFunctionsOnASingleLine); IO.mapOptional("AllowShortLambdasOnASingleLine", Style.AllowShortLambdasOnASingleLine); IO.mapOptional("AllowShortIfStatementsOnASingleLine", Style.AllowShortIfStatementsOnASingleLine); IO.mapOptional("AllowShortLoopsOnASingleLine", Style.AllowShortLoopsOnASingleLine); IO.mapOptional("AlwaysBreakAfterDefinitionReturnType", Style.AlwaysBreakAfterDefinitionReturnType); IO.mapOptional("AlwaysBreakAfterReturnType", Style.AlwaysBreakAfterReturnType); // If AlwaysBreakAfterDefinitionReturnType was specified but // AlwaysBreakAfterReturnType was not, initialize the latter from the // former for backwards compatibility. if (Style.AlwaysBreakAfterDefinitionReturnType != FormatStyle::DRTBS_None && Style.AlwaysBreakAfterReturnType == FormatStyle::RTBS_None) { if (Style.AlwaysBreakAfterDefinitionReturnType == FormatStyle::DRTBS_All) Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_AllDefinitions; else if (Style.AlwaysBreakAfterDefinitionReturnType == FormatStyle::DRTBS_TopLevel) Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevelDefinitions; } IO.mapOptional("AlwaysBreakBeforeMultilineStrings", Style.AlwaysBreakBeforeMultilineStrings); IO.mapOptional("AlwaysBreakTemplateDeclarations", Style.AlwaysBreakTemplateDeclarations); IO.mapOptional("BinPackArguments", Style.BinPackArguments); IO.mapOptional("BinPackParameters", Style.BinPackParameters); IO.mapOptional("BraceWrapping", Style.BraceWrapping); IO.mapOptional("BreakBeforeBinaryOperators", Style.BreakBeforeBinaryOperators); IO.mapOptional("BreakBeforeBraces", Style.BreakBeforeBraces); bool BreakBeforeInheritanceComma = false; IO.mapOptional("BreakBeforeInheritanceComma", BreakBeforeInheritanceComma); IO.mapOptional("BreakInheritanceList", Style.BreakInheritanceList); // If BreakBeforeInheritanceComma was specified but // BreakInheritance was not, initialize the latter from the // former for backwards compatibility. if (BreakBeforeInheritanceComma && Style.BreakInheritanceList == FormatStyle::BILS_BeforeColon) Style.BreakInheritanceList = FormatStyle::BILS_BeforeComma; IO.mapOptional("BreakBeforeTernaryOperators", Style.BreakBeforeTernaryOperators); bool BreakConstructorInitializersBeforeComma = false; IO.mapOptional("BreakConstructorInitializersBeforeComma", BreakConstructorInitializersBeforeComma); IO.mapOptional("BreakConstructorInitializers", Style.BreakConstructorInitializers); // If BreakConstructorInitializersBeforeComma was specified but // BreakConstructorInitializers was not, initialize the latter from the // former for backwards compatibility. if (BreakConstructorInitializersBeforeComma && Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeColon) Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; IO.mapOptional("BreakAfterJavaFieldAnnotations", Style.BreakAfterJavaFieldAnnotations); IO.mapOptional("BreakStringLiterals", Style.BreakStringLiterals); IO.mapOptional("ColumnLimit", Style.ColumnLimit); IO.mapOptional("CommentPragmas", Style.CommentPragmas); IO.mapOptional("CompactNamespaces", Style.CompactNamespaces); IO.mapOptional("ConstructorInitializerAllOnOneLineOrOnePerLine", Style.ConstructorInitializerAllOnOneLineOrOnePerLine); IO.mapOptional("ConstructorInitializerIndentWidth", Style.ConstructorInitializerIndentWidth); IO.mapOptional("ContinuationIndentWidth", Style.ContinuationIndentWidth); IO.mapOptional("Cpp11BracedListStyle", Style.Cpp11BracedListStyle); IO.mapOptional("DerivePointerAlignment", Style.DerivePointerAlignment); IO.mapOptional("DisableFormat", Style.DisableFormat); IO.mapOptional("ExperimentalAutoDetectBinPacking", Style.ExperimentalAutoDetectBinPacking); IO.mapOptional("FixNamespaceComments", Style.FixNamespaceComments); IO.mapOptional("ForEachMacros", Style.ForEachMacros); IO.mapOptional("IncludeBlocks", Style.IncludeStyle.IncludeBlocks); IO.mapOptional("IncludeCategories", Style.IncludeStyle.IncludeCategories); IO.mapOptional("IncludeIsMainRegex", Style.IncludeStyle.IncludeIsMainRegex); IO.mapOptional("IndentCaseLabels", Style.IndentCaseLabels); IO.mapOptional("IndentGotoLabels", Style.IndentGotoLabels); IO.mapOptional("IndentPPDirectives", Style.IndentPPDirectives); IO.mapOptional("IndentWidth", Style.IndentWidth); IO.mapOptional("IndentWrappedFunctionNames", Style.IndentWrappedFunctionNames); IO.mapOptional("JavaImportGroups", Style.JavaImportGroups); IO.mapOptional("JavaScriptQuotes", Style.JavaScriptQuotes); IO.mapOptional("JavaScriptWrapImports", Style.JavaScriptWrapImports); IO.mapOptional("KeepEmptyLinesAtTheStartOfBlocks", Style.KeepEmptyLinesAtTheStartOfBlocks); IO.mapOptional("MacroBlockBegin", Style.MacroBlockBegin); IO.mapOptional("MacroBlockEnd", Style.MacroBlockEnd); IO.mapOptional("MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep); IO.mapOptional("NamespaceIndentation", Style.NamespaceIndentation); IO.mapOptional("NamespaceMacros", Style.NamespaceMacros); IO.mapOptional("ObjCBinPackProtocolList", Style.ObjCBinPackProtocolList); IO.mapOptional("ObjCBlockIndentWidth", Style.ObjCBlockIndentWidth); IO.mapOptional("ObjCSpaceAfterProperty", Style.ObjCSpaceAfterProperty); IO.mapOptional("ObjCSpaceBeforeProtocolList", Style.ObjCSpaceBeforeProtocolList); IO.mapOptional("PenaltyBreakAssignment", Style.PenaltyBreakAssignment); IO.mapOptional("PenaltyBreakBeforeFirstCallParameter", Style.PenaltyBreakBeforeFirstCallParameter); IO.mapOptional("PenaltyBreakComment", Style.PenaltyBreakComment); IO.mapOptional("PenaltyBreakFirstLessLess", Style.PenaltyBreakFirstLessLess); IO.mapOptional("PenaltyBreakString", Style.PenaltyBreakString); IO.mapOptional("PenaltyBreakTemplateDeclaration", Style.PenaltyBreakTemplateDeclaration); IO.mapOptional("PenaltyExcessCharacter", Style.PenaltyExcessCharacter); IO.mapOptional("PenaltyReturnTypeOnItsOwnLine", Style.PenaltyReturnTypeOnItsOwnLine); IO.mapOptional("PointerAlignment", Style.PointerAlignment); IO.mapOptional("RawStringFormats", Style.RawStringFormats); IO.mapOptional("ReflowComments", Style.ReflowComments); IO.mapOptional("SortIncludes", Style.SortIncludes); IO.mapOptional("SortUsingDeclarations", Style.SortUsingDeclarations); IO.mapOptional("SpaceAfterCStyleCast", Style.SpaceAfterCStyleCast); IO.mapOptional("SpaceAfterLogicalNot", Style.SpaceAfterLogicalNot); IO.mapOptional("SpaceAfterTemplateKeyword", Style.SpaceAfterTemplateKeyword); IO.mapOptional("SpaceBeforeAssignmentOperators", Style.SpaceBeforeAssignmentOperators); IO.mapOptional("SpaceBeforeCpp11BracedList", Style.SpaceBeforeCpp11BracedList); IO.mapOptional("SpaceBeforeCtorInitializerColon", Style.SpaceBeforeCtorInitializerColon); IO.mapOptional("SpaceBeforeInheritanceColon", Style.SpaceBeforeInheritanceColon); IO.mapOptional("SpaceBeforeParens", Style.SpaceBeforeParens); IO.mapOptional("SpaceBeforeRangeBasedForLoopColon", Style.SpaceBeforeRangeBasedForLoopColon); IO.mapOptional("SpaceInEmptyBlock", Style.SpaceInEmptyBlock); IO.mapOptional("SpaceInEmptyParentheses", Style.SpaceInEmptyParentheses); IO.mapOptional("SpacesBeforeTrailingComments", Style.SpacesBeforeTrailingComments); IO.mapOptional("SpacesInAngles", Style.SpacesInAngles); IO.mapOptional("SpacesInContainerLiterals", Style.SpacesInContainerLiterals); IO.mapOptional("SpacesInCStyleCastParentheses", Style.SpacesInCStyleCastParentheses); IO.mapOptional("SpacesInParentheses", Style.SpacesInParentheses); IO.mapOptional("SpacesInSquareBrackets", Style.SpacesInSquareBrackets); IO.mapOptional("Standard", Style.Standard); IO.mapOptional("StatementMacros", Style.StatementMacros); IO.mapOptional("TabWidth", Style.TabWidth); IO.mapOptional("TypenameMacros", Style.TypenameMacros); IO.mapOptional("UseTab", Style.UseTab); } }; template <> struct MappingTraits { static void mapping(IO &IO, FormatStyle::BraceWrappingFlags &Wrapping) { IO.mapOptional("AfterCaseLabel", Wrapping.AfterCaseLabel); IO.mapOptional("AfterClass", Wrapping.AfterClass); IO.mapOptional("AfterControlStatement", Wrapping.AfterControlStatement); IO.mapOptional("AfterEnum", Wrapping.AfterEnum); IO.mapOptional("AfterFunction", Wrapping.AfterFunction); IO.mapOptional("AfterNamespace", Wrapping.AfterNamespace); IO.mapOptional("AfterObjCDeclaration", Wrapping.AfterObjCDeclaration); IO.mapOptional("AfterStruct", Wrapping.AfterStruct); IO.mapOptional("AfterUnion", Wrapping.AfterUnion); IO.mapOptional("AfterExternBlock", Wrapping.AfterExternBlock); IO.mapOptional("BeforeCatch", Wrapping.BeforeCatch); IO.mapOptional("BeforeElse", Wrapping.BeforeElse); IO.mapOptional("IndentBraces", Wrapping.IndentBraces); IO.mapOptional("SplitEmptyFunction", Wrapping.SplitEmptyFunction); IO.mapOptional("SplitEmptyRecord", Wrapping.SplitEmptyRecord); IO.mapOptional("SplitEmptyNamespace", Wrapping.SplitEmptyNamespace); } }; template <> struct MappingTraits { static void mapping(IO &IO, FormatStyle::RawStringFormat &Format) { IO.mapOptional("Language", Format.Language); IO.mapOptional("Delimiters", Format.Delimiters); IO.mapOptional("EnclosingFunctions", Format.EnclosingFunctions); IO.mapOptional("CanonicalDelimiter", Format.CanonicalDelimiter); IO.mapOptional("BasedOnStyle", Format.BasedOnStyle); } }; // Allows to read vector while keeping default values. // IO.getContext() should contain a pointer to the FormatStyle structure, that // will be used to get default values for missing keys. // If the first element has no Language specified, it will be treated as the // default one for the following elements. template <> struct DocumentListTraits> { static size_t size(IO &IO, std::vector &Seq) { return Seq.size(); } static FormatStyle &element(IO &IO, std::vector &Seq, size_t Index) { if (Index >= Seq.size()) { assert(Index == Seq.size()); FormatStyle Template; if (!Seq.empty() && Seq[0].Language == FormatStyle::LK_None) { Template = Seq[0]; } else { Template = *((const FormatStyle *)IO.getContext()); Template.Language = FormatStyle::LK_None; } Seq.resize(Index + 1, Template); } return Seq[Index]; } }; } // namespace yaml } // namespace llvm namespace clang { namespace format { const std::error_category &getParseCategory() { static const ParseErrorCategory C{}; return C; } std::error_code make_error_code(ParseError e) { return std::error_code(static_cast(e), getParseCategory()); } inline llvm::Error make_string_error(const llvm::Twine &Message) { return llvm::make_error(Message, llvm::inconvertibleErrorCode()); } const char *ParseErrorCategory::name() const noexcept { return "clang-format.parse_error"; } std::string ParseErrorCategory::message(int EV) const { switch (static_cast(EV)) { case ParseError::Success: return "Success"; case ParseError::Error: return "Invalid argument"; case ParseError::Unsuitable: return "Unsuitable"; } llvm_unreachable("unexpected parse error"); } static FormatStyle expandPresets(const FormatStyle &Style) { if (Style.BreakBeforeBraces == FormatStyle::BS_Custom) return Style; FormatStyle Expanded = Style; Expanded.BraceWrapping = {false, false, false, false, false, false, false, false, false, false, false, false, false, true, true, true}; switch (Style.BreakBeforeBraces) { case FormatStyle::BS_Linux: Expanded.BraceWrapping.AfterClass = true; Expanded.BraceWrapping.AfterFunction = true; Expanded.BraceWrapping.AfterNamespace = true; break; case FormatStyle::BS_Mozilla: Expanded.BraceWrapping.AfterClass = true; Expanded.BraceWrapping.AfterEnum = true; Expanded.BraceWrapping.AfterFunction = true; Expanded.BraceWrapping.AfterStruct = true; Expanded.BraceWrapping.AfterUnion = true; Expanded.BraceWrapping.AfterExternBlock = true; Expanded.BraceWrapping.SplitEmptyFunction = true; Expanded.BraceWrapping.SplitEmptyRecord = false; break; case FormatStyle::BS_Stroustrup: Expanded.BraceWrapping.AfterFunction = true; Expanded.BraceWrapping.BeforeCatch = true; Expanded.BraceWrapping.BeforeElse = true; break; case FormatStyle::BS_Allman: Expanded.BraceWrapping.AfterCaseLabel = true; Expanded.BraceWrapping.AfterClass = true; Expanded.BraceWrapping.AfterControlStatement = true; Expanded.BraceWrapping.AfterEnum = true; Expanded.BraceWrapping.AfterFunction = true; Expanded.BraceWrapping.AfterNamespace = true; Expanded.BraceWrapping.AfterObjCDeclaration = true; Expanded.BraceWrapping.AfterStruct = true; Expanded.BraceWrapping.AfterUnion = true; Expanded.BraceWrapping.AfterExternBlock = true; Expanded.BraceWrapping.BeforeCatch = true; Expanded.BraceWrapping.BeforeElse = true; break; case FormatStyle::BS_Whitesmiths: Expanded.BraceWrapping.AfterCaseLabel = true; Expanded.BraceWrapping.AfterClass = true; Expanded.BraceWrapping.AfterControlStatement = true; Expanded.BraceWrapping.AfterEnum = true; Expanded.BraceWrapping.AfterFunction = true; Expanded.BraceWrapping.AfterNamespace = true; Expanded.BraceWrapping.AfterObjCDeclaration = true; Expanded.BraceWrapping.AfterStruct = true; Expanded.BraceWrapping.AfterExternBlock = true; Expanded.BraceWrapping.BeforeCatch = true; Expanded.BraceWrapping.BeforeElse = true; break; case FormatStyle::BS_GNU: Expanded.BraceWrapping = {true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true}; break; case FormatStyle::BS_WebKit: Expanded.BraceWrapping.AfterFunction = true; break; default: break; } return Expanded; } FormatStyle getLLVMStyle(FormatStyle::LanguageKind Language) { FormatStyle LLVMStyle; LLVMStyle.Language = Language; LLVMStyle.AccessModifierOffset = -2; LLVMStyle.AlignEscapedNewlines = FormatStyle::ENAS_Right; LLVMStyle.AlignAfterOpenBracket = FormatStyle::BAS_Align; LLVMStyle.AlignOperands = true; LLVMStyle.AlignTrailingComments = true; LLVMStyle.AlignConsecutiveAssignments = false; LLVMStyle.AlignConsecutiveDeclarations = false; LLVMStyle.AlignConsecutiveMacros = false; LLVMStyle.AllowAllArgumentsOnNextLine = true; LLVMStyle.AllowAllConstructorInitializersOnNextLine = true; LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true; LLVMStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All; LLVMStyle.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never; LLVMStyle.AllowShortCaseLabelsOnASingleLine = false; LLVMStyle.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Never; LLVMStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_All; LLVMStyle.AllowShortLoopsOnASingleLine = false; LLVMStyle.AlwaysBreakAfterReturnType = FormatStyle::RTBS_None; LLVMStyle.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_None; LLVMStyle.AlwaysBreakBeforeMultilineStrings = false; LLVMStyle.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_MultiLine; LLVMStyle.BinPackArguments = true; LLVMStyle.BinPackParameters = true; LLVMStyle.BreakBeforeBinaryOperators = FormatStyle::BOS_None; LLVMStyle.BreakBeforeTernaryOperators = true; LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach; LLVMStyle.BraceWrapping = {false, false, false, false, false, false, false, false, false, false, false, false, false, true, true, true}; LLVMStyle.BreakAfterJavaFieldAnnotations = false; LLVMStyle.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon; LLVMStyle.BreakInheritanceList = FormatStyle::BILS_BeforeColon; LLVMStyle.BreakStringLiterals = true; LLVMStyle.ColumnLimit = 80; LLVMStyle.CommentPragmas = "^ IWYU pragma:"; LLVMStyle.CompactNamespaces = false; LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false; LLVMStyle.ConstructorInitializerIndentWidth = 4; LLVMStyle.ContinuationIndentWidth = 4; LLVMStyle.Cpp11BracedListStyle = true; LLVMStyle.DerivePointerAlignment = false; LLVMStyle.ExperimentalAutoDetectBinPacking = false; LLVMStyle.FixNamespaceComments = true; LLVMStyle.ForEachMacros.push_back("foreach"); LLVMStyle.ForEachMacros.push_back("Q_FOREACH"); LLVMStyle.ForEachMacros.push_back("BOOST_FOREACH"); LLVMStyle.IncludeStyle.IncludeCategories = { - {"^\"(llvm|llvm-c|clang|clang-c)/", 2}, - {"^(<|\"(gtest|gmock|isl|json)/)", 3}, - {".*", 1}}; + {"^\"(llvm|llvm-c|clang|clang-c)/", 2, 0}, + {"^(<|\"(gtest|gmock|isl|json)/)", 3, 0}, + {".*", 1, 0}}; LLVMStyle.IncludeStyle.IncludeIsMainRegex = "(Test)?$"; LLVMStyle.IncludeStyle.IncludeBlocks = tooling::IncludeStyle::IBS_Preserve; LLVMStyle.IndentCaseLabels = false; LLVMStyle.IndentGotoLabels = true; LLVMStyle.IndentPPDirectives = FormatStyle::PPDIS_None; LLVMStyle.IndentWrappedFunctionNames = false; LLVMStyle.IndentWidth = 2; LLVMStyle.JavaScriptQuotes = FormatStyle::JSQS_Leave; LLVMStyle.JavaScriptWrapImports = true; LLVMStyle.TabWidth = 8; LLVMStyle.MaxEmptyLinesToKeep = 1; LLVMStyle.KeepEmptyLinesAtTheStartOfBlocks = true; LLVMStyle.NamespaceIndentation = FormatStyle::NI_None; LLVMStyle.ObjCBinPackProtocolList = FormatStyle::BPS_Auto; LLVMStyle.ObjCBlockIndentWidth = 2; LLVMStyle.ObjCSpaceAfterProperty = false; LLVMStyle.ObjCSpaceBeforeProtocolList = true; LLVMStyle.PointerAlignment = FormatStyle::PAS_Right; LLVMStyle.SpacesBeforeTrailingComments = 1; LLVMStyle.Standard = FormatStyle::LS_Cpp11; LLVMStyle.UseTab = FormatStyle::UT_Never; LLVMStyle.ReflowComments = true; LLVMStyle.SpacesInParentheses = false; LLVMStyle.SpacesInSquareBrackets = false; LLVMStyle.SpaceInEmptyBlock = false; LLVMStyle.SpaceInEmptyParentheses = false; LLVMStyle.SpacesInContainerLiterals = true; LLVMStyle.SpacesInCStyleCastParentheses = false; LLVMStyle.SpaceAfterCStyleCast = false; LLVMStyle.SpaceAfterLogicalNot = false; LLVMStyle.SpaceAfterTemplateKeyword = true; LLVMStyle.SpaceBeforeCtorInitializerColon = true; LLVMStyle.SpaceBeforeInheritanceColon = true; LLVMStyle.SpaceBeforeParens = FormatStyle::SBPO_ControlStatements; LLVMStyle.SpaceBeforeRangeBasedForLoopColon = true; LLVMStyle.SpaceBeforeAssignmentOperators = true; LLVMStyle.SpaceBeforeCpp11BracedList = false; LLVMStyle.SpacesInAngles = false; LLVMStyle.PenaltyBreakAssignment = prec::Assignment; LLVMStyle.PenaltyBreakComment = 300; LLVMStyle.PenaltyBreakFirstLessLess = 120; LLVMStyle.PenaltyBreakString = 1000; LLVMStyle.PenaltyExcessCharacter = 1000000; LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 60; LLVMStyle.PenaltyBreakBeforeFirstCallParameter = 19; LLVMStyle.PenaltyBreakTemplateDeclaration = prec::Relational; LLVMStyle.DisableFormat = false; LLVMStyle.SortIncludes = true; LLVMStyle.SortUsingDeclarations = true; LLVMStyle.StatementMacros.push_back("Q_UNUSED"); LLVMStyle.StatementMacros.push_back("QT_REQUIRE_VERSION"); // Defaults that differ when not C++. if (Language == FormatStyle::LK_TableGen) { LLVMStyle.SpacesInContainerLiterals = false; } return LLVMStyle; } FormatStyle getGoogleStyle(FormatStyle::LanguageKind Language) { if (Language == FormatStyle::LK_TextProto) { FormatStyle GoogleStyle = getGoogleStyle(FormatStyle::LK_Proto); GoogleStyle.Language = FormatStyle::LK_TextProto; return GoogleStyle; } FormatStyle GoogleStyle = getLLVMStyle(Language); GoogleStyle.AccessModifierOffset = -1; GoogleStyle.AlignEscapedNewlines = FormatStyle::ENAS_Left; GoogleStyle.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_WithoutElse; GoogleStyle.AllowShortLoopsOnASingleLine = true; GoogleStyle.AlwaysBreakBeforeMultilineStrings = true; GoogleStyle.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes; GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true; GoogleStyle.DerivePointerAlignment = true; - GoogleStyle.IncludeStyle.IncludeCategories = { - {"^", 2}, {"^<.*\\.h>", 1}, {"^<.*", 2}, {".*", 3}}; + GoogleStyle.IncludeStyle.IncludeCategories = {{"^", 2, 0}, + {"^<.*\\.h>", 1, 0}, + {"^<.*", 2, 0}, + {".*", 3, 0}}; GoogleStyle.IncludeStyle.IncludeIsMainRegex = "([-_](test|unittest))?$"; GoogleStyle.IncludeStyle.IncludeBlocks = tooling::IncludeStyle::IBS_Regroup; GoogleStyle.IndentCaseLabels = true; GoogleStyle.KeepEmptyLinesAtTheStartOfBlocks = false; GoogleStyle.ObjCBinPackProtocolList = FormatStyle::BPS_Never; GoogleStyle.ObjCSpaceAfterProperty = false; GoogleStyle.ObjCSpaceBeforeProtocolList = true; GoogleStyle.PointerAlignment = FormatStyle::PAS_Left; GoogleStyle.RawStringFormats = { { FormatStyle::LK_Cpp, /*Delimiters=*/ { "cc", "CC", "cpp", "Cpp", "CPP", "c++", "C++", }, /*EnclosingFunctionNames=*/ {}, /*CanonicalDelimiter=*/"", /*BasedOnStyle=*/"google", }, { FormatStyle::LK_TextProto, /*Delimiters=*/ { "pb", "PB", "proto", "PROTO", }, /*EnclosingFunctionNames=*/ { "EqualsProto", "EquivToProto", "PARSE_PARTIAL_TEXT_PROTO", "PARSE_TEST_PROTO", "PARSE_TEXT_PROTO", "ParseTextOrDie", "ParseTextProtoOrDie", }, /*CanonicalDelimiter=*/"", /*BasedOnStyle=*/"google", }, }; GoogleStyle.SpacesBeforeTrailingComments = 2; GoogleStyle.Standard = FormatStyle::LS_Auto; GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200; GoogleStyle.PenaltyBreakBeforeFirstCallParameter = 1; if (Language == FormatStyle::LK_Java) { GoogleStyle.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; GoogleStyle.AlignOperands = false; GoogleStyle.AlignTrailingComments = false; GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty; GoogleStyle.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Never; GoogleStyle.AlwaysBreakBeforeMultilineStrings = false; GoogleStyle.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment; GoogleStyle.ColumnLimit = 100; GoogleStyle.SpaceAfterCStyleCast = true; GoogleStyle.SpacesBeforeTrailingComments = 1; } else if (Language == FormatStyle::LK_JavaScript) { GoogleStyle.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak; GoogleStyle.AlignOperands = false; GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty; GoogleStyle.AlwaysBreakBeforeMultilineStrings = false; GoogleStyle.BreakBeforeTernaryOperators = false; // taze:, triple slash directives (`/// <...`), @see, which is commonly // followed by overlong URLs. GoogleStyle.CommentPragmas = "(taze:|^/[ \t]*<|@see)"; GoogleStyle.MaxEmptyLinesToKeep = 3; GoogleStyle.NamespaceIndentation = FormatStyle::NI_All; GoogleStyle.SpacesInContainerLiterals = false; GoogleStyle.JavaScriptQuotes = FormatStyle::JSQS_Single; GoogleStyle.JavaScriptWrapImports = false; } else if (Language == FormatStyle::LK_Proto) { GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty; GoogleStyle.AlwaysBreakBeforeMultilineStrings = false; GoogleStyle.SpacesInContainerLiterals = false; GoogleStyle.Cpp11BracedListStyle = false; // This affects protocol buffer options specifications and text protos. // Text protos are currently mostly formatted inside C++ raw string literals // and often the current breaking behavior of string literals is not // beneficial there. Investigate turning this on once proper string reflow // has been implemented. GoogleStyle.BreakStringLiterals = false; } else if (Language == FormatStyle::LK_ObjC) { GoogleStyle.AlwaysBreakBeforeMultilineStrings = false; GoogleStyle.ColumnLimit = 100; // "Regroup" doesn't work well for ObjC yet (main header heuristic, // relationship between ObjC standard library headers and other heades, // #imports, etc.) GoogleStyle.IncludeStyle.IncludeBlocks = tooling::IncludeStyle::IBS_Preserve; } return GoogleStyle; } FormatStyle getChromiumStyle(FormatStyle::LanguageKind Language) { FormatStyle ChromiumStyle = getGoogleStyle(Language); // Disable include reordering across blocks in Chromium code. // - clang-format tries to detect that foo.h is the "main" header for // foo.cc and foo_unittest.cc via IncludeIsMainRegex. However, Chromium // uses many other suffices (_win.cc, _mac.mm, _posix.cc, _browsertest.cc, // _private.cc, _impl.cc etc) in different permutations // (_win_browsertest.cc) so disable this until IncludeIsMainRegex has a // better default for Chromium code. // - The default for .cc and .mm files is different (r357695) for Google style // for the same reason. The plan is to unify this again once the main // header detection works for Google's ObjC code, but this hasn't happened // yet. Since Chromium has some ObjC code, switching Chromium is blocked // on that. // - Finally, "If include reordering is harmful, put things in different // blocks to prevent it" has been a recommendation for a long time that // people are used to. We'll need a dev education push to change this to // "If include reordering is harmful, put things in a different block and // _prepend that with a comment_ to prevent it" before changing behavior. ChromiumStyle.IncludeStyle.IncludeBlocks = tooling::IncludeStyle::IBS_Preserve; if (Language == FormatStyle::LK_Java) { ChromiumStyle.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_WithoutElse; ChromiumStyle.BreakAfterJavaFieldAnnotations = true; ChromiumStyle.ContinuationIndentWidth = 8; ChromiumStyle.IndentWidth = 4; // See styleguide for import groups: // https://chromium.googlesource.com/chromium/src/+/master/styleguide/java/java.md#Import-Order ChromiumStyle.JavaImportGroups = { "android", "androidx", "com", "dalvik", "junit", "org", "com.google.android.apps.chrome", "org.chromium", "java", "javax", }; ChromiumStyle.SortIncludes = true; } else if (Language == FormatStyle::LK_JavaScript) { ChromiumStyle.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Never; ChromiumStyle.AllowShortLoopsOnASingleLine = false; } else { ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false; ChromiumStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline; ChromiumStyle.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Never; ChromiumStyle.AllowShortLoopsOnASingleLine = false; ChromiumStyle.BinPackParameters = false; ChromiumStyle.DerivePointerAlignment = false; if (Language == FormatStyle::LK_ObjC) ChromiumStyle.ColumnLimit = 80; } return ChromiumStyle; } FormatStyle getMozillaStyle() { FormatStyle MozillaStyle = getLLVMStyle(); MozillaStyle.AllowAllParametersOfDeclarationOnNextLine = false; MozillaStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline; MozillaStyle.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevel; MozillaStyle.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_TopLevel; MozillaStyle.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes; MozillaStyle.BinPackParameters = false; MozillaStyle.BinPackArguments = false; MozillaStyle.BreakBeforeBraces = FormatStyle::BS_Mozilla; MozillaStyle.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; MozillaStyle.BreakInheritanceList = FormatStyle::BILS_BeforeComma; MozillaStyle.ConstructorInitializerIndentWidth = 2; MozillaStyle.ContinuationIndentWidth = 2; MozillaStyle.Cpp11BracedListStyle = false; MozillaStyle.FixNamespaceComments = false; MozillaStyle.IndentCaseLabels = true; MozillaStyle.ObjCSpaceAfterProperty = true; MozillaStyle.ObjCSpaceBeforeProtocolList = false; MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200; MozillaStyle.PointerAlignment = FormatStyle::PAS_Left; MozillaStyle.SpaceAfterTemplateKeyword = false; return MozillaStyle; } FormatStyle getWebKitStyle() { FormatStyle Style = getLLVMStyle(); Style.AccessModifierOffset = -4; Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; Style.AlignOperands = false; Style.AlignTrailingComments = false; Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty; Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; Style.BreakBeforeBraces = FormatStyle::BS_WebKit; Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; Style.Cpp11BracedListStyle = false; Style.ColumnLimit = 0; Style.FixNamespaceComments = false; Style.IndentWidth = 4; Style.NamespaceIndentation = FormatStyle::NI_Inner; Style.ObjCBlockIndentWidth = 4; Style.ObjCSpaceAfterProperty = true; Style.PointerAlignment = FormatStyle::PAS_Left; Style.SpaceBeforeCpp11BracedList = true; Style.SpaceInEmptyBlock = true; return Style; } FormatStyle getGNUStyle() { FormatStyle Style = getLLVMStyle(); Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_All; Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_AllDefinitions; Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All; Style.BreakBeforeBraces = FormatStyle::BS_GNU; Style.BreakBeforeTernaryOperators = true; Style.Cpp11BracedListStyle = false; Style.ColumnLimit = 79; Style.FixNamespaceComments = false; Style.SpaceBeforeParens = FormatStyle::SBPO_Always; Style.Standard = FormatStyle::LS_Cpp03; return Style; } FormatStyle getMicrosoftStyle(FormatStyle::LanguageKind Language) { FormatStyle Style = getLLVMStyle(); Style.ColumnLimit = 120; Style.TabWidth = 4; Style.IndentWidth = 4; Style.UseTab = FormatStyle::UT_Never; Style.BreakBeforeBraces = FormatStyle::BS_Custom; Style.BraceWrapping.AfterClass = true; Style.BraceWrapping.AfterControlStatement = true; Style.BraceWrapping.AfterEnum = true; Style.BraceWrapping.AfterFunction = true; Style.BraceWrapping.AfterNamespace = true; Style.BraceWrapping.AfterObjCDeclaration = true; Style.BraceWrapping.AfterStruct = true; Style.BraceWrapping.AfterExternBlock = true; Style.BraceWrapping.BeforeCatch = true; Style.BraceWrapping.BeforeElse = true; Style.PenaltyReturnTypeOnItsOwnLine = 1000; Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None; Style.AllowShortCaseLabelsOnASingleLine = false; Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Never; Style.AllowShortLoopsOnASingleLine = false; return Style; } FormatStyle getNoStyle() { FormatStyle NoStyle = getLLVMStyle(); NoStyle.DisableFormat = true; NoStyle.SortIncludes = false; NoStyle.SortUsingDeclarations = false; return NoStyle; } bool getPredefinedStyle(StringRef Name, FormatStyle::LanguageKind Language, FormatStyle *Style) { if (Name.equals_lower("llvm")) { *Style = getLLVMStyle(Language); } else if (Name.equals_lower("chromium")) { *Style = getChromiumStyle(Language); } else if (Name.equals_lower("mozilla")) { *Style = getMozillaStyle(); } else if (Name.equals_lower("google")) { *Style = getGoogleStyle(Language); } else if (Name.equals_lower("webkit")) { *Style = getWebKitStyle(); } else if (Name.equals_lower("gnu")) { *Style = getGNUStyle(); } else if (Name.equals_lower("microsoft")) { *Style = getMicrosoftStyle(Language); } else if (Name.equals_lower("none")) { *Style = getNoStyle(); } else { return false; } Style->Language = Language; return true; } std::error_code parseConfiguration(StringRef Text, FormatStyle *Style) { assert(Style); FormatStyle::LanguageKind Language = Style->Language; assert(Language != FormatStyle::LK_None); if (Text.trim().empty()) return make_error_code(ParseError::Error); Style->StyleSet.Clear(); std::vector Styles; llvm::yaml::Input Input(Text); // DocumentListTraits> uses the context to get default // values for the fields, keys for which are missing from the configuration. // Mapping also uses the context to get the language to find the correct // base style. Input.setContext(Style); Input >> Styles; if (Input.error()) return Input.error(); for (unsigned i = 0; i < Styles.size(); ++i) { // Ensures that only the first configuration can skip the Language option. if (Styles[i].Language == FormatStyle::LK_None && i != 0) return make_error_code(ParseError::Error); // Ensure that each language is configured at most once. for (unsigned j = 0; j < i; ++j) { if (Styles[i].Language == Styles[j].Language) { LLVM_DEBUG(llvm::dbgs() << "Duplicate languages in the config file on positions " << j << " and " << i << "\n"); return make_error_code(ParseError::Error); } } } // Look for a suitable configuration starting from the end, so we can // find the configuration for the specific language first, and the default // configuration (which can only be at slot 0) after it. FormatStyle::FormatStyleSet StyleSet; bool LanguageFound = false; for (int i = Styles.size() - 1; i >= 0; --i) { if (Styles[i].Language != FormatStyle::LK_None) StyleSet.Add(Styles[i]); if (Styles[i].Language == Language) LanguageFound = true; } if (!LanguageFound) { if (Styles.empty() || Styles[0].Language != FormatStyle::LK_None) return make_error_code(ParseError::Unsuitable); FormatStyle DefaultStyle = Styles[0]; DefaultStyle.Language = Language; StyleSet.Add(std::move(DefaultStyle)); } *Style = *StyleSet.Get(Language); return make_error_code(ParseError::Success); } std::string configurationAsText(const FormatStyle &Style) { std::string Text; llvm::raw_string_ostream Stream(Text); llvm::yaml::Output Output(Stream); // We use the same mapping method for input and output, so we need a non-const // reference here. FormatStyle NonConstStyle = expandPresets(Style); Output << NonConstStyle; return Stream.str(); } llvm::Optional FormatStyle::FormatStyleSet::Get(FormatStyle::LanguageKind Language) const { if (!Styles) return None; auto It = Styles->find(Language); if (It == Styles->end()) return None; FormatStyle Style = It->second; Style.StyleSet = *this; return Style; } void FormatStyle::FormatStyleSet::Add(FormatStyle Style) { assert(Style.Language != LK_None && "Cannot add a style for LK_None to a StyleSet"); assert( !Style.StyleSet.Styles && "Cannot add a style associated with an existing StyleSet to a StyleSet"); if (!Styles) Styles = std::make_shared(); (*Styles)[Style.Language] = std::move(Style); } void FormatStyle::FormatStyleSet::Clear() { Styles.reset(); } llvm::Optional FormatStyle::GetLanguageStyle(FormatStyle::LanguageKind Language) const { return StyleSet.Get(Language); } namespace { class JavaScriptRequoter : public TokenAnalyzer { public: JavaScriptRequoter(const Environment &Env, const FormatStyle &Style) : TokenAnalyzer(Env, Style) {} std::pair analyze(TokenAnnotator &Annotator, SmallVectorImpl &AnnotatedLines, FormatTokenLexer &Tokens) override { AffectedRangeMgr.computeAffectedLines(AnnotatedLines); tooling::Replacements Result; requoteJSStringLiteral(AnnotatedLines, Result); return {Result, 0}; } private: // Replaces double/single-quoted string literal as appropriate, re-escaping // the contents in the process. void requoteJSStringLiteral(SmallVectorImpl &Lines, tooling::Replacements &Result) { for (AnnotatedLine *Line : Lines) { requoteJSStringLiteral(Line->Children, Result); if (!Line->Affected) continue; for (FormatToken *FormatTok = Line->First; FormatTok; FormatTok = FormatTok->Next) { StringRef Input = FormatTok->TokenText; if (FormatTok->Finalized || !FormatTok->isStringLiteral() || // NB: testing for not starting with a double quote to avoid // breaking `template strings`. (Style.JavaScriptQuotes == FormatStyle::JSQS_Single && !Input.startswith("\"")) || (Style.JavaScriptQuotes == FormatStyle::JSQS_Double && !Input.startswith("\'"))) continue; // Change start and end quote. bool IsSingle = Style.JavaScriptQuotes == FormatStyle::JSQS_Single; SourceLocation Start = FormatTok->Tok.getLocation(); auto Replace = [&](SourceLocation Start, unsigned Length, StringRef ReplacementText) { auto Err = Result.add(tooling::Replacement( Env.getSourceManager(), Start, Length, ReplacementText)); // FIXME: handle error. For now, print error message and skip the // replacement for release version. if (Err) { llvm::errs() << llvm::toString(std::move(Err)) << "\n"; assert(false); } }; Replace(Start, 1, IsSingle ? "'" : "\""); Replace(FormatTok->Tok.getEndLoc().getLocWithOffset(-1), 1, IsSingle ? "'" : "\""); // Escape internal quotes. bool Escaped = false; for (size_t i = 1; i < Input.size() - 1; i++) { switch (Input[i]) { case '\\': if (!Escaped && i + 1 < Input.size() && ((IsSingle && Input[i + 1] == '"') || (!IsSingle && Input[i + 1] == '\''))) { // Remove this \, it's escaping a " or ' that no longer needs // escaping Replace(Start.getLocWithOffset(i), 1, ""); continue; } Escaped = !Escaped; break; case '\"': case '\'': if (!Escaped && IsSingle == (Input[i] == '\'')) { // Escape the quote. Replace(Start.getLocWithOffset(i), 0, "\\"); } Escaped = false; break; default: Escaped = false; break; } } } } } }; class Formatter : public TokenAnalyzer { public: Formatter(const Environment &Env, const FormatStyle &Style, FormattingAttemptStatus *Status) : TokenAnalyzer(Env, Style), Status(Status) {} std::pair analyze(TokenAnnotator &Annotator, SmallVectorImpl &AnnotatedLines, FormatTokenLexer &Tokens) override { tooling::Replacements Result; deriveLocalStyle(AnnotatedLines); AffectedRangeMgr.computeAffectedLines(AnnotatedLines); for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) { Annotator.calculateFormattingInformation(*AnnotatedLines[i]); } Annotator.setCommentLineLevels(AnnotatedLines); WhitespaceManager Whitespaces( Env.getSourceManager(), Style, inputUsesCRLF(Env.getSourceManager().getBufferData(Env.getFileID()))); ContinuationIndenter Indenter(Style, Tokens.getKeywords(), Env.getSourceManager(), Whitespaces, Encoding, BinPackInconclusiveFunctions); unsigned Penalty = UnwrappedLineFormatter(&Indenter, &Whitespaces, Style, Tokens.getKeywords(), Env.getSourceManager(), Status) .format(AnnotatedLines, /*DryRun=*/false, /*AdditionalIndent=*/0, /*FixBadIndentation=*/false, /*FirstStartColumn=*/Env.getFirstStartColumn(), /*NextStartColumn=*/Env.getNextStartColumn(), /*LastStartColumn=*/Env.getLastStartColumn()); for (const auto &R : Whitespaces.generateReplacements()) if (Result.add(R)) return std::make_pair(Result, 0); return std::make_pair(Result, Penalty); } private: static bool inputUsesCRLF(StringRef Text) { return Text.count('\r') * 2 > Text.count('\n'); } bool hasCpp03IncompatibleFormat(const SmallVectorImpl &Lines) { for (const AnnotatedLine *Line : Lines) { if (hasCpp03IncompatibleFormat(Line->Children)) return true; for (FormatToken *Tok = Line->First->Next; Tok; Tok = Tok->Next) { if (Tok->WhitespaceRange.getBegin() == Tok->WhitespaceRange.getEnd()) { if (Tok->is(tok::coloncolon) && Tok->Previous->is(TT_TemplateOpener)) return true; if (Tok->is(TT_TemplateCloser) && Tok->Previous->is(TT_TemplateCloser)) return true; } } } return false; } int countVariableAlignments(const SmallVectorImpl &Lines) { int AlignmentDiff = 0; for (const AnnotatedLine *Line : Lines) { AlignmentDiff += countVariableAlignments(Line->Children); for (FormatToken *Tok = Line->First; Tok && Tok->Next; Tok = Tok->Next) { if (!Tok->is(TT_PointerOrReference)) continue; bool SpaceBefore = Tok->WhitespaceRange.getBegin() != Tok->WhitespaceRange.getEnd(); bool SpaceAfter = Tok->Next->WhitespaceRange.getBegin() != Tok->Next->WhitespaceRange.getEnd(); if (SpaceBefore && !SpaceAfter) ++AlignmentDiff; if (!SpaceBefore && SpaceAfter) --AlignmentDiff; } } return AlignmentDiff; } void deriveLocalStyle(const SmallVectorImpl &AnnotatedLines) { bool HasBinPackedFunction = false; bool HasOnePerLineFunction = false; for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) { if (!AnnotatedLines[i]->First->Next) continue; FormatToken *Tok = AnnotatedLines[i]->First->Next; while (Tok->Next) { if (Tok->PackingKind == PPK_BinPacked) HasBinPackedFunction = true; if (Tok->PackingKind == PPK_OnePerLine) HasOnePerLineFunction = true; Tok = Tok->Next; } } if (Style.DerivePointerAlignment) Style.PointerAlignment = countVariableAlignments(AnnotatedLines) <= 0 ? FormatStyle::PAS_Left : FormatStyle::PAS_Right; if (Style.Standard == FormatStyle::LS_Auto) Style.Standard = hasCpp03IncompatibleFormat(AnnotatedLines) ? FormatStyle::LS_Cpp11 : FormatStyle::LS_Cpp03; BinPackInconclusiveFunctions = HasBinPackedFunction || !HasOnePerLineFunction; } bool BinPackInconclusiveFunctions; FormattingAttemptStatus *Status; }; // This class clean up the erroneous/redundant code around the given ranges in // file. class Cleaner : public TokenAnalyzer { public: Cleaner(const Environment &Env, const FormatStyle &Style) : TokenAnalyzer(Env, Style), DeletedTokens(FormatTokenLess(Env.getSourceManager())) {} // FIXME: eliminate unused parameters. std::pair analyze(TokenAnnotator &Annotator, SmallVectorImpl &AnnotatedLines, FormatTokenLexer &Tokens) override { // FIXME: in the current implementation the granularity of affected range // is an annotated line. However, this is not sufficient. Furthermore, // redundant code introduced by replacements does not necessarily // intercept with ranges of replacements that result in the redundancy. // To determine if some redundant code is actually introduced by // replacements(e.g. deletions), we need to come up with a more // sophisticated way of computing affected ranges. AffectedRangeMgr.computeAffectedLines(AnnotatedLines); checkEmptyNamespace(AnnotatedLines); for (auto *Line : AnnotatedLines) cleanupLine(Line); return {generateFixes(), 0}; } private: void cleanupLine(AnnotatedLine *Line) { for (auto *Child : Line->Children) { cleanupLine(Child); } if (Line->Affected) { cleanupRight(Line->First, tok::comma, tok::comma); cleanupRight(Line->First, TT_CtorInitializerColon, tok::comma); cleanupRight(Line->First, tok::l_paren, tok::comma); cleanupLeft(Line->First, tok::comma, tok::r_paren); cleanupLeft(Line->First, TT_CtorInitializerComma, tok::l_brace); cleanupLeft(Line->First, TT_CtorInitializerColon, tok::l_brace); cleanupLeft(Line->First, TT_CtorInitializerColon, tok::equal); } } bool containsOnlyComments(const AnnotatedLine &Line) { for (FormatToken *Tok = Line.First; Tok != nullptr; Tok = Tok->Next) { if (Tok->isNot(tok::comment)) return false; } return true; } // Iterate through all lines and remove any empty (nested) namespaces. void checkEmptyNamespace(SmallVectorImpl &AnnotatedLines) { std::set DeletedLines; for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) { auto &Line = *AnnotatedLines[i]; if (Line.startsWithNamespace()) { checkEmptyNamespace(AnnotatedLines, i, i, DeletedLines); } } for (auto Line : DeletedLines) { FormatToken *Tok = AnnotatedLines[Line]->First; while (Tok) { deleteToken(Tok); Tok = Tok->Next; } } } // The function checks if the namespace, which starts from \p CurrentLine, and // its nested namespaces are empty and delete them if they are empty. It also // sets \p NewLine to the last line checked. // Returns true if the current namespace is empty. bool checkEmptyNamespace(SmallVectorImpl &AnnotatedLines, unsigned CurrentLine, unsigned &NewLine, std::set &DeletedLines) { unsigned InitLine = CurrentLine, End = AnnotatedLines.size(); if (Style.BraceWrapping.AfterNamespace) { // If the left brace is in a new line, we should consume it first so that // it does not make the namespace non-empty. // FIXME: error handling if there is no left brace. if (!AnnotatedLines[++CurrentLine]->startsWith(tok::l_brace)) { NewLine = CurrentLine; return false; } } else if (!AnnotatedLines[CurrentLine]->endsWith(tok::l_brace)) { return false; } while (++CurrentLine < End) { if (AnnotatedLines[CurrentLine]->startsWith(tok::r_brace)) break; if (AnnotatedLines[CurrentLine]->startsWithNamespace()) { if (!checkEmptyNamespace(AnnotatedLines, CurrentLine, NewLine, DeletedLines)) return false; CurrentLine = NewLine; continue; } if (containsOnlyComments(*AnnotatedLines[CurrentLine])) continue; // If there is anything other than comments or nested namespaces in the // current namespace, the namespace cannot be empty. NewLine = CurrentLine; return false; } NewLine = CurrentLine; if (CurrentLine >= End) return false; // Check if the empty namespace is actually affected by changed ranges. if (!AffectedRangeMgr.affectsCharSourceRange(CharSourceRange::getCharRange( AnnotatedLines[InitLine]->First->Tok.getLocation(), AnnotatedLines[CurrentLine]->Last->Tok.getEndLoc()))) return false; for (unsigned i = InitLine; i <= CurrentLine; ++i) { DeletedLines.insert(i); } return true; } // Checks pairs {start, start->next},..., {end->previous, end} and deletes one // of the token in the pair if the left token has \p LK token kind and the // right token has \p RK token kind. If \p DeleteLeft is true, the left token // is deleted on match; otherwise, the right token is deleted. template void cleanupPair(FormatToken *Start, LeftKind LK, RightKind RK, bool DeleteLeft) { auto NextNotDeleted = [this](const FormatToken &Tok) -> FormatToken * { for (auto *Res = Tok.Next; Res; Res = Res->Next) if (!Res->is(tok::comment) && DeletedTokens.find(Res) == DeletedTokens.end()) return Res; return nullptr; }; for (auto *Left = Start; Left;) { auto *Right = NextNotDeleted(*Left); if (!Right) break; if (Left->is(LK) && Right->is(RK)) { deleteToken(DeleteLeft ? Left : Right); for (auto *Tok = Left->Next; Tok && Tok != Right; Tok = Tok->Next) deleteToken(Tok); // If the right token is deleted, we should keep the left token // unchanged and pair it with the new right token. if (!DeleteLeft) continue; } Left = Right; } } template void cleanupLeft(FormatToken *Start, LeftKind LK, RightKind RK) { cleanupPair(Start, LK, RK, /*DeleteLeft=*/true); } template void cleanupRight(FormatToken *Start, LeftKind LK, RightKind RK) { cleanupPair(Start, LK, RK, /*DeleteLeft=*/false); } // Delete the given token. inline void deleteToken(FormatToken *Tok) { if (Tok) DeletedTokens.insert(Tok); } tooling::Replacements generateFixes() { tooling::Replacements Fixes; std::vector Tokens; std::copy(DeletedTokens.begin(), DeletedTokens.end(), std::back_inserter(Tokens)); // Merge multiple continuous token deletions into one big deletion so that // the number of replacements can be reduced. This makes computing affected // ranges more efficient when we run reformat on the changed code. unsigned Idx = 0; while (Idx < Tokens.size()) { unsigned St = Idx, End = Idx; while ((End + 1) < Tokens.size() && Tokens[End]->Next == Tokens[End + 1]) { End++; } auto SR = CharSourceRange::getCharRange(Tokens[St]->Tok.getLocation(), Tokens[End]->Tok.getEndLoc()); auto Err = Fixes.add(tooling::Replacement(Env.getSourceManager(), SR, "")); // FIXME: better error handling. for now just print error message and skip // for the release version. if (Err) { llvm::errs() << llvm::toString(std::move(Err)) << "\n"; assert(false && "Fixes must not conflict!"); } Idx = End + 1; } return Fixes; } // Class for less-than inequality comparason for the set `RedundantTokens`. // We store tokens in the order they appear in the translation unit so that // we do not need to sort them in `generateFixes()`. struct FormatTokenLess { FormatTokenLess(const SourceManager &SM) : SM(SM) {} bool operator()(const FormatToken *LHS, const FormatToken *RHS) const { return SM.isBeforeInTranslationUnit(LHS->Tok.getLocation(), RHS->Tok.getLocation()); } const SourceManager &SM; }; // Tokens to be deleted. std::set DeletedTokens; }; class ObjCHeaderStyleGuesser : public TokenAnalyzer { public: ObjCHeaderStyleGuesser(const Environment &Env, const FormatStyle &Style) : TokenAnalyzer(Env, Style), IsObjC(false) {} std::pair analyze(TokenAnnotator &Annotator, SmallVectorImpl &AnnotatedLines, FormatTokenLexer &Tokens) override { assert(Style.Language == FormatStyle::LK_Cpp); IsObjC = guessIsObjC(Env.getSourceManager(), AnnotatedLines, Tokens.getKeywords()); tooling::Replacements Result; return {Result, 0}; } bool isObjC() { return IsObjC; } private: static bool guessIsObjC(const SourceManager &SourceManager, const SmallVectorImpl &AnnotatedLines, const AdditionalKeywords &Keywords) { // Keep this array sorted, since we are binary searching over it. static constexpr llvm::StringLiteral FoundationIdentifiers[] = { "CGFloat", "CGPoint", "CGPointMake", "CGPointZero", "CGRect", "CGRectEdge", "CGRectInfinite", "CGRectMake", "CGRectNull", "CGRectZero", "CGSize", "CGSizeMake", "CGVector", "CGVectorMake", "NSAffineTransform", "NSArray", "NSAttributedString", "NSBlockOperation", "NSBundle", "NSCache", "NSCalendar", "NSCharacterSet", "NSCountedSet", "NSData", "NSDataDetector", "NSDecimal", "NSDecimalNumber", "NSDictionary", "NSEdgeInsets", "NSHashTable", "NSIndexPath", "NSIndexSet", "NSInteger", "NSInvocationOperation", "NSLocale", "NSMapTable", "NSMutableArray", "NSMutableAttributedString", "NSMutableCharacterSet", "NSMutableData", "NSMutableDictionary", "NSMutableIndexSet", "NSMutableOrderedSet", "NSMutableSet", "NSMutableString", "NSNumber", "NSNumberFormatter", "NSObject", "NSOperation", "NSOperationQueue", "NSOperationQueuePriority", "NSOrderedSet", "NSPoint", "NSPointerArray", "NSQualityOfService", "NSRange", "NSRect", "NSRegularExpression", "NSSet", "NSSize", "NSString", "NSTimeZone", "NSUInteger", "NSURL", "NSURLComponents", "NSURLQueryItem", "NSUUID", "NSValue", "UIImage", "UIView", }; for (auto Line : AnnotatedLines) { for (const FormatToken *FormatTok = Line->First; FormatTok; FormatTok = FormatTok->Next) { if ((FormatTok->Previous && FormatTok->Previous->is(tok::at) && (FormatTok->Tok.getObjCKeywordID() != tok::objc_not_keyword || FormatTok->isOneOf(tok::numeric_constant, tok::l_square, tok::l_brace))) || (FormatTok->Tok.isAnyIdentifier() && std::binary_search(std::begin(FoundationIdentifiers), std::end(FoundationIdentifiers), FormatTok->TokenText)) || FormatTok->is(TT_ObjCStringLiteral) || FormatTok->isOneOf(Keywords.kw_NS_CLOSED_ENUM, Keywords.kw_NS_ENUM, Keywords.kw_NS_OPTIONS, TT_ObjCBlockLBrace, TT_ObjCBlockLParen, TT_ObjCDecl, TT_ObjCForIn, TT_ObjCMethodExpr, TT_ObjCMethodSpecifier, TT_ObjCProperty)) { LLVM_DEBUG(llvm::dbgs() << "Detected ObjC at location " << FormatTok->Tok.getLocation().printToString( SourceManager) << " token: " << FormatTok->TokenText << " token type: " << getTokenTypeName(FormatTok->Type) << "\n"); return true; } if (guessIsObjC(SourceManager, Line->Children, Keywords)) return true; } } return false; } bool IsObjC; }; struct IncludeDirective { StringRef Filename; StringRef Text; unsigned Offset; int Category; int Priority; }; struct JavaImportDirective { StringRef Identifier; StringRef Text; unsigned Offset; std::vector AssociatedCommentLines; bool IsStatic; }; } // end anonymous namespace // Determines whether 'Ranges' intersects with ('Start', 'End'). static bool affectsRange(ArrayRef Ranges, unsigned Start, unsigned End) { for (auto Range : Ranges) { if (Range.getOffset() < End && Range.getOffset() + Range.getLength() > Start) return true; } return false; } // Returns a pair (Index, OffsetToEOL) describing the position of the cursor // before sorting/deduplicating. Index is the index of the include under the // cursor in the original set of includes. If this include has duplicates, it is // the index of the first of the duplicates as the others are going to be // removed. OffsetToEOL describes the cursor's position relative to the end of // its current line. // If `Cursor` is not on any #include, `Index` will be UINT_MAX. static std::pair FindCursorIndex(const SmallVectorImpl &Includes, const SmallVectorImpl &Indices, unsigned Cursor) { unsigned CursorIndex = UINT_MAX; unsigned OffsetToEOL = 0; for (int i = 0, e = Includes.size(); i != e; ++i) { unsigned Start = Includes[Indices[i]].Offset; unsigned End = Start + Includes[Indices[i]].Text.size(); if (!(Cursor >= Start && Cursor < End)) continue; CursorIndex = Indices[i]; OffsetToEOL = End - Cursor; // Put the cursor on the only remaining #include among the duplicate // #includes. while (--i >= 0 && Includes[CursorIndex].Text == Includes[Indices[i]].Text) CursorIndex = i; break; } return std::make_pair(CursorIndex, OffsetToEOL); } // Sorts and deduplicate a block of includes given by 'Includes' alphabetically // adding the necessary replacement to 'Replaces'. 'Includes' must be in strict // source order. // #include directives with the same text will be deduplicated, and only the // first #include in the duplicate #includes remains. If the `Cursor` is // provided and put on a deleted #include, it will be moved to the remaining // #include in the duplicate #includes. static void sortCppIncludes(const FormatStyle &Style, const SmallVectorImpl &Includes, ArrayRef Ranges, StringRef FileName, StringRef Code, tooling::Replacements &Replaces, unsigned *Cursor) { tooling::IncludeCategoryManager Categories(Style.IncludeStyle, FileName); unsigned IncludesBeginOffset = Includes.front().Offset; unsigned IncludesEndOffset = Includes.back().Offset + Includes.back().Text.size(); unsigned IncludesBlockSize = IncludesEndOffset - IncludesBeginOffset; if (!affectsRange(Ranges, IncludesBeginOffset, IncludesEndOffset)) return; SmallVector Indices; for (unsigned i = 0, e = Includes.size(); i != e; ++i) { Indices.push_back(i); } llvm::stable_sort(Indices, [&](unsigned LHSI, unsigned RHSI) { return std::tie(Includes[LHSI].Priority, Includes[LHSI].Filename) < std::tie(Includes[RHSI].Priority, Includes[RHSI].Filename); }); // The index of the include on which the cursor will be put after // sorting/deduplicating. unsigned CursorIndex; // The offset from cursor to the end of line. unsigned CursorToEOLOffset; if (Cursor) std::tie(CursorIndex, CursorToEOLOffset) = FindCursorIndex(Includes, Indices, *Cursor); // Deduplicate #includes. Indices.erase(std::unique(Indices.begin(), Indices.end(), [&](unsigned LHSI, unsigned RHSI) { return Includes[LHSI].Text == Includes[RHSI].Text; }), Indices.end()); int CurrentCategory = Includes.front().Category; // If the #includes are out of order, we generate a single replacement fixing // the entire block. Otherwise, no replacement is generated. // In case Style.IncldueStyle.IncludeBlocks != IBS_Preserve, this check is not // enough as additional newlines might be added or removed across #include // blocks. This we handle below by generating the updated #imclude blocks and // comparing it to the original. if (Indices.size() == Includes.size() && std::is_sorted(Indices.begin(), Indices.end()) && Style.IncludeStyle.IncludeBlocks == tooling::IncludeStyle::IBS_Preserve) return; std::string result; for (unsigned Index : Indices) { if (!result.empty()) { result += "\n"; if (Style.IncludeStyle.IncludeBlocks == tooling::IncludeStyle::IBS_Regroup && CurrentCategory != Includes[Index].Category) result += "\n"; } result += Includes[Index].Text; if (Cursor && CursorIndex == Index) *Cursor = IncludesBeginOffset + result.size() - CursorToEOLOffset; CurrentCategory = Includes[Index].Category; } // If the #includes are out of order, we generate a single replacement fixing // the entire range of blocks. Otherwise, no replacement is generated. if (result == Code.substr(IncludesBeginOffset, IncludesBlockSize)) return; auto Err = Replaces.add(tooling::Replacement( FileName, Includes.front().Offset, IncludesBlockSize, result)); // FIXME: better error handling. For now, just skip the replacement for the // release version. if (Err) { llvm::errs() << llvm::toString(std::move(Err)) << "\n"; assert(false); } } namespace { const char CppIncludeRegexPattern[] = R"(^[\t\ ]*#[\t\ ]*(import|include)[^"<]*(["<][^">]*[">]))"; } // anonymous namespace tooling::Replacements sortCppIncludes(const FormatStyle &Style, StringRef Code, ArrayRef Ranges, StringRef FileName, tooling::Replacements &Replaces, unsigned *Cursor) { unsigned Prev = 0; unsigned SearchFrom = 0; llvm::Regex IncludeRegex(CppIncludeRegexPattern); SmallVector Matches; SmallVector IncludesInBlock; // In compiled files, consider the first #include to be the main #include of // the file if it is not a system #include. This ensures that the header // doesn't have hidden dependencies // (http://llvm.org/docs/CodingStandards.html#include-style). // // FIXME: Do some sanity checking, e.g. edit distance of the base name, to fix // cases where the first #include is unlikely to be the main header. tooling::IncludeCategoryManager Categories(Style.IncludeStyle, FileName); bool FirstIncludeBlock = true; bool MainIncludeFound = false; bool FormattingOff = false; for (;;) { auto Pos = Code.find('\n', SearchFrom); StringRef Line = Code.substr(Prev, (Pos != StringRef::npos ? Pos : Code.size()) - Prev); StringRef Trimmed = Line.trim(); if (Trimmed == "// clang-format off" || Trimmed == "/* clang-format off */") FormattingOff = true; else if (Trimmed == "// clang-format on" || Trimmed == "/* clang-format on */") FormattingOff = false; const bool EmptyLineSkipped = Trimmed.empty() && (Style.IncludeStyle.IncludeBlocks == tooling::IncludeStyle::IBS_Merge || Style.IncludeStyle.IncludeBlocks == tooling::IncludeStyle::IBS_Regroup); if (!FormattingOff && !Line.endswith("\\")) { if (IncludeRegex.match(Line, &Matches)) { StringRef IncludeName = Matches[2]; int Category = Categories.getIncludePriority( IncludeName, /*CheckMainHeader=*/!MainIncludeFound && FirstIncludeBlock); int Priority = Categories.getSortIncludePriority( IncludeName, !MainIncludeFound && FirstIncludeBlock); if (Category == 0) MainIncludeFound = true; IncludesInBlock.push_back( {IncludeName, Line, Prev, Category, Priority}); } else if (!IncludesInBlock.empty() && !EmptyLineSkipped) { sortCppIncludes(Style, IncludesInBlock, Ranges, FileName, Code, Replaces, Cursor); IncludesInBlock.clear(); FirstIncludeBlock = false; } Prev = Pos + 1; } if (Pos == StringRef::npos || Pos + 1 == Code.size()) break; SearchFrom = Pos + 1; } if (!IncludesInBlock.empty()) { sortCppIncludes(Style, IncludesInBlock, Ranges, FileName, Code, Replaces, Cursor); } return Replaces; } // Returns group number to use as a first order sort on imports. Gives UINT_MAX // if the import does not match any given groups. static unsigned findJavaImportGroup(const FormatStyle &Style, StringRef ImportIdentifier) { unsigned LongestMatchIndex = UINT_MAX; unsigned LongestMatchLength = 0; for (unsigned I = 0; I < Style.JavaImportGroups.size(); I++) { std::string GroupPrefix = Style.JavaImportGroups[I]; if (ImportIdentifier.startswith(GroupPrefix) && GroupPrefix.length() > LongestMatchLength) { LongestMatchIndex = I; LongestMatchLength = GroupPrefix.length(); } } return LongestMatchIndex; } // Sorts and deduplicates a block of includes given by 'Imports' based on // JavaImportGroups, then adding the necessary replacement to 'Replaces'. // Import declarations with the same text will be deduplicated. Between each // import group, a newline is inserted, and within each import group, a // lexicographic sort based on ASCII value is performed. static void sortJavaImports(const FormatStyle &Style, const SmallVectorImpl &Imports, ArrayRef Ranges, StringRef FileName, StringRef Code, tooling::Replacements &Replaces) { unsigned ImportsBeginOffset = Imports.front().Offset; unsigned ImportsEndOffset = Imports.back().Offset + Imports.back().Text.size(); unsigned ImportsBlockSize = ImportsEndOffset - ImportsBeginOffset; if (!affectsRange(Ranges, ImportsBeginOffset, ImportsEndOffset)) return; SmallVector Indices; SmallVector JavaImportGroups; for (unsigned i = 0, e = Imports.size(); i != e; ++i) { Indices.push_back(i); JavaImportGroups.push_back( findJavaImportGroup(Style, Imports[i].Identifier)); } llvm::sort(Indices, [&](unsigned LHSI, unsigned RHSI) { // Negating IsStatic to push static imports above non-static imports. return std::make_tuple(!Imports[LHSI].IsStatic, JavaImportGroups[LHSI], Imports[LHSI].Identifier) < std::make_tuple(!Imports[RHSI].IsStatic, JavaImportGroups[RHSI], Imports[RHSI].Identifier); }); // Deduplicate imports. Indices.erase(std::unique(Indices.begin(), Indices.end(), [&](unsigned LHSI, unsigned RHSI) { return Imports[LHSI].Text == Imports[RHSI].Text; }), Indices.end()); bool CurrentIsStatic = Imports[Indices.front()].IsStatic; unsigned CurrentImportGroup = JavaImportGroups[Indices.front()]; std::string result; for (unsigned Index : Indices) { if (!result.empty()) { result += "\n"; if (CurrentIsStatic != Imports[Index].IsStatic || CurrentImportGroup != JavaImportGroups[Index]) result += "\n"; } for (StringRef CommentLine : Imports[Index].AssociatedCommentLines) { result += CommentLine; result += "\n"; } result += Imports[Index].Text; CurrentIsStatic = Imports[Index].IsStatic; CurrentImportGroup = JavaImportGroups[Index]; } // If the imports are out of order, we generate a single replacement fixing // the entire block. Otherwise, no replacement is generated. if (result == Code.substr(Imports.front().Offset, ImportsBlockSize)) return; auto Err = Replaces.add(tooling::Replacement(FileName, Imports.front().Offset, ImportsBlockSize, result)); // FIXME: better error handling. For now, just skip the replacement for the // release version. if (Err) { llvm::errs() << llvm::toString(std::move(Err)) << "\n"; assert(false); } } namespace { const char JavaImportRegexPattern[] = "^[\t ]*import[\t ]+(static[\t ]*)?([^\t ]*)[\t ]*;"; } // anonymous namespace tooling::Replacements sortJavaImports(const FormatStyle &Style, StringRef Code, ArrayRef Ranges, StringRef FileName, tooling::Replacements &Replaces) { unsigned Prev = 0; unsigned SearchFrom = 0; llvm::Regex ImportRegex(JavaImportRegexPattern); SmallVector Matches; SmallVector ImportsInBlock; std::vector AssociatedCommentLines; bool FormattingOff = false; for (;;) { auto Pos = Code.find('\n', SearchFrom); StringRef Line = Code.substr(Prev, (Pos != StringRef::npos ? Pos : Code.size()) - Prev); StringRef Trimmed = Line.trim(); if (Trimmed == "// clang-format off") FormattingOff = true; else if (Trimmed == "// clang-format on") FormattingOff = false; if (ImportRegex.match(Line, &Matches)) { if (FormattingOff) { // If at least one import line has formatting turned off, turn off // formatting entirely. return Replaces; } StringRef Static = Matches[1]; StringRef Identifier = Matches[2]; bool IsStatic = false; if (Static.contains("static")) { IsStatic = true; } ImportsInBlock.push_back( {Identifier, Line, Prev, AssociatedCommentLines, IsStatic}); AssociatedCommentLines.clear(); } else if (Trimmed.size() > 0 && !ImportsInBlock.empty()) { // Associating comments within the imports with the nearest import below AssociatedCommentLines.push_back(Line); } Prev = Pos + 1; if (Pos == StringRef::npos || Pos + 1 == Code.size()) break; SearchFrom = Pos + 1; } if (!ImportsInBlock.empty()) sortJavaImports(Style, ImportsInBlock, Ranges, FileName, Code, Replaces); return Replaces; } bool isMpegTS(StringRef Code) { // MPEG transport streams use the ".ts" file extension. clang-format should // not attempt to format those. MPEG TS' frame format starts with 0x47 every // 189 bytes - detect that and return. return Code.size() > 188 && Code[0] == 0x47 && Code[188] == 0x47; } bool isLikelyXml(StringRef Code) { return Code.ltrim().startswith("<"); } tooling::Replacements sortIncludes(const FormatStyle &Style, StringRef Code, ArrayRef Ranges, StringRef FileName, unsigned *Cursor) { tooling::Replacements Replaces; if (!Style.SortIncludes) return Replaces; if (isLikelyXml(Code)) return Replaces; if (Style.Language == FormatStyle::LanguageKind::LK_JavaScript && isMpegTS(Code)) return Replaces; if (Style.Language == FormatStyle::LanguageKind::LK_JavaScript) return sortJavaScriptImports(Style, Code, Ranges, FileName); if (Style.Language == FormatStyle::LanguageKind::LK_Java) return sortJavaImports(Style, Code, Ranges, FileName, Replaces); sortCppIncludes(Style, Code, Ranges, FileName, Replaces, Cursor); return Replaces; } template static llvm::Expected processReplacements(T ProcessFunc, StringRef Code, const tooling::Replacements &Replaces, const FormatStyle &Style) { if (Replaces.empty()) return tooling::Replacements(); auto NewCode = applyAllReplacements(Code, Replaces); if (!NewCode) return NewCode.takeError(); std::vector ChangedRanges = Replaces.getAffectedRanges(); StringRef FileName = Replaces.begin()->getFilePath(); tooling::Replacements FormatReplaces = ProcessFunc(Style, *NewCode, ChangedRanges, FileName); return Replaces.merge(FormatReplaces); } llvm::Expected formatReplacements(StringRef Code, const tooling::Replacements &Replaces, const FormatStyle &Style) { // We need to use lambda function here since there are two versions of // `sortIncludes`. auto SortIncludes = [](const FormatStyle &Style, StringRef Code, std::vector Ranges, StringRef FileName) -> tooling::Replacements { return sortIncludes(Style, Code, Ranges, FileName); }; auto SortedReplaces = processReplacements(SortIncludes, Code, Replaces, Style); if (!SortedReplaces) return SortedReplaces.takeError(); // We need to use lambda function here since there are two versions of // `reformat`. auto Reformat = [](const FormatStyle &Style, StringRef Code, std::vector Ranges, StringRef FileName) -> tooling::Replacements { return reformat(Style, Code, Ranges, FileName); }; return processReplacements(Reformat, Code, *SortedReplaces, Style); } namespace { inline bool isHeaderInsertion(const tooling::Replacement &Replace) { return Replace.getOffset() == UINT_MAX && Replace.getLength() == 0 && llvm::Regex(CppIncludeRegexPattern) .match(Replace.getReplacementText()); } inline bool isHeaderDeletion(const tooling::Replacement &Replace) { return Replace.getOffset() == UINT_MAX && Replace.getLength() == 1; } // FIXME: insert empty lines between newly created blocks. tooling::Replacements fixCppIncludeInsertions(StringRef Code, const tooling::Replacements &Replaces, const FormatStyle &Style) { if (!Style.isCpp()) return Replaces; tooling::Replacements HeaderInsertions; std::set HeadersToDelete; tooling::Replacements Result; for (const auto &R : Replaces) { if (isHeaderInsertion(R)) { // Replacements from \p Replaces must be conflict-free already, so we can // simply consume the error. llvm::consumeError(HeaderInsertions.add(R)); } else if (isHeaderDeletion(R)) { HeadersToDelete.insert(R.getReplacementText()); } else if (R.getOffset() == UINT_MAX) { llvm::errs() << "Insertions other than header #include insertion are " "not supported! " << R.getReplacementText() << "\n"; } else { llvm::consumeError(Result.add(R)); } } if (HeaderInsertions.empty() && HeadersToDelete.empty()) return Replaces; StringRef FileName = Replaces.begin()->getFilePath(); tooling::HeaderIncludes Includes(FileName, Code, Style.IncludeStyle); for (const auto &Header : HeadersToDelete) { tooling::Replacements Replaces = Includes.remove(Header.trim("\"<>"), Header.startswith("<")); for (const auto &R : Replaces) { auto Err = Result.add(R); if (Err) { // Ignore the deletion on conflict. llvm::errs() << "Failed to add header deletion replacement for " << Header << ": " << llvm::toString(std::move(Err)) << "\n"; } } } llvm::Regex IncludeRegex = llvm::Regex(CppIncludeRegexPattern); llvm::SmallVector Matches; for (const auto &R : HeaderInsertions) { auto IncludeDirective = R.getReplacementText(); bool Matched = IncludeRegex.match(IncludeDirective, &Matches); assert(Matched && "Header insertion replacement must have replacement text " "'#include ...'"); (void)Matched; auto IncludeName = Matches[2]; auto Replace = Includes.insert(IncludeName.trim("\"<>"), IncludeName.startswith("<")); if (Replace) { auto Err = Result.add(*Replace); if (Err) { llvm::consumeError(std::move(Err)); unsigned NewOffset = Result.getShiftedCodePosition(Replace->getOffset()); auto Shifted = tooling::Replacement(FileName, NewOffset, 0, Replace->getReplacementText()); Result = Result.merge(tooling::Replacements(Shifted)); } } } return Result; } } // anonymous namespace llvm::Expected cleanupAroundReplacements(StringRef Code, const tooling::Replacements &Replaces, const FormatStyle &Style) { // We need to use lambda function here since there are two versions of // `cleanup`. auto Cleanup = [](const FormatStyle &Style, StringRef Code, std::vector Ranges, StringRef FileName) -> tooling::Replacements { return cleanup(Style, Code, Ranges, FileName); }; // Make header insertion replacements insert new headers into correct blocks. tooling::Replacements NewReplaces = fixCppIncludeInsertions(Code, Replaces, Style); return processReplacements(Cleanup, Code, NewReplaces, Style); } namespace internal { std::pair reformat(const FormatStyle &Style, StringRef Code, ArrayRef Ranges, unsigned FirstStartColumn, unsigned NextStartColumn, unsigned LastStartColumn, StringRef FileName, FormattingAttemptStatus *Status) { FormatStyle Expanded = expandPresets(Style); if (Expanded.DisableFormat) return {tooling::Replacements(), 0}; if (isLikelyXml(Code)) return {tooling::Replacements(), 0}; if (Expanded.Language == FormatStyle::LK_JavaScript && isMpegTS(Code)) return {tooling::Replacements(), 0}; typedef std::function( const Environment &)> AnalyzerPass; SmallVector Passes; if (Style.Language == FormatStyle::LK_Cpp) { if (Style.FixNamespaceComments) Passes.emplace_back([&](const Environment &Env) { return NamespaceEndCommentsFixer(Env, Expanded).process(); }); if (Style.SortUsingDeclarations) Passes.emplace_back([&](const Environment &Env) { return UsingDeclarationsSorter(Env, Expanded).process(); }); } if (Style.Language == FormatStyle::LK_JavaScript && Style.JavaScriptQuotes != FormatStyle::JSQS_Leave) Passes.emplace_back([&](const Environment &Env) { return JavaScriptRequoter(Env, Expanded).process(); }); Passes.emplace_back([&](const Environment &Env) { return Formatter(Env, Expanded, Status).process(); }); auto Env = std::make_unique(Code, FileName, Ranges, FirstStartColumn, NextStartColumn, LastStartColumn); llvm::Optional CurrentCode = None; tooling::Replacements Fixes; unsigned Penalty = 0; for (size_t I = 0, E = Passes.size(); I < E; ++I) { std::pair PassFixes = Passes[I](*Env); auto NewCode = applyAllReplacements( CurrentCode ? StringRef(*CurrentCode) : Code, PassFixes.first); if (NewCode) { Fixes = Fixes.merge(PassFixes.first); Penalty += PassFixes.second; if (I + 1 < E) { CurrentCode = std::move(*NewCode); Env = std::make_unique( *CurrentCode, FileName, tooling::calculateRangesAfterReplacements(Fixes, Ranges), FirstStartColumn, NextStartColumn, LastStartColumn); } } } return {Fixes, Penalty}; } } // namespace internal tooling::Replacements reformat(const FormatStyle &Style, StringRef Code, ArrayRef Ranges, StringRef FileName, FormattingAttemptStatus *Status) { return internal::reformat(Style, Code, Ranges, /*FirstStartColumn=*/0, /*NextStartColumn=*/0, /*LastStartColumn=*/0, FileName, Status) .first; } tooling::Replacements cleanup(const FormatStyle &Style, StringRef Code, ArrayRef Ranges, StringRef FileName) { // cleanups only apply to C++ (they mostly concern ctor commas etc.) if (Style.Language != FormatStyle::LK_Cpp) return tooling::Replacements(); return Cleaner(Environment(Code, FileName, Ranges), Style).process().first; } tooling::Replacements reformat(const FormatStyle &Style, StringRef Code, ArrayRef Ranges, StringRef FileName, bool *IncompleteFormat) { FormattingAttemptStatus Status; auto Result = reformat(Style, Code, Ranges, FileName, &Status); if (!Status.FormatComplete) *IncompleteFormat = true; return Result; } tooling::Replacements fixNamespaceEndComments(const FormatStyle &Style, StringRef Code, ArrayRef Ranges, StringRef FileName) { return NamespaceEndCommentsFixer(Environment(Code, FileName, Ranges), Style) .process() .first; } tooling::Replacements sortUsingDeclarations(const FormatStyle &Style, StringRef Code, ArrayRef Ranges, StringRef FileName) { return UsingDeclarationsSorter(Environment(Code, FileName, Ranges), Style) .process() .first; } LangOptions getFormattingLangOpts(const FormatStyle &Style) { LangOptions LangOpts; FormatStyle::LanguageStandard LexingStd = Style.Standard == FormatStyle::LS_Auto ? FormatStyle::LS_Cpp11 : Style.Standard; LangOpts.CPlusPlus = 1; LangOpts.CPlusPlus11 = LexingStd >= FormatStyle::LS_Cpp11; LangOpts.CPlusPlus14 = LexingStd >= FormatStyle::LS_Cpp11; LangOpts.CPlusPlus17 = LexingStd >= FormatStyle::LS_Cpp11; LangOpts.CPlusPlus2a = LexingStd >= FormatStyle::LS_Cpp11; LangOpts.LineComment = 1; bool AlternativeOperators = Style.isCpp(); LangOpts.CXXOperatorNames = AlternativeOperators ? 1 : 0; LangOpts.Bool = 1; LangOpts.ObjC = 1; LangOpts.MicrosoftExt = 1; // To get kw___try, kw___finally. LangOpts.DeclSpecKeyword = 1; // To get __declspec. return LangOpts; } const char *StyleOptionHelpDescription = "Coding style, currently supports:\n" " LLVM, Google, Chromium, Mozilla, WebKit.\n" "Use -style=file to load style configuration from\n" ".clang-format file located in one of the parent\n" "directories of the source file (or current\n" "directory for stdin).\n" "Use -style=\"{key: value, ...}\" to set specific\n" "parameters, e.g.:\n" " -style=\"{BasedOnStyle: llvm, IndentWidth: 8}\""; static FormatStyle::LanguageKind getLanguageByFileName(StringRef FileName) { if (FileName.endswith(".java")) return FormatStyle::LK_Java; if (FileName.endswith_lower(".js") || FileName.endswith_lower(".mjs") || FileName.endswith_lower(".ts")) return FormatStyle::LK_JavaScript; // (module) JavaScript or TypeScript. if (FileName.endswith(".m") || FileName.endswith(".mm")) return FormatStyle::LK_ObjC; if (FileName.endswith_lower(".proto") || FileName.endswith_lower(".protodevel")) return FormatStyle::LK_Proto; if (FileName.endswith_lower(".textpb") || FileName.endswith_lower(".pb.txt") || FileName.endswith_lower(".textproto") || FileName.endswith_lower(".asciipb")) return FormatStyle::LK_TextProto; if (FileName.endswith_lower(".td")) return FormatStyle::LK_TableGen; if (FileName.endswith_lower(".cs")) return FormatStyle::LK_CSharp; return FormatStyle::LK_Cpp; } FormatStyle::LanguageKind guessLanguage(StringRef FileName, StringRef Code) { const auto GuessedLanguage = getLanguageByFileName(FileName); if (GuessedLanguage == FormatStyle::LK_Cpp) { auto Extension = llvm::sys::path::extension(FileName); // If there's no file extension (or it's .h), we need to check the contents // of the code to see if it contains Objective-C. if (Extension.empty() || Extension == ".h") { auto NonEmptyFileName = FileName.empty() ? "guess.h" : FileName; Environment Env(Code, NonEmptyFileName, /*Ranges=*/{}); ObjCHeaderStyleGuesser Guesser(Env, getLLVMStyle()); Guesser.process(); if (Guesser.isObjC()) return FormatStyle::LK_ObjC; } } return GuessedLanguage; } const char *DefaultFormatStyle = "file"; const char *DefaultFallbackStyle = "LLVM"; llvm::Expected getStyle(StringRef StyleName, StringRef FileName, StringRef FallbackStyleName, StringRef Code, llvm::vfs::FileSystem *FS) { if (!FS) { FS = llvm::vfs::getRealFileSystem().get(); } FormatStyle Style = getLLVMStyle(guessLanguage(FileName, Code)); FormatStyle FallbackStyle = getNoStyle(); if (!getPredefinedStyle(FallbackStyleName, Style.Language, &FallbackStyle)) return make_string_error("Invalid fallback style \"" + FallbackStyleName); if (StyleName.startswith("{")) { // Parse YAML/JSON style from the command line. if (std::error_code ec = parseConfiguration(StyleName, &Style)) return make_string_error("Error parsing -style: " + ec.message()); return Style; } if (!StyleName.equals_lower("file")) { if (!getPredefinedStyle(StyleName, Style.Language, &Style)) return make_string_error("Invalid value for -style"); return Style; } // Look for .clang-format/_clang-format file in the file's parent directories. SmallString<128> UnsuitableConfigFiles; SmallString<128> Path(FileName); if (std::error_code EC = FS->makeAbsolute(Path)) return make_string_error(EC.message()); for (StringRef Directory = Path; !Directory.empty(); Directory = llvm::sys::path::parent_path(Directory)) { auto Status = FS->status(Directory); if (!Status || Status->getType() != llvm::sys::fs::file_type::directory_file) { continue; } SmallString<128> ConfigFile(Directory); llvm::sys::path::append(ConfigFile, ".clang-format"); LLVM_DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n"); Status = FS->status(ConfigFile.str()); bool FoundConfigFile = Status && (Status->getType() == llvm::sys::fs::file_type::regular_file); if (!FoundConfigFile) { // Try _clang-format too, since dotfiles are not commonly used on Windows. ConfigFile = Directory; llvm::sys::path::append(ConfigFile, "_clang-format"); LLVM_DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n"); Status = FS->status(ConfigFile.str()); FoundConfigFile = Status && (Status->getType() == llvm::sys::fs::file_type::regular_file); } if (FoundConfigFile) { llvm::ErrorOr> Text = FS->getBufferForFile(ConfigFile.str()); if (std::error_code EC = Text.getError()) return make_string_error(EC.message()); if (std::error_code ec = parseConfiguration(Text.get()->getBuffer(), &Style)) { if (ec == ParseError::Unsuitable) { if (!UnsuitableConfigFiles.empty()) UnsuitableConfigFiles.append(", "); UnsuitableConfigFiles.append(ConfigFile); continue; } return make_string_error("Error reading " + ConfigFile + ": " + ec.message()); } LLVM_DEBUG(llvm::dbgs() << "Using configuration file " << ConfigFile << "\n"); return Style; } } if (!UnsuitableConfigFiles.empty()) return make_string_error("Configuration file(s) do(es) not support " + getLanguageName(Style.Language) + ": " + UnsuitableConfigFiles); return FallbackStyle; } } // namespace format } // namespace clang diff --git a/clang/unittests/Format/FormatTest.cpp b/clang/unittests/Format/FormatTest.cpp index 94eab1a6af50..581d15672ba3 100644 --- a/clang/unittests/Format/FormatTest.cpp +++ b/clang/unittests/Format/FormatTest.cpp @@ -1,14378 +1,14378 @@ //===- unittest/Format/FormatTest.cpp - Formatting unit tests -------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #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) { LLVM_DEBUG(llvm::errs() << "---\n"); LLVM_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)); LLVM_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 Expected, llvm::StringRef Code, const FormatStyle &Style = getLLVMStyle()) { EXPECT_EQ(Expected.str(), format(Expected, Style)) << "Expected code is not stable"; EXPECT_EQ(Expected.str(), format(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(Expected.str(), format(test::messUp(Code), ObjCStyle)); } } void verifyFormat(llvm::StringRef Code, const FormatStyle &Style = getLLVMStyle()) { verifyFormat(Code, test::messUp(Code), Style); } 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")); } TEST_F(FormatTest, DefaultLLVMStyleIsCpp) { EXPECT_EQ(FormatStyle::LK_Cpp, getLLVMStyle().Language); } TEST_F(FormatTest, LLVMStyleOverride) { EXPECT_EQ(FormatStyle::LK_Proto, getLLVMStyle(FormatStyle::LK_Proto).Language); } //===----------------------------------------------------------------------===// // 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("/* something */ namespace N {\n" "\n" "int i;\n" "}", format("/* something */ namespace N {\n" "\n" "int i;\n" "}", getGoogleStyle())); EXPECT_EQ("inline namespace N {\n" "\n" "int i;\n" "}", format("inline namespace N {\n" "\n" "int i;\n" "}", getGoogleStyle())); EXPECT_EQ("/* something */ inline namespace N {\n" "\n" "int i;\n" "}", format("/* something */ inline namespace N {\n" "\n" "int i;\n" "}", getGoogleStyle())); EXPECT_EQ("export namespace N {\n" "\n" "int i;\n" "}", format("export 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" "}")); // Don't remove empty lines before namespace endings. FormatStyle LLVMWithNoNamespaceFix = getLLVMStyle(); LLVMWithNoNamespaceFix.FixNamespaceComments = false; EXPECT_EQ("namespace {\n" "int i;\n" "\n" "}", format("namespace {\n" "int i;\n" "\n" "}", LLVMWithNoNamespaceFix)); EXPECT_EQ("namespace {\n" "int i;\n" "}", format("namespace {\n" "int i;\n" "}", LLVMWithNoNamespaceFix)); EXPECT_EQ("namespace {\n" "int i;\n" "\n" "};", format("namespace {\n" "int i;\n" "\n" "};", LLVMWithNoNamespaceFix)); EXPECT_EQ("namespace {\n" "int i;\n" "};", format("namespace {\n" "int i;\n" "};", LLVMWithNoNamespaceFix)); EXPECT_EQ("namespace {\n" "int i;\n" "\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 (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" " if CONSTEXPR (c)\n" " g();\n" "h();"); verifyFormat("if constexpr (a)\n" " if constexpr (b) {\n" " f();\n" " }\n" "g();"); verifyFormat("if CONSTEXPR (a)\n" " if CONSTEXPR (b) {\n" " f();\n" " }\n" "g();"); FormatStyle AllowsMergedIf = getLLVMStyle(); AllowsMergedIf.AlignEscapedNewlines = FormatStyle::ENAS_Left; AllowsMergedIf.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_WithoutElse; 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, FormatIfWithoutCompoundStatementButElseWith) { FormatStyle AllowsMergedIf = getLLVMStyle(); AllowsMergedIf.AlignEscapedNewlines = FormatStyle::ENAS_Left; AllowsMergedIf.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_WithoutElse; verifyFormat("if (a)\n" " f();\n" "else {\n" " g();\n" "}", AllowsMergedIf); verifyFormat("if (a)\n" " f();\n" "else\n" " g();\n", AllowsMergedIf); AllowsMergedIf.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Always; verifyFormat("if (a) f();\n" "else {\n" " g();\n" "}", AllowsMergedIf); verifyFormat("if (a) f();\n" "else {\n" " if (a) f();\n" " else {\n" " g();\n" " }\n" " g();\n" "}", 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.ColumnLimit = 40; AllowSimpleBracedStatements.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always; AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_WithoutElse; AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = true; AllowSimpleBracedStatements.BreakBeforeBraces = FormatStyle::BS_Custom; AllowSimpleBracedStatements.BraceWrapping.AfterFunction = true; AllowSimpleBracedStatements.BraceWrapping.SplitEmptyRecord = false; verifyFormat("if (true) {}", AllowSimpleBracedStatements); verifyFormat("if constexpr (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("if CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements); verifyFormat("while (true) { f(); }", AllowSimpleBracedStatements); verifyFormat("for (;;) { f(); }", AllowSimpleBracedStatements); verifyFormat("if (true) {\n" " ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n" "}", 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 = FormatStyle::SIS_Never; verifyFormat("if (true) {}", AllowSimpleBracedStatements); verifyFormat("if (true) {\n" " f();\n" "}", AllowSimpleBracedStatements); verifyFormat("if (true) {\n" " f();\n" "} else {\n" " f();\n" "}", AllowSimpleBracedStatements); AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = false; verifyFormat("while (true) {}", AllowSimpleBracedStatements); verifyFormat("while (true) {\n" " f();\n" "}", AllowSimpleBracedStatements); verifyFormat("for (;;) {}", AllowSimpleBracedStatements); verifyFormat("for (;;) {\n" " f();\n" "}", AllowSimpleBracedStatements); AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_WithoutElse; AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = true; AllowSimpleBracedStatements.BraceWrapping.AfterControlStatement = true; verifyFormat("if (true) {}", AllowSimpleBracedStatements); verifyFormat("if constexpr (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("if CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements); verifyFormat("while (true) { f(); }", AllowSimpleBracedStatements); verifyFormat("for (;;) { f(); }", AllowSimpleBracedStatements); verifyFormat("if (true)\n" "{\n" " ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n" "}", AllowSimpleBracedStatements); verifyFormat("if (true)\n" "{ //\n" " f();\n" "}", AllowSimpleBracedStatements); verifyFormat("if (true)\n" "{\n" " f();\n" " f();\n" "}", AllowSimpleBracedStatements); verifyFormat("if (true)\n" "{\n" " f();\n" "} else\n" "{\n" " f();\n" "}", AllowSimpleBracedStatements); AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Never; verifyFormat("if (true) {}", AllowSimpleBracedStatements); verifyFormat("if (true)\n" "{\n" " f();\n" "}", AllowSimpleBracedStatements); verifyFormat("if (true)\n" "{\n" " f();\n" "} else\n" "{\n" " f();\n" "}", AllowSimpleBracedStatements); AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = false; verifyFormat("while (true) {}", AllowSimpleBracedStatements); verifyFormat("while (true)\n" "{\n" " f();\n" "}", AllowSimpleBracedStatements); verifyFormat("for (;;) {}", AllowSimpleBracedStatements); verifyFormat("for (;;)\n" "{\n" " f();\n" "}", AllowSimpleBracedStatements); } TEST_F(FormatTest, ShortBlocksInMacrosDontMergeWithCodeAfterMacro) { FormatStyle Style = getLLVMStyleWithColumns(60); Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always; Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_WithoutElse; Style.BreakBeforeBraces = FormatStyle::BS_Allman; EXPECT_EQ("#define A \\\n" " if (HANDLEwernufrnuLwrmviferuvnierv) \\\n" " { RET_ERR1_ANUIREUINERUIFNIOAerwfwrvnuier; }\n" "X;", format("#define A \\\n" " if (HANDLEwernufrnuLwrmviferuvnierv) { \\\n" " RET_ERR1_ANUIREUINERUIFNIOAerwfwrvnuier; \\\n" " }\n" "X;", Style)); } 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("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 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 constexpr (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n" " aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n" "}"); verifyFormat("if (a) {\n" "} else if CONSTEXPR (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)); 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) {"); // These should not be formatted as Objective-C for-in loops. verifyFormat("for (Foo *x = 0; x != in; x++) {\n}"); verifyFormat("Foo *x;\nfor (x = 0; x != in; x++) {\n}"); verifyFormat("Foo *x;\nfor (x in y) {\n}"); verifyFormat( "for (const Foo &baz = in.value(); !baz.at_end(); ++baz) {\n}"); 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); FormatStyle AlignLeft = getLLVMStyle(); AlignLeft.PointerAlignment = FormatStyle::PAS_Left; verifyFormat("for (A* a = start; a < end; ++a, ++value) {\n}", AlignLeft); } 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())); EXPECT_EQ("switch (n) {\n" "case 0: {\n" " return false;\n" "}\n" "default: {\n" " return true;\n" "}\n" "}", format("switch (n)\n" "{\n" "case 0: {\n" " return false;\n" "}\n" "default: {\n" " return true;\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)); FormatStyle Style = getLLVMStyle(); Style.IndentCaseLabels = true; Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never; Style.BreakBeforeBraces = FormatStyle::BS_Custom; Style.BraceWrapping.AfterCaseLabel = true; Style.BraceWrapping.AfterControlStatement = true; EXPECT_EQ("switch (n)\n" "{\n" " case 0:\n" " {\n" " return false;\n" " }\n" " default:\n" " {\n" " return true;\n" " }\n" "}", format("switch (n) {\n" " case 0: {\n" " return false;\n" " }\n" " default: {\n" " return true;\n" " }\n" "}", Style)); Style.BraceWrapping.AfterCaseLabel = false; EXPECT_EQ("switch (n)\n" "{\n" " case 0: {\n" " return false;\n" " }\n" " default: {\n" " return true;\n" " }\n" "}", format("switch (n) {\n" " case 0:\n" " {\n" " return false;\n" " }\n" " default:\n" " {\n" " return true;\n" " }\n" "}", Style)); } 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); Style.ColumnLimit = 80; Style.AllowShortCaseLabelsOnASingleLine = false; Style.IndentCaseLabels = true; EXPECT_EQ("switch (n) {\n" " default /*comments*/:\n" " return true;\n" " case 0:\n" " return false;\n" "}", format("switch (n) {\n" "default/*comments*/:\n" " return true;\n" "case 0:\n" " return false;\n" "}", Style)); Style.AllowShortCaseLabelsOnASingleLine = true; Style.BreakBeforeBraces = FormatStyle::BS_Custom; Style.BraceWrapping.AfterCaseLabel = true; Style.BraceWrapping.AfterControlStatement = true; EXPECT_EQ("switch (n)\n" "{\n" " case 0:\n" " {\n" " return false;\n" " }\n" " default:\n" " {\n" " return true;\n" " }\n" "}", format("switch (n) {\n" " case 0: {\n" " return false;\n" " }\n" " default:\n" " {\n" " return true;\n" " }\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" "}"); FormatStyle Style = getLLVMStyle(); Style.IndentGotoLabels = false; 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" "}", Style); verifyFormat("{\n" " some_code();\n" "test_label:\n" " some_other_code();\n" "}", Style); 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" "};"); verifyFormat("export 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" "};"); verifyGoogleFormat("export 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, BreakInheritanceStyle) { FormatStyle StyleWithInheritanceBreakBeforeComma = getLLVMStyle(); StyleWithInheritanceBreakBeforeComma.BreakInheritanceList = FormatStyle::BILS_BeforeComma; verifyFormat("class MyClass : public X {};", StyleWithInheritanceBreakBeforeComma); verifyFormat("class MyClass\n" " : public X\n" " , public Y {};", StyleWithInheritanceBreakBeforeComma); verifyFormat("class AAAAAAAAAAAAAAAAAAAAAA\n" " : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB\n" " , public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};", StyleWithInheritanceBreakBeforeComma); verifyFormat("struct aaaaaaaaaaaaa\n" " : public aaaaaaaaaaaaaaaaaaa< // break\n" " aaaaaaaaaaaaaaaa> {};", StyleWithInheritanceBreakBeforeComma); FormatStyle StyleWithInheritanceBreakAfterColon = getLLVMStyle(); StyleWithInheritanceBreakAfterColon.BreakInheritanceList = FormatStyle::BILS_AfterColon; verifyFormat("class MyClass : public X {};", StyleWithInheritanceBreakAfterColon); verifyFormat("class MyClass : public X, public Y {};", StyleWithInheritanceBreakAfterColon); verifyFormat("class AAAAAAAAAAAAAAAAAAAAAA :\n" " public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n" " public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};", StyleWithInheritanceBreakAfterColon); verifyFormat("struct aaaaaaaaaaaaa :\n" " public aaaaaaaaaaaaaaaaaaa< // break\n" " aaaaaaaaaaaaaaaa> {};", StyleWithInheritanceBreakAfterColon); } 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, FormatsTypedefEnum) { FormatStyle Style = getLLVMStyle(); Style.ColumnLimit = 40; verifyFormat("typedef enum {} EmptyEnum;"); verifyFormat("typedef enum { A, B, C } ShortEnum;"); verifyFormat("typedef enum {\n" " ZERO = 0,\n" " ONE = 1,\n" " TWO = 2,\n" " THREE = 3\n" "} LongEnum;", Style); Style.BreakBeforeBraces = FormatStyle::BS_Custom; Style.BraceWrapping.AfterEnum = true; verifyFormat("typedef enum {} EmptyEnum;"); verifyFormat("typedef enum { A, B, C } ShortEnum;"); verifyFormat("typedef enum\n" "{\n" " ZERO = 0,\n" " ONE = 1,\n" " TWO = 2,\n" " THREE = 3\n" "} LongEnum;", Style); } TEST_F(FormatTest, FormatsNSEnums) { verifyGoogleFormat("typedef NS_ENUM(NSInteger, SomeName) { AAA, BBB }"); verifyGoogleFormat( "typedef NS_CLOSED_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_CLOSED_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_CLOSED_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::inline D {\n" "class A {};\n" "void f() { f(); }\n" "}", LLVMWithNoNamespaceFix); verifyFormat("namespace N::inline D::E {\n" "class A {};\n" "void f() { f(); }\n" "}", LLVMWithNoNamespaceFix); verifyFormat("namespace [[deprecated(\"foo[bar\")]] some_namespace {\n" "class A {};\n" "void f() { f(); }\n" "}", LLVMWithNoNamespaceFix); verifyFormat("/* something */ namespace some_namespace {\n" "class A {};\n" "void f() { f(); }\n" "}", LLVMWithNoNamespaceFix); verifyFormat("namespace {\n" "class A {};\n" "void f() { f(); }\n" "}", LLVMWithNoNamespaceFix); verifyFormat("/* something */ namespace {\n" "class A {};\n" "void f() { f(); }\n" "}", LLVMWithNoNamespaceFix); verifyFormat("inline namespace X {\n" "class A {};\n" "void f() { f(); }\n" "}", LLVMWithNoNamespaceFix); verifyFormat("/* something */ inline namespace X {\n" "class A {};\n" "void f() { f(); }\n" "}", LLVMWithNoNamespaceFix); verifyFormat("export 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, NamespaceMacros) { FormatStyle Style = getLLVMStyle(); Style.NamespaceMacros.push_back("TESTSUITE"); verifyFormat("TESTSUITE(A) {\n" "int foo();\n" "} // TESTSUITE(A)", Style); verifyFormat("TESTSUITE(A, B) {\n" "int foo();\n" "} // TESTSUITE(A)", Style); // Properly indent according to NamespaceIndentation style Style.NamespaceIndentation = FormatStyle::NI_All; verifyFormat("TESTSUITE(A) {\n" " int foo();\n" "} // TESTSUITE(A)", Style); verifyFormat("TESTSUITE(A) {\n" " namespace B {\n" " int foo();\n" " } // namespace B\n" "} // TESTSUITE(A)", Style); verifyFormat("namespace A {\n" " TESTSUITE(B) {\n" " int foo();\n" " } // TESTSUITE(B)\n" "} // namespace A", Style); Style.NamespaceIndentation = FormatStyle::NI_Inner; verifyFormat("TESTSUITE(A) {\n" "TESTSUITE(B) {\n" " int foo();\n" "} // TESTSUITE(B)\n" "} // TESTSUITE(A)", Style); verifyFormat("TESTSUITE(A) {\n" "namespace B {\n" " int foo();\n" "} // namespace B\n" "} // TESTSUITE(A)", Style); verifyFormat("namespace A {\n" "TESTSUITE(B) {\n" " int foo();\n" "} // TESTSUITE(B)\n" "} // namespace A", Style); // Properly merge namespace-macros blocks in CompactNamespaces mode Style.NamespaceIndentation = FormatStyle::NI_None; Style.CompactNamespaces = true; verifyFormat("TESTSUITE(A) { TESTSUITE(B) {\n" "}} // TESTSUITE(A::B)", Style); EXPECT_EQ("TESTSUITE(out) { TESTSUITE(in) {\n" "}} // TESTSUITE(out::in)", format("TESTSUITE(out) {\n" "TESTSUITE(in) {\n" "} // TESTSUITE(in)\n" "} // TESTSUITE(out)", Style)); EXPECT_EQ("TESTSUITE(out) { TESTSUITE(in) {\n" "}} // TESTSUITE(out::in)", format("TESTSUITE(out) {\n" "TESTSUITE(in) {\n" "} // TESTSUITE(in)\n" "} // TESTSUITE(out)", Style)); // Do not merge different namespaces/macros EXPECT_EQ("namespace out {\n" "TESTSUITE(in) {\n" "} // TESTSUITE(in)\n" "} // namespace out", format("namespace out {\n" "TESTSUITE(in) {\n" "} // TESTSUITE(in)\n" "} // namespace out", Style)); EXPECT_EQ("TESTSUITE(out) {\n" "namespace in {\n" "} // namespace in\n" "} // TESTSUITE(out)", format("TESTSUITE(out) {\n" "namespace in {\n" "} // namespace in\n" "} // TESTSUITE(out)", Style)); Style.NamespaceMacros.push_back("FOOBAR"); EXPECT_EQ("TESTSUITE(out) {\n" "FOOBAR(in) {\n" "} // FOOBAR(in)\n" "} // TESTSUITE(out)", format("TESTSUITE(out) {\n" "FOOBAR(in) {\n" "} // FOOBAR(in)\n" "} // TESTSUITE(out)", Style)); } TEST_F(FormatTest, FormatsCompactNamespaces) { FormatStyle Style = getLLVMStyle(); Style.CompactNamespaces = true; Style.NamespaceMacros.push_back("TESTSUITE"); 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;"); verifyFormat("extern \"C\" {}"); verifyFormat("extern \"C\" {\n" "int foo();\n" "}"); verifyFormat("extern \"C\" int foo() {}"); verifyFormat("extern \"C\" int foo();"); verifyFormat("extern \"C\" int foo() {\n" " int i = 42;\n" " return i;\n" "}"); FormatStyle Style = getLLVMStyle(); Style.BreakBeforeBraces = FormatStyle::BS_Custom; Style.BraceWrapping.AfterFunction = true; verifyFormat("extern \"C\" int foo() {}", Style); verifyFormat("extern \"C\" int foo();", Style); verifyFormat("extern \"C\" int foo()\n" "{\n" " int i = 42;\n" " return i;\n" "}", Style); Style.BraceWrapping.AfterExternBlock = true; Style.BraceWrapping.SplitEmptyRecord = false; verifyFormat("extern \"C\"\n" "{}", Style); verifyFormat("extern \"C\"\n" "{\n" " int foo();\n" "}", Style); } 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_Whitesmiths; verifyFormat("try\n" " {\n" " // something white\n" " }\n" "catch (...)\n" " {\n" " // something white\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)")); FormatStyle Style = getLLVMStyle(); Style.SpaceBeforeParens = FormatStyle::SBPO_Never; verifyFormat("#define true ((foo)1)", Style); Style.SpaceBeforeParens = FormatStyle::SBPO_Always; verifyFormat("#define false((foo)0)", Style); } 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)); // See PR41483 EXPECT_EQ("/**/ FOO(a)\n" "FOO(b)", format("/**/ FOO(a)\n" "FOO(b)")); } 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" "};")); FormatStyle Style = getLLVMStyle(); Style.BreakBeforeBraces = FormatStyle::BS_Custom; Style.BraceWrapping.AfterControlStatement = true; Style.BraceWrapping.AfterFunction = true; EXPECT_EQ("void f()\n" "try\n" "{\n" "}", format("void f() try {\n" "}", Style)); 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(>)"); // Some macros contain an implicit semicolon. Style = getLLVMStyle(); Style.StatementMacros.push_back("FOO"); verifyFormat("FOO(a) int b = 0;"); verifyFormat("FOO(a)\n" "int b = 0;", Style); verifyFormat("FOO(a);\n" "int b = 0;", Style); verifyFormat("FOO(argc, argv, \"4.0.2\")\n" "int b = 0;", Style); verifyFormat("FOO()\n" "int b = 0;", Style); verifyFormat("FOO\n" "int b = 0;", Style); verifyFormat("void f() {\n" " FOO(a)\n" " return a;\n" "}", Style); verifyFormat("FOO(a)\n" "FOO(b)", Style); verifyFormat("int a = 0;\n" "FOO(b)\n" "int c = 0;", Style); verifyFormat("int a = 0;\n" "int x = FOO(a)\n" "int b = 0;", Style); verifyFormat("void foo(int a) { FOO(a) }\n" "uint32_t bar() {}", Style); } TEST_F(FormatTest, LayoutMacroDefinitionsStatementsSpanningBlocks) { verifyFormat("#define A \\\n" " f({ \\\n" " g(); \\\n" " });", getLLVMStyleWithColumns(11)); } TEST_F(FormatTest, IndentPreprocessorDirectives) { FormatStyle Style = getLLVMStyle(); Style.IndentPPDirectives = FormatStyle::PPDIS_None; Style.ColumnLimit = 40; verifyFormat("#ifdef _WIN32\n" "#define A 0\n" "#ifdef VAR2\n" "#define B 1\n" "#include \n" "#define MACRO \\\n" " some_very_long_func_aaaaaaaaaa();\n" "#endif\n" "#else\n" "#define A 1\n" "#endif", Style); Style.IndentPPDirectives = FormatStyle::PPDIS_AfterHash; verifyFormat("#ifdef _WIN32\n" "# define A 0\n" "# ifdef VAR2\n" "# define B 1\n" "# include \n" "# define MACRO \\\n" " some_very_long_func_aaaaaaaaaa();\n" "# endif\n" "#else\n" "# define A 1\n" "#endif", Style); verifyFormat("#if A\n" "# define MACRO \\\n" " void a(int x) { \\\n" " b(); \\\n" " c(); \\\n" " d(); \\\n" " e(); \\\n" " f(); \\\n" " }\n" "#endif", Style); // Comments before include guard. verifyFormat("// file comment\n" "// file comment\n" "#ifndef HEADER_H\n" "#define HEADER_H\n" "code();\n" "#endif", Style); // Test with include guards. verifyFormat("#ifndef HEADER_H\n" "#define HEADER_H\n" "code();\n" "#endif", Style); // Include guards must have a #define with the same variable immediately // after #ifndef. verifyFormat("#ifndef NOT_GUARD\n" "# define FOO\n" "code();\n" "#endif", Style); // Include guards must cover the entire file. verifyFormat("code();\n" "code();\n" "#ifndef NOT_GUARD\n" "# define NOT_GUARD\n" "code();\n" "#endif", Style); verifyFormat("#ifndef NOT_GUARD\n" "# define NOT_GUARD\n" "code();\n" "#endif\n" "code();", Style); // Test with trailing blank lines. verifyFormat("#ifndef HEADER_H\n" "#define HEADER_H\n" "code();\n" "#endif\n", Style); // Include guards don't have #else. verifyFormat("#ifndef NOT_GUARD\n" "# define NOT_GUARD\n" "code();\n" "#else\n" "#endif", Style); verifyFormat("#ifndef NOT_GUARD\n" "# define NOT_GUARD\n" "code();\n" "#elif FOO\n" "#endif", Style); // Non-identifier #define after potential include guard. verifyFormat("#ifndef FOO\n" "# define 1\n" "#endif\n", Style); // #if closes past last non-preprocessor line. verifyFormat("#ifndef FOO\n" "#define FOO\n" "#if 1\n" "int i;\n" "# define A 0\n" "#endif\n" "#endif\n", Style); // Don't crash if there is an #elif directive without a condition. verifyFormat("#if 1\n" "int x;\n" "#elif\n" "int y;\n" "#else\n" "int z;\n" "#endif", Style); // FIXME: This doesn't handle the case where there's code between the // #ifndef and #define but all other conditions hold. This is because when // the #define line is parsed, UnwrappedLineParser::Lines doesn't hold the // previous code line yet, so we can't detect it. EXPECT_EQ("#ifndef NOT_GUARD\n" "code();\n" "#define NOT_GUARD\n" "code();\n" "#endif", format("#ifndef NOT_GUARD\n" "code();\n" "# define NOT_GUARD\n" "code();\n" "#endif", Style)); // FIXME: This doesn't handle cases where legitimate preprocessor lines may // be outside an include guard. Examples are #pragma once and // #pragma GCC diagnostic, or anything else that does not change the meaning // of the file if it's included multiple times. EXPECT_EQ("#ifdef WIN32\n" "# pragma once\n" "#endif\n" "#ifndef HEADER_H\n" "# define HEADER_H\n" "code();\n" "#endif", format("#ifdef WIN32\n" "# pragma once\n" "#endif\n" "#ifndef HEADER_H\n" "#define HEADER_H\n" "code();\n" "#endif", Style)); // FIXME: This does not detect when there is a single non-preprocessor line // in front of an include-guard-like structure where other conditions hold // because ScopedLineState hides the line. EXPECT_EQ("code();\n" "#ifndef HEADER_H\n" "#define HEADER_H\n" "code();\n" "#endif", format("code();\n" "#ifndef HEADER_H\n" "# define HEADER_H\n" "code();\n" "#endif", Style)); // Keep comments aligned with #, otherwise indent comments normally. These // tests cannot use verifyFormat because messUp manipulates leading // whitespace. { const char *Expected = "" "void f() {\n" "#if 1\n" "// Preprocessor aligned.\n" "# define A 0\n" " // Code. Separated by blank line.\n" "\n" "# define B 0\n" " // Code. Not aligned with #\n" "# define C 0\n" "#endif"; const char *ToFormat = "" "void f() {\n" "#if 1\n" "// Preprocessor aligned.\n" "# define A 0\n" "// Code. Separated by blank line.\n" "\n" "# define B 0\n" " // Code. Not aligned with #\n" "# define C 0\n" "#endif"; EXPECT_EQ(Expected, format(ToFormat, Style)); EXPECT_EQ(Expected, format(Expected, Style)); } // Keep block quotes aligned. { const char *Expected = "" "void f() {\n" "#if 1\n" "/* Preprocessor aligned. */\n" "# define A 0\n" " /* Code. Separated by blank line. */\n" "\n" "# define B 0\n" " /* Code. Not aligned with # */\n" "# define C 0\n" "#endif"; const char *ToFormat = "" "void f() {\n" "#if 1\n" "/* Preprocessor aligned. */\n" "# define A 0\n" "/* Code. Separated by blank line. */\n" "\n" "# define B 0\n" " /* Code. Not aligned with # */\n" "# define C 0\n" "#endif"; EXPECT_EQ(Expected, format(ToFormat, Style)); EXPECT_EQ(Expected, format(Expected, Style)); } // Keep comments aligned with un-indented directives. { const char *Expected = "" "void f() {\n" "// Preprocessor aligned.\n" "#define A 0\n" " // Code. Separated by blank line.\n" "\n" "#define B 0\n" " // Code. Not aligned with #\n" "#define C 0\n"; const char *ToFormat = "" "void f() {\n" "// Preprocessor aligned.\n" "#define A 0\n" "// Code. Separated by blank line.\n" "\n" "#define B 0\n" " // Code. Not aligned with #\n" "#define C 0\n"; EXPECT_EQ(Expected, format(ToFormat, Style)); EXPECT_EQ(Expected, format(Expected, Style)); } // Test AfterHash with tabs. { FormatStyle Tabbed = Style; Tabbed.UseTab = FormatStyle::UT_Always; Tabbed.IndentWidth = 8; Tabbed.TabWidth = 8; verifyFormat("#ifdef _WIN32\n" "#\tdefine A 0\n" "#\tifdef VAR2\n" "#\t\tdefine B 1\n" "#\t\tinclude \n" "#\t\tdefine MACRO \\\n" "\t\t\tsome_very_long_func_aaaaaaaaaa();\n" "#\tendif\n" "#else\n" "#\tdefine A 1\n" "#endif", Tabbed); } // Regression test: Multiline-macro inside include guards. verifyFormat("#ifndef HEADER_H\n" "#define HEADER_H\n" "#define A() \\\n" " int i; \\\n" " int j;\n" "#endif // HEADER_H", getLLVMStyleWithColumns(20)); Style.IndentPPDirectives = FormatStyle::PPDIS_BeforeHash; // Basic before hash indent tests verifyFormat("#ifdef _WIN32\n" " #define A 0\n" " #ifdef VAR2\n" " #define B 1\n" " #include \n" " #define MACRO \\\n" " some_very_long_func_aaaaaaaaaa();\n" " #endif\n" "#else\n" " #define A 1\n" "#endif", Style); verifyFormat("#if A\n" " #define MACRO \\\n" " void a(int x) { \\\n" " b(); \\\n" " c(); \\\n" " d(); \\\n" " e(); \\\n" " f(); \\\n" " }\n" "#endif", Style); // Keep comments aligned with indented directives. These // tests cannot use verifyFormat because messUp manipulates leading // whitespace. { const char *Expected = "void f() {\n" "// Aligned to preprocessor.\n" "#if 1\n" " // Aligned to code.\n" " int a;\n" " #if 1\n" " // Aligned to preprocessor.\n" " #define A 0\n" " // Aligned to code.\n" " int b;\n" " #endif\n" "#endif\n" "}"; const char *ToFormat = "void f() {\n" "// Aligned to preprocessor.\n" "#if 1\n" "// Aligned to code.\n" "int a;\n" "#if 1\n" "// Aligned to preprocessor.\n" "#define A 0\n" "// Aligned to code.\n" "int b;\n" "#endif\n" "#endif\n" "}"; EXPECT_EQ(Expected, format(ToFormat, Style)); EXPECT_EQ(Expected, format(Expected, Style)); } { const char *Expected = "void f() {\n" "/* Aligned to preprocessor. */\n" "#if 1\n" " /* Aligned to code. */\n" " int a;\n" " #if 1\n" " /* Aligned to preprocessor. */\n" " #define A 0\n" " /* Aligned to code. */\n" " int b;\n" " #endif\n" "#endif\n" "}"; const char *ToFormat = "void f() {\n" "/* Aligned to preprocessor. */\n" "#if 1\n" "/* Aligned to code. */\n" "int a;\n" "#if 1\n" "/* Aligned to preprocessor. */\n" "#define A 0\n" "/* Aligned to code. */\n" "int b;\n" "#endif\n" "#endif\n" "}"; EXPECT_EQ(Expected, format(ToFormat, Style)); EXPECT_EQ(Expected, format(Expected, Style)); } // Test single comment before preprocessor verifyFormat("// Comment\n" "\n" "#if 1\n" "#endif", Style); } 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) { FormatStyle Narrow = getLLVMStyleWithColumns(11); EXPECT_EQ("#define A \\\n int i; \\\n int j;", format("#define A \\\nint i;\\\n int j;", Narrow)); 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 AlignLeft = getLLVMStyle(); AlignLeft.AlignEscapedNewlines = FormatStyle::ENAS_Left; EXPECT_EQ("#define MACRO(x) \\\n" "private: \\\n" " int x(int a);\n", format("#define MACRO(x) \\\n" "private: \\\n" " int x(int a);\n", AlignLeft)); // CRLF line endings EXPECT_EQ("#define A \\\r\n int i; \\\r\n int j;", format("#define A \\\r\nint i;\\\r\n int j;", Narrow)); EXPECT_EQ("#define A\r\n\r\nint i;", format("#define A \\\r\n\r\n int i;")); EXPECT_EQ("template f();", format("\\\ntemplate f();")); EXPECT_EQ("/* \\ \\ \\\r\n */", format("\\\r\n/* \\ \\ \\\r\n */")); EXPECT_EQ("", format("")); EXPECT_EQ("#define MACRO(x) \\\r\n" "private: \\\r\n" " int x(int a);\r\n", format("#define MACRO(x) \\\r\n" "private: \\\r\n" " int x(int a);\r\n", AlignLeft)); 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 = FormatStyle::SIS_WithoutElse; 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(\n" " 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 {}"); FormatStyle Style = getLLVMStyle(); Style.SpaceInEmptyBlock = true; EXPECT_EQ("void f() { }", format("void f() {}", Style)); Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty; EXPECT_EQ("while (true) { }", format("while (true) {}", Style)); } 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("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" "}"); verifyFormat( "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\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" "}"); 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 constexpr (aaaaa && bbbbb > // break\n" " ccccc) {\n" "}"); verifyFormat("if () {\n" "} else if CONSTEXPR (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); Style.ColumnLimit = 80; Style.IndentWidth = 4; Style.TabWidth = 4; Style.UseTab = FormatStyle::UT_Always; Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign; Style.AlignOperands = false; EXPECT_EQ("return someVeryVeryLongConditionThatBarelyFitsOnALine\n" "\t&& (someOtherLongishConditionPart1\n" "\t\t|| someOtherEvenLongerNestedConditionPart2);", format("return someVeryVeryLongConditionThatBarelyFitsOnALine && " "(someOtherLongishConditionPart1 || " "someOtherEvenLongerNestedConditionPart2);", 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, AllowAllConstructorInitializersOnNextLine) { FormatStyle Style = getLLVMStyle(); Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; Style.ColumnLimit = 60; Style.ConstructorInitializerAllOnOneLineOrOnePerLine = true; Style.AllowAllConstructorInitializersOnNextLine = true; Style.BinPackParameters = false; for (int i = 0; i < 4; ++i) { // Test all combinations of parameters that should not have an effect. Style.AllowAllParametersOfDeclarationOnNextLine = i & 1; Style.AllowAllArgumentsOnNextLine = i & 2; Style.AllowAllConstructorInitializersOnNextLine = true; Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; verifyFormat("Constructor()\n" " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", Style); verifyFormat("Constructor() : a(a), b(b) {}", Style); Style.AllowAllConstructorInitializersOnNextLine = false; verifyFormat("Constructor()\n" " : aaaaaaaaaaaaaaaaaaaa(a)\n" " , bbbbbbbbbbbbbbbbbbbbb(b) {}", Style); verifyFormat("Constructor() : a(a), b(b) {}", Style); Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon; Style.AllowAllConstructorInitializersOnNextLine = true; verifyFormat("Constructor()\n" " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", Style); Style.AllowAllConstructorInitializersOnNextLine = false; verifyFormat("Constructor()\n" " : aaaaaaaaaaaaaaaaaaaa(a),\n" " bbbbbbbbbbbbbbbbbbbbb(b) {}", Style); Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon; Style.AllowAllConstructorInitializersOnNextLine = true; verifyFormat("Constructor() :\n" " aaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", Style); Style.AllowAllConstructorInitializersOnNextLine = false; verifyFormat("Constructor() :\n" " aaaaaaaaaaaaaaaaaa(a),\n" " bbbbbbbbbbbbbbbbbbbbb(b) {}", Style); } // Test interactions between AllowAllParametersOfDeclarationOnNextLine and // AllowAllConstructorInitializersOnNextLine in all // BreakConstructorInitializers modes Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma; Style.AllowAllParametersOfDeclarationOnNextLine = true; Style.AllowAllConstructorInitializersOnNextLine = false; verifyFormat("SomeClassWithALongName::Constructor(\n" " int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb)\n" " : aaaaaaaaaaaaaaaaaaaa(a)\n" " , bbbbbbbbbbbbbbbbbbbbb(b) {}", Style); Style.AllowAllConstructorInitializersOnNextLine = true; verifyFormat("SomeClassWithALongName::Constructor(\n" " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" " int bbbbbbbbbbbbb,\n" " int cccccccccccccccc)\n" " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", Style); Style.AllowAllParametersOfDeclarationOnNextLine = false; Style.AllowAllConstructorInitializersOnNextLine = false; verifyFormat("SomeClassWithALongName::Constructor(\n" " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" " int bbbbbbbbbbbbb)\n" " : aaaaaaaaaaaaaaaaaaaa(a)\n" " , bbbbbbbbbbbbbbbbbbbbb(b) {}", Style); Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon; Style.AllowAllParametersOfDeclarationOnNextLine = true; verifyFormat("SomeClassWithALongName::Constructor(\n" " int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb)\n" " : aaaaaaaaaaaaaaaaaaaa(a),\n" " bbbbbbbbbbbbbbbbbbbbb(b) {}", Style); Style.AllowAllConstructorInitializersOnNextLine = true; verifyFormat("SomeClassWithALongName::Constructor(\n" " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" " int bbbbbbbbbbbbb,\n" " int cccccccccccccccc)\n" " : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", Style); Style.AllowAllParametersOfDeclarationOnNextLine = false; Style.AllowAllConstructorInitializersOnNextLine = false; verifyFormat("SomeClassWithALongName::Constructor(\n" " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" " int bbbbbbbbbbbbb)\n" " : aaaaaaaaaaaaaaaaaaaa(a),\n" " bbbbbbbbbbbbbbbbbbbbb(b) {}", Style); Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon; Style.AllowAllParametersOfDeclarationOnNextLine = true; verifyFormat("SomeClassWithALongName::Constructor(\n" " int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb) :\n" " aaaaaaaaaaaaaaaaaaaa(a),\n" " bbbbbbbbbbbbbbbbbbbbb(b) {}", Style); Style.AllowAllConstructorInitializersOnNextLine = true; verifyFormat("SomeClassWithALongName::Constructor(\n" " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" " int bbbbbbbbbbbbb,\n" " int cccccccccccccccc) :\n" " aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}", Style); Style.AllowAllParametersOfDeclarationOnNextLine = false; Style.AllowAllConstructorInitializersOnNextLine = false; verifyFormat("SomeClassWithALongName::Constructor(\n" " int aaaaaaaaaaaaaaaaaaaaaaaa,\n" " int bbbbbbbbbbbbb) :\n" " aaaaaaaaaaaaaaaaaaaa(a),\n" " bbbbbbbbbbbbbbbbbbbbb(b) {}", Style); } TEST_F(FormatTest, AllowAllArgumentsOnNextLine) { FormatStyle Style = getLLVMStyle(); Style.ColumnLimit = 60; Style.BinPackArguments = false; for (int i = 0; i < 4; ++i) { // Test all combinations of parameters that should not have an effect. Style.AllowAllParametersOfDeclarationOnNextLine = i & 1; Style.AllowAllConstructorInitializersOnNextLine = i & 2; Style.AllowAllArgumentsOnNextLine = true; verifyFormat("void foo() {\n" " FunctionCallWithReallyLongName(\n" " aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbb);\n" "}", Style); Style.AllowAllArgumentsOnNextLine = false; verifyFormat("void foo() {\n" " FunctionCallWithReallyLongName(\n" " aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" " bbbbbbbbbbbb);\n" "}", Style); Style.AllowAllArgumentsOnNextLine = true; verifyFormat("void foo() {\n" " auto VariableWithReallyLongName = {\n" " aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbb};\n" "}", Style); Style.AllowAllArgumentsOnNextLine = false; verifyFormat("void foo() {\n" " auto VariableWithReallyLongName = {\n" " aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" " bbbbbbbbbbbb};\n" "}", Style); } // This parameter should not affect declarations. Style.BinPackParameters = false; Style.AllowAllArgumentsOnNextLine = false; Style.AllowAllParametersOfDeclarationOnNextLine = true; verifyFormat("void FunctionCallWithReallyLongName(\n" " int aaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbb);", Style); Style.AllowAllParametersOfDeclarationOnNextLine = false; verifyFormat("void FunctionCallWithReallyLongName(\n" " int aaaaaaaaaaaaaaaaaaaaaaa,\n" " int bbbbbbbbbbbb);", Style); } 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)); Style.ConstructorInitializerAllOnOneLineOrOnePerLine = true; verifyFormat( "SomeClass::Constructor() :\n" " aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}", Style); Style.ConstructorInitializerAllOnOneLineOrOnePerLine = false; 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.AllowAllConstructorInitializersOnNextLine = 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); // `ConstructorInitializerIndentWidth` actually applies to InheritanceList as // well Style.BreakInheritanceList = FormatStyle::BILS_BeforeColon; verifyFormat( "class SomeClass\n" " : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" " public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};", Style); Style.BreakInheritanceList = FormatStyle::BILS_BeforeComma; verifyFormat( "class SomeClass\n" " : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n" " , public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};", Style); Style.BreakInheritanceList = FormatStyle::BILS_AfterColon; verifyFormat( "class SomeClass :\n" " public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n" " public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};", Style); } #ifndef EXPENSIVE_CHECKS // Expensive checks enables libstdc++ checking which includes validating the // state of ranges used in std::priority_queue - this blows out the // runtime/scalability of the function and makes this test unacceptably slow. 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); } #endif 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, DontBreakBeforeQualifiedOperator) { // Regression test for https://bugs.llvm.org/show_bug.cgi?id=40516: // Prefer keeping `::` followed by `operator` together. EXPECT_EQ("const aaaa::bbbbbbb &\n" "ccccccccc::operator++() {\n" " stuff();\n" "}", format("const aaaa::bbbbbbb\n" "&ccccccccc::operator++() { stuff(); }", getLLVMStyleWithColumns(40))); } 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); Style.BreakBeforeBraces = FormatStyle::BS_Whitesmiths; 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);"); // Dont break if only closing statements before member call verifyFormat("test() {\n" " ([]() -> {\n" " int b = 32;\n" " return 3;\n" " }).foo();\n" "}"); verifyFormat("test() {\n" " (\n" " []() -> {\n" " int b = 32;\n" " return 3;\n" " },\n" " foo, bar)\n" " .foo();\n" "}"); verifyFormat("test() {\n" " ([]() -> {\n" " int b = 32;\n" " return 3;\n" " })\n" " .foo()\n" " .bar();\n" "}"); verifyFormat("test() {\n" " ([]() -> {\n" " int b = 32;\n" " return 3;\n" " })\n" " .foo(\"aaaaaaaaaaaaaaaaa\"\n" " \"bbbb\");\n" "}", getLLVMStyleWithColumns(30)); } 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); verifyFormat("int\n" "foo(A a)\n" "{\n" " return a;\n" "}\n", Style); verifyFormat("int\n" "foo(A<8> a)\n" "{\n" " return a;\n" "}\n", Style); verifyFormat("int\n" "foo(A, 8> a)\n" "{\n" " return a;\n" "}\n", Style); verifyFormat("int\n" "foo(A, bool> a)\n" "{\n" " return a;\n" "}\n", Style); verifyFormat("int\n" "foo(A, bool> a)\n" "{\n" " return a;\n" "}\n", Style); verifyFormat("int\n" "foo(A, 8> a)\n" "{\n" " return a;\n" "}\n", Style); Style = getGNUStyle(); // Test for comments at the end of function declarations. verifyFormat("void\n" "foo (int a, /*abc*/ int b) // def\n" "{\n" "}\n", Style); verifyFormat("void\n" "foo (int a, /* abc */ int b) /* def */\n" "{\n" "}\n", Style); // Definitions that should not break after return type verifyFormat("void foo (int a, int b); // def\n", Style); verifyFormat("void foo (int a, int b); /* def */\n", Style); verifyFormat("void foo (int a, int b);\n", 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 = FormatStyle::BTDS_Yes; verifyFormat("template \nclass C {};", AlwaysBreak); verifyFormat("template \nvoid f();", AlwaysBreak); verifyFormat("template \nvoid f() {}", AlwaysBreak); verifyFormat("void aaaaaaaaaaaaaaaaaaa(\n" " ccccccccccccccccccccccccccccccccccccccccccccccc);"); verifyFormat("template